text
stringlengths
81
477k
file_path
stringlengths
22
92
module
stringlengths
13
87
token_count
int64
24
94.8k
has_source_code
bool
1 class
// File: crates/hyperswitch_domain_models/src/ext_traits.rs // Module: hyperswitch_domain_models::src::ext_traits use common_utils::{ errors::{self, CustomResult}, ext_traits::ValueExt, fp_utils::when, }; use error_stack::ResultExt; use crate::errors::api_error_response; pub type DomainResult<T> = CustomResult<T, api_error_response::ApiErrorResponse>; pub trait OptionExt<T> { fn check_value_present(&self, field_name: &'static str) -> DomainResult<()>; fn get_required_value(self, field_name: &'static str) -> DomainResult<T>; fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError> where T: AsRef<str>, E: std::str::FromStr, // Requirement for converting the `Err` variant of `FromStr` to `Report<Err>` <E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static; fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError> where T: ValueExt, U: serde::de::DeserializeOwned; fn update_value(&mut self, value: Option<T>); } impl<T> OptionExt<T> for Option<T> { fn check_value_present(&self, field_name: &'static str) -> DomainResult<()> { when(self.is_none(), || { Err(error_stack::Report::new( api_error_response::ApiErrorResponse::MissingRequiredField { field_name }, ) .attach_printable(format!("Missing required field {field_name}"))) }) } // This will allow the error message that was generated in this function to point to the call site #[track_caller] fn get_required_value(self, field_name: &'static str) -> DomainResult<T> { match self { Some(v) => Ok(v), None => Err(error_stack::Report::new( api_error_response::ApiErrorResponse::MissingRequiredField { field_name }, ) .attach_printable(format!("Missing required field {field_name}"))), } } fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError> where T: AsRef<str>, E: std::str::FromStr, <E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static, { let value = self .get_required_value(enum_name) .change_context(errors::ParsingError::UnknownError)?; E::from_str(value.as_ref()) .change_context(errors::ParsingError::UnknownError) .attach_printable_lazy(|| format!("Invalid {{ {enum_name} }} ")) } fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError> where T: ValueExt, U: serde::de::DeserializeOwned, { let value = self .get_required_value(type_name) .change_context(errors::ParsingError::UnknownError)?; value.parse_value(type_name) } fn update_value(&mut self, value: Self) { if let Some(a) = value { *self = Some(a) } } }
crates/hyperswitch_domain_models/src/ext_traits.rs
hyperswitch_domain_models::src::ext_traits
733
true
// File: crates/hyperswitch_domain_models/src/consts.rs // Module: hyperswitch_domain_models::src::consts //! Constants that are used in the domain models. use std::{collections::HashSet, sync::LazyLock}; pub static ROUTING_ENABLED_PAYMENT_METHODS: LazyLock<HashSet<common_enums::PaymentMethod>> = LazyLock::new(|| { let mut set = HashSet::new(); set.insert(common_enums::PaymentMethod::BankTransfer); set.insert(common_enums::PaymentMethod::BankDebit); set.insert(common_enums::PaymentMethod::BankRedirect); set }); pub static ROUTING_ENABLED_PAYMENT_METHOD_TYPES: LazyLock< HashSet<common_enums::PaymentMethodType>, > = LazyLock::new(|| { let mut set = HashSet::new(); set.insert(common_enums::PaymentMethodType::GooglePay); set.insert(common_enums::PaymentMethodType::ApplePay); set.insert(common_enums::PaymentMethodType::Klarna); set.insert(common_enums::PaymentMethodType::Paypal); set.insert(common_enums::PaymentMethodType::SamsungPay); set }); /// Length of the unique reference ID generated for connector mandate requests pub const CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH: usize = 18;
crates/hyperswitch_domain_models/src/consts.rs
hyperswitch_domain_models::src::consts
278
true
// File: crates/hyperswitch_domain_models/src/router_request_types.rs // Module: hyperswitch_domain_models::src::router_request_types pub mod authentication; pub mod fraud_check; pub mod revenue_recovery; pub mod subscriptions; pub mod unified_authentication_service; use api_models::payments::{AdditionalPaymentData, AddressDetails, RequestSurchargeDetails}; use common_types::payments as common_payments_types; use common_utils::{consts, errors, ext_traits::OptionExt, id_type, pii, types::MinorUnit}; use diesel_models::{enums as storage_enums, types::OrderDetailsWithAmount}; use error_stack::ResultExt; use masking::Secret; use serde::Serialize; use serde_with::serde_as; use super::payment_method_data::PaymentMethodData; use crate::{ address, errors::api_error_response::{ApiErrorResponse, NotImplementedMessage}, mandates, payment_method_data::ExternalVaultPaymentMethodData, payments, router_data::{self, AccessTokenAuthenticationResponse, RouterData}, router_flow_types as flows, router_response_types as response_types, vault::PaymentMethodVaultingData, }; #[derive(Debug, Clone, Serialize)] pub struct PaymentsAuthorizeData { pub payment_method_data: PaymentMethodData, /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount) /// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately /// ```text /// get_original_amount() /// get_surcharge_amount() /// get_tax_on_surcharge_amount() /// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount /// ``` pub amount: i64, pub order_tax_amount: Option<MinorUnit>, pub email: Option<pii::Email>, pub customer_name: Option<Secret<String>>, pub currency: storage_enums::Currency, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, pub statement_descriptor: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub router_return_url: Option<String>, pub webhook_url: Option<String>, pub complete_authorize_url: Option<String>, // Mandates pub setup_future_usage: Option<storage_enums::FutureUsage>, pub mandate_id: Option<api_models::payments::MandateIds>, pub off_session: Option<bool>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub setup_mandate_details: Option<mandates::MandateData>, pub browser_info: Option<BrowserInformation>, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub order_category: Option<String>, pub session_token: Option<String>, pub enrolled_for_3ds: bool, pub related_transaction_id: Option<String>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub surcharge_details: Option<SurchargeDetails>, pub customer_id: Option<id_type::CustomerId>, pub request_incremental_authorization: bool, pub metadata: Option<serde_json::Value>, pub authentication_data: Option<AuthenticationData>, pub request_extended_authorization: Option<common_types::primitive_wrappers::RequestExtendedAuthorizationBool>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, // New amount for amount frame work pub minor_amount: MinorUnit, /// 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. pub merchant_order_reference_id: Option<String>, pub integrity_object: Option<AuthoriseIntegrityObject>, pub shipping_cost: Option<MinorUnit>, pub additional_payment_method_data: Option<AdditionalPaymentData>, pub merchant_account_id: Option<Secret<String>>, pub merchant_config_currency: Option<storage_enums::Currency>, pub connector_testing_data: Option<pii::SecretSerdeValue>, pub order_id: Option<String>, pub locale: Option<String>, pub payment_channel: Option<common_enums::PaymentChannel>, pub enable_partial_authorization: Option<common_types::primitive_wrappers::EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, pub is_stored_credential: Option<bool>, pub mit_category: Option<common_enums::MitCategory>, } #[derive(Debug, Clone, Serialize)] pub struct ExternalVaultProxyPaymentsData { pub payment_method_data: ExternalVaultPaymentMethodData, /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount) /// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately /// ```text /// get_original_amount() /// get_surcharge_amount() /// get_tax_on_surcharge_amount() /// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount /// ``` pub amount: i64, pub order_tax_amount: Option<MinorUnit>, pub email: Option<pii::Email>, pub customer_name: Option<Secret<String>>, pub currency: storage_enums::Currency, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, pub statement_descriptor: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub router_return_url: Option<String>, pub webhook_url: Option<String>, pub complete_authorize_url: Option<String>, // Mandates pub setup_future_usage: Option<storage_enums::FutureUsage>, pub mandate_id: Option<api_models::payments::MandateIds>, pub off_session: Option<bool>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub setup_mandate_details: Option<mandates::MandateData>, pub browser_info: Option<BrowserInformation>, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub order_category: Option<String>, pub session_token: Option<String>, pub enrolled_for_3ds: bool, pub related_transaction_id: Option<String>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub surcharge_details: Option<SurchargeDetails>, pub customer_id: Option<id_type::CustomerId>, pub request_incremental_authorization: bool, pub metadata: Option<serde_json::Value>, pub authentication_data: Option<AuthenticationData>, pub request_extended_authorization: Option<common_types::primitive_wrappers::RequestExtendedAuthorizationBool>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, // New amount for amount frame work pub minor_amount: MinorUnit, /// 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. pub merchant_order_reference_id: Option<id_type::PaymentReferenceId>, pub integrity_object: Option<AuthoriseIntegrityObject>, pub shipping_cost: Option<MinorUnit>, pub additional_payment_method_data: Option<AdditionalPaymentData>, pub merchant_account_id: Option<Secret<String>>, pub merchant_config_currency: Option<storage_enums::Currency>, pub connector_testing_data: Option<pii::SecretSerdeValue>, pub order_id: Option<String>, } // Note: Integrity traits for ExternalVaultProxyPaymentsData are not implemented // as they are not mandatory for this flow. The integrity_check field in RouterData // will use Ok(()) as default, similar to other flows. // Implement ConnectorCustomerData conversion for ExternalVaultProxy RouterData impl TryFrom< &RouterData< flows::ExternalVaultProxy, ExternalVaultProxyPaymentsData, response_types::PaymentsResponseData, >, > for ConnectorCustomerData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from( data: &RouterData< flows::ExternalVaultProxy, ExternalVaultProxyPaymentsData, response_types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { email: data.request.email.clone(), payment_method_data: None, // External vault proxy doesn't use regular payment method data description: None, phone: None, name: data.request.customer_name.clone(), preprocessing_id: data.preprocessing_id.clone(), split_payments: data.request.split_payments.clone(), setup_future_usage: data.request.setup_future_usage, customer_acceptance: data.request.customer_acceptance.clone(), customer_id: None, billing_address: None, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentsPostSessionTokensData { // amount here would include amount, surcharge_amount and shipping_cost pub amount: MinorUnit, /// original amount sent by the merchant pub order_amount: MinorUnit, pub currency: storage_enums::Currency, pub capture_method: Option<storage_enums::CaptureMethod>, /// 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. pub merchant_order_reference_id: Option<String>, pub shipping_cost: Option<MinorUnit>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub router_return_url: Option<String>, } #[derive(Debug, Clone, Serialize)] pub struct PaymentsUpdateMetadataData { pub metadata: pii::SecretSerdeValue, pub connector_transaction_id: String, } #[derive(Debug, Clone, PartialEq, Serialize)] pub struct AuthoriseIntegrityObject { /// Authorise amount pub amount: MinorUnit, /// Authorise currency pub currency: storage_enums::Currency, } #[derive(Debug, Clone, PartialEq, Serialize)] pub struct SyncIntegrityObject { /// Sync amount pub amount: Option<MinorUnit>, /// Sync currency pub currency: Option<storage_enums::Currency>, } #[derive(Debug, Clone, Default, Serialize)] pub struct PaymentsCaptureData { pub amount_to_capture: i64, pub currency: storage_enums::Currency, pub connector_transaction_id: String, pub payment_amount: i64, pub multiple_capture_data: Option<MultipleCaptureRequestData>, pub connector_meta: Option<serde_json::Value>, pub browser_info: Option<BrowserInformation>, pub metadata: Option<serde_json::Value>, // This metadata is used to store the metadata shared during the payment intent request. pub capture_method: Option<storage_enums::CaptureMethod>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, // New amount for amount frame work pub minor_payment_amount: MinorUnit, pub minor_amount_to_capture: MinorUnit, pub integrity_object: Option<CaptureIntegrityObject>, pub webhook_url: Option<String>, } #[derive(Debug, Clone, PartialEq, Serialize)] pub struct CaptureIntegrityObject { /// capture amount pub capture_amount: Option<MinorUnit>, /// capture currency pub currency: storage_enums::Currency, } #[derive(Debug, Clone, Default, Serialize)] pub struct PaymentsIncrementalAuthorizationData { pub total_amount: i64, pub additional_amount: i64, pub currency: storage_enums::Currency, pub reason: Option<String>, pub connector_transaction_id: String, pub connector_meta: Option<serde_json::Value>, } #[derive(Debug, Clone, Default, Serialize)] pub struct MultipleCaptureRequestData { pub capture_sequence: i16, pub capture_reference: String, } #[derive(Debug, Clone, Serialize)] pub struct AuthorizeSessionTokenData { pub amount_to_capture: Option<i64>, pub currency: storage_enums::Currency, pub connector_transaction_id: String, pub amount: Option<i64>, } #[derive(Debug, Clone, Serialize)] pub struct ConnectorCustomerData { pub description: Option<String>, pub email: Option<pii::Email>, pub phone: Option<Secret<String>>, pub name: Option<Secret<String>>, pub preprocessing_id: Option<String>, pub payment_method_data: Option<PaymentMethodData>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, // Mandates pub setup_future_usage: Option<storage_enums::FutureUsage>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub customer_id: Option<id_type::CustomerId>, pub billing_address: Option<AddressDetails>, } impl TryFrom<SetupMandateRequestData> for ConnectorCustomerData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> { Ok(Self { email: data.email, payment_method_data: Some(data.payment_method_data), description: None, phone: None, name: None, preprocessing_id: None, split_payments: None, setup_future_usage: data.setup_future_usage, customer_acceptance: data.customer_acceptance, customer_id: None, billing_address: None, }) } } impl TryFrom<SetupMandateRequestData> for PaymentsPreProcessingData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: Some(data.payment_method_data), amount: data.amount, minor_amount: data.minor_amount, email: data.email, currency: Some(data.currency), payment_method_type: data.payment_method_type, setup_mandate_details: data.setup_mandate_details, capture_method: data.capture_method, order_details: None, router_return_url: data.router_return_url, webhook_url: data.webhook_url, complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, surcharge_details: None, connector_transaction_id: None, mandate_id: data.mandate_id, related_transaction_id: None, redirect_response: None, enrolled_for_3ds: false, split_payments: None, metadata: data.metadata, customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, is_stored_credential: data.is_stored_credential, }) } } impl TryFrom< &RouterData<flows::Authorize, PaymentsAuthorizeData, response_types::PaymentsResponseData>, > for ConnectorCustomerData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from( data: &RouterData< flows::Authorize, PaymentsAuthorizeData, response_types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { email: data.request.email.clone(), payment_method_data: Some(data.request.payment_method_data.clone()), description: None, phone: None, name: data.request.customer_name.clone(), preprocessing_id: data.preprocessing_id.clone(), split_payments: data.request.split_payments.clone(), setup_future_usage: data.request.setup_future_usage, customer_acceptance: data.request.customer_acceptance.clone(), customer_id: None, billing_address: None, }) } } impl TryFrom<&RouterData<flows::Session, PaymentsSessionData, response_types::PaymentsResponseData>> for ConnectorCustomerData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from( data: &RouterData< flows::Session, PaymentsSessionData, response_types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { email: data.request.email.clone(), payment_method_data: None, description: None, phone: None, name: data.request.customer_name.clone(), preprocessing_id: data.preprocessing_id.clone(), split_payments: None, setup_future_usage: None, customer_acceptance: None, customer_id: None, billing_address: None, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentMethodTokenizationData { pub payment_method_data: PaymentMethodData, pub browser_info: Option<BrowserInformation>, pub currency: storage_enums::Currency, pub amount: Option<i64>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub setup_mandate_details: Option<mandates::MandateData>, pub mandate_id: Option<api_models::payments::MandateIds>, } impl TryFrom<SetupMandateRequestData> for PaymentMethodTokenizationData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: data.payment_method_data, browser_info: None, currency: data.currency, amount: data.amount, split_payments: None, customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, setup_mandate_details: data.setup_mandate_details, mandate_id: data.mandate_id, }) } } impl<F> From<&RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>> for PaymentMethodTokenizationData { fn from( data: &RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>, ) -> Self { Self { payment_method_data: data.request.payment_method_data.clone(), browser_info: None, currency: data.request.currency, amount: Some(data.request.amount), split_payments: data.request.split_payments.clone(), customer_acceptance: data.request.customer_acceptance.clone(), setup_future_usage: data.request.setup_future_usage, setup_mandate_details: data.request.setup_mandate_details.clone(), mandate_id: data.request.mandate_id.clone(), } } } impl TryFrom<PaymentsAuthorizeData> for PaymentMethodTokenizationData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: data.payment_method_data, browser_info: data.browser_info, currency: data.currency, amount: Some(data.amount), split_payments: data.split_payments.clone(), customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, setup_mandate_details: data.setup_mandate_details, mandate_id: data.mandate_id, }) } } impl TryFrom<CompleteAuthorizeData> for PaymentMethodTokenizationData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: data .payment_method_data .get_required_value("payment_method_data") .change_context(ApiErrorResponse::MissingRequiredField { field_name: "payment_method_data", })?, browser_info: data.browser_info, currency: data.currency, amount: Some(data.amount), split_payments: None, customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, setup_mandate_details: data.setup_mandate_details, mandate_id: data.mandate_id, }) } } impl TryFrom<ExternalVaultProxyPaymentsData> for PaymentMethodTokenizationData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(_data: ExternalVaultProxyPaymentsData) -> Result<Self, Self::Error> { // TODO: External vault proxy payments should not use regular payment method tokenization // This needs to be implemented separately for external vault flows Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason( "External vault proxy tokenization not implemented".to_string(), ), } .into()) } } #[derive(Debug, Clone, Serialize)] pub struct CreateOrderRequestData { pub minor_amount: MinorUnit, pub currency: storage_enums::Currency, } impl TryFrom<PaymentsAuthorizeData> for CreateOrderRequestData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { minor_amount: data.minor_amount, currency: data.currency, }) } } impl TryFrom<ExternalVaultProxyPaymentsData> for CreateOrderRequestData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: ExternalVaultProxyPaymentsData) -> Result<Self, Self::Error> { Ok(Self { minor_amount: data.minor_amount, currency: data.currency, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentsPreProcessingData { pub payment_method_data: Option<PaymentMethodData>, pub amount: Option<i64>, pub email: Option<pii::Email>, pub currency: Option<storage_enums::Currency>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub setup_mandate_details: Option<mandates::MandateData>, pub capture_method: Option<storage_enums::CaptureMethod>, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub router_return_url: Option<String>, pub webhook_url: Option<String>, pub complete_authorize_url: Option<String>, pub surcharge_details: Option<SurchargeDetails>, pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, pub enrolled_for_3ds: bool, pub mandate_id: Option<api_models::payments::MandateIds>, pub related_transaction_id: Option<String>, pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, pub metadata: Option<Secret<serde_json::Value>>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub setup_future_usage: Option<storage_enums::FutureUsage>, // New amount for amount frame work pub minor_amount: Option<MinorUnit>, pub is_stored_credential: Option<bool>, } #[derive(Debug, Clone, Serialize)] pub struct GiftCardBalanceCheckRequestData { pub payment_method_data: PaymentMethodData, pub currency: Option<storage_enums::Currency>, pub minor_amount: Option<MinorUnit>, } impl TryFrom<PaymentsAuthorizeData> for PaymentsPreProcessingData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: Some(data.payment_method_data), amount: Some(data.amount), minor_amount: Some(data.minor_amount), email: data.email, currency: Some(data.currency), payment_method_type: data.payment_method_type, setup_mandate_details: data.setup_mandate_details, capture_method: data.capture_method, order_details: data.order_details, router_return_url: data.router_return_url, webhook_url: data.webhook_url, complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, surcharge_details: data.surcharge_details, connector_transaction_id: None, mandate_id: data.mandate_id, related_transaction_id: data.related_transaction_id, redirect_response: None, enrolled_for_3ds: data.enrolled_for_3ds, split_payments: data.split_payments, metadata: data.metadata.map(Secret::new), customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, is_stored_credential: data.is_stored_credential, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentsPreAuthenticateData { pub payment_method_data: Option<PaymentMethodData>, pub amount: Option<i64>, pub email: Option<pii::Email>, pub currency: Option<storage_enums::Currency>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub router_return_url: Option<String>, pub complete_authorize_url: Option<String>, pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, pub enrolled_for_3ds: bool, pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, // New amount for amount frame work pub minor_amount: Option<MinorUnit>, } impl TryFrom<PaymentsAuthorizeData> for PaymentsPreAuthenticateData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: Some(data.payment_method_data), amount: Some(data.amount), minor_amount: Some(data.minor_amount), email: data.email, currency: Some(data.currency), payment_method_type: data.payment_method_type, router_return_url: data.router_return_url, complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, connector_transaction_id: None, redirect_response: None, enrolled_for_3ds: data.enrolled_for_3ds, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentsAuthenticateData { pub payment_method_data: Option<PaymentMethodData>, pub amount: Option<i64>, pub email: Option<pii::Email>, pub currency: Option<storage_enums::Currency>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub router_return_url: Option<String>, pub complete_authorize_url: Option<String>, pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, pub enrolled_for_3ds: bool, pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, // New amount for amount frame work pub minor_amount: Option<MinorUnit>, } impl TryFrom<PaymentsAuthorizeData> for PaymentsAuthenticateData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: Some(data.payment_method_data), amount: Some(data.amount), minor_amount: Some(data.minor_amount), email: data.email, currency: Some(data.currency), payment_method_type: data.payment_method_type, router_return_url: data.router_return_url, complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, connector_transaction_id: None, redirect_response: None, enrolled_for_3ds: data.enrolled_for_3ds, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentsPostAuthenticateData { pub payment_method_data: Option<PaymentMethodData>, pub amount: Option<i64>, pub email: Option<pii::Email>, pub currency: Option<storage_enums::Currency>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub router_return_url: Option<String>, pub complete_authorize_url: Option<String>, pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, pub enrolled_for_3ds: bool, pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, // New amount for amount frame work pub minor_amount: Option<MinorUnit>, } impl TryFrom<PaymentsAuthorizeData> for PaymentsPostAuthenticateData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: Some(data.payment_method_data), amount: Some(data.amount), minor_amount: Some(data.minor_amount), email: data.email, currency: Some(data.currency), payment_method_type: data.payment_method_type, router_return_url: data.router_return_url, complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, connector_transaction_id: None, redirect_response: None, enrolled_for_3ds: data.enrolled_for_3ds, }) } } impl TryFrom<CompleteAuthorizeData> for PaymentsPreProcessingData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: data.payment_method_data, amount: Some(data.amount), minor_amount: Some(data.minor_amount), email: data.email, currency: Some(data.currency), payment_method_type: None, setup_mandate_details: data.setup_mandate_details, capture_method: data.capture_method, order_details: None, router_return_url: None, webhook_url: None, complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, surcharge_details: None, connector_transaction_id: data.connector_transaction_id, mandate_id: data.mandate_id, related_transaction_id: None, redirect_response: data.redirect_response, split_payments: None, enrolled_for_3ds: true, metadata: data.connector_meta.map(Secret::new), customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, is_stored_credential: data.is_stored_credential, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentsPostProcessingData { pub payment_method_data: PaymentMethodData, pub customer_id: Option<id_type::CustomerId>, pub connector_transaction_id: Option<String>, pub country: Option<common_enums::CountryAlpha2>, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub header_payload: Option<payments::HeaderPayload>, } impl<F> TryFrom<RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>> for PaymentsPostProcessingData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from( data: RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: data.request.payment_method_data, connector_transaction_id: match data.response { Ok(response_types::PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(id), .. }) => Some(id.clone()), _ => None, }, customer_id: data.request.customer_id, country: data .address .get_payment_billing() .and_then(|bl| bl.address.as_ref()) .and_then(|address| address.country), connector_meta_data: data.connector_meta_data.clone(), header_payload: data.header_payload, }) } } #[derive(Debug, Clone, Serialize)] pub struct CompleteAuthorizeData { pub payment_method_data: Option<PaymentMethodData>, pub amount: i64, pub email: Option<pii::Email>, pub currency: storage_enums::Currency, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, // Mandates pub setup_future_usage: Option<storage_enums::FutureUsage>, pub mandate_id: Option<api_models::payments::MandateIds>, pub off_session: Option<bool>, pub setup_mandate_details: Option<mandates::MandateData>, pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, pub connector_meta: Option<serde_json::Value>, pub complete_authorize_url: Option<String>, pub metadata: Option<serde_json::Value>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, // New amount for amount frame work pub minor_amount: MinorUnit, pub merchant_account_id: Option<Secret<String>>, pub merchant_config_currency: Option<storage_enums::Currency>, pub threeds_method_comp_ind: Option<api_models::payments::ThreeDsCompletionIndicator>, pub is_stored_credential: Option<bool>, } #[derive(Debug, Clone, Serialize)] pub struct CompleteAuthorizeRedirectResponse { pub params: Option<Secret<String>>, pub payload: Option<pii::SecretSerdeValue>, } #[derive(Debug, Default, Clone, Serialize)] pub struct PaymentsSyncData { //TODO : add fields based on the connector requirements pub connector_transaction_id: ResponseId, pub encoded_data: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub connector_meta: Option<serde_json::Value>, pub sync_type: SyncRequestType, pub mandate_id: Option<api_models::payments::MandateIds>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub currency: storage_enums::Currency, pub payment_experience: Option<common_enums::PaymentExperience>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub amount: MinorUnit, pub integrity_object: Option<SyncIntegrityObject>, pub connector_reference_id: Option<String>, pub setup_future_usage: Option<storage_enums::FutureUsage>, } #[derive(Debug, Default, Clone, Serialize)] pub enum SyncRequestType { MultipleCaptureSync(Vec<String>), #[default] SinglePaymentSync, } #[derive(Debug, Default, Clone, Serialize)] pub struct PaymentsCancelData { pub amount: Option<i64>, pub currency: Option<storage_enums::Currency>, pub connector_transaction_id: String, pub cancellation_reason: Option<String>, pub connector_meta: Option<serde_json::Value>, pub browser_info: Option<BrowserInformation>, pub metadata: Option<serde_json::Value>, // This metadata is used to store the metadata shared during the payment intent request. // minor amount data for amount framework pub minor_amount: Option<MinorUnit>, pub webhook_url: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, } #[derive(Debug, Default, Clone, Serialize)] pub struct PaymentsCancelPostCaptureData { pub currency: Option<storage_enums::Currency>, pub connector_transaction_id: String, pub cancellation_reason: Option<String>, pub connector_meta: Option<serde_json::Value>, // minor amount data for amount framework pub minor_amount: Option<MinorUnit>, } #[derive(Debug, Default, Clone, Serialize)] pub struct PaymentsExtendAuthorizationData { pub minor_amount: MinorUnit, pub currency: storage_enums::Currency, pub connector_transaction_id: String, pub connector_meta: Option<serde_json::Value>, } #[derive(Debug, Default, Clone)] pub struct PaymentsRejectData { pub amount: Option<i64>, pub currency: Option<storage_enums::Currency>, } #[derive(Debug, Default, Clone)] pub struct PaymentsApproveData { pub amount: Option<i64>, pub currency: Option<storage_enums::Currency>, } #[derive(Clone, Debug, Default, Serialize, serde::Deserialize)] pub struct BrowserInformation { pub color_depth: Option<u8>, pub java_enabled: Option<bool>, pub java_script_enabled: Option<bool>, pub language: Option<String>, pub screen_height: Option<u32>, pub screen_width: Option<u32>, pub time_zone: Option<i32>, pub ip_address: Option<std::net::IpAddr>, pub accept_header: Option<String>, pub user_agent: Option<String>, pub os_type: Option<String>, pub os_version: Option<String>, pub device_model: Option<String>, pub accept_language: Option<String>, pub referer: Option<String>, } #[cfg(feature = "v2")] impl From<common_utils::types::BrowserInformation> for BrowserInformation { fn from(value: common_utils::types::BrowserInformation) -> Self { Self { color_depth: value.color_depth, java_enabled: value.java_enabled, java_script_enabled: value.java_script_enabled, language: value.language, screen_height: value.screen_height, screen_width: value.screen_width, time_zone: value.time_zone, ip_address: value.ip_address, accept_header: value.accept_header, user_agent: value.user_agent, os_type: value.os_type, os_version: value.os_version, device_model: value.device_model, accept_language: value.accept_language, referer: value.referer, } } } #[cfg(feature = "v1")] impl From<api_models::payments::BrowserInformation> for BrowserInformation { fn from(value: api_models::payments::BrowserInformation) -> Self { Self { color_depth: value.color_depth, java_enabled: value.java_enabled, java_script_enabled: value.java_script_enabled, language: value.language, screen_height: value.screen_height, screen_width: value.screen_width, time_zone: value.time_zone, ip_address: value.ip_address, accept_header: value.accept_header, user_agent: value.user_agent, os_type: value.os_type, os_version: value.os_version, device_model: value.device_model, accept_language: value.accept_language, referer: value.referer, } } } #[derive(Debug, Clone, Default, Serialize)] pub enum ResponseId { ConnectorTransactionId(String), EncodedData(String), #[default] NoResponseId, } impl ResponseId { pub fn get_connector_transaction_id( &self, ) -> errors::CustomResult<String, errors::ValidationError> { match self { Self::ConnectorTransactionId(txn_id) => Ok(txn_id.to_string()), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "connector_transaction_id", }) .attach_printable("Expected connector transaction ID not found"), } } } #[derive(Clone, Debug, serde::Deserialize, Serialize)] pub struct SurchargeDetails { /// original_amount pub original_amount: MinorUnit, /// surcharge value pub surcharge: common_utils::types::Surcharge, /// tax on surcharge value pub tax_on_surcharge: Option<common_utils::types::Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>>, /// surcharge amount for this payment pub surcharge_amount: MinorUnit, /// tax on surcharge amount for this payment pub tax_on_surcharge_amount: MinorUnit, } impl SurchargeDetails { pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_on_surcharge_amount } } #[cfg(feature = "v1")] impl From<( &RequestSurchargeDetails, &payments::payment_attempt::PaymentAttempt, )> for SurchargeDetails { fn from( (request_surcharge_details, payment_attempt): ( &RequestSurchargeDetails, &payments::payment_attempt::PaymentAttempt, ), ) -> Self { let surcharge_amount = request_surcharge_details.surcharge_amount; let tax_on_surcharge_amount = request_surcharge_details.tax_amount.unwrap_or_default(); Self { original_amount: payment_attempt.net_amount.get_order_amount(), surcharge: common_utils::types::Surcharge::Fixed( request_surcharge_details.surcharge_amount, ), tax_on_surcharge: None, surcharge_amount, tax_on_surcharge_amount, } } } #[cfg(feature = "v2")] impl From<( &RequestSurchargeDetails, &payments::payment_attempt::PaymentAttempt, )> for SurchargeDetails { fn from( (_request_surcharge_details, _payment_attempt): ( &RequestSurchargeDetails, &payments::payment_attempt::PaymentAttempt, ), ) -> Self { todo!() } } #[derive(Debug, Clone, Serialize)] pub struct AuthenticationData { pub eci: Option<String>, pub cavv: Secret<String>, pub threeds_server_transaction_id: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub ds_trans_id: Option<String>, pub created_at: time::PrimitiveDateTime, pub challenge_code: Option<String>, pub challenge_cancel: Option<String>, pub challenge_code_reason: Option<String>, pub message_extension: Option<pii::SecretSerdeValue>, pub acs_trans_id: Option<String>, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, } #[derive(Debug, Clone)] pub struct RefundsData { pub refund_id: String, pub connector_transaction_id: String, pub connector_refund_id: Option<String>, pub currency: storage_enums::Currency, /// Amount for the payment against which this refund is issued pub payment_amount: i64, pub reason: Option<String>, pub webhook_url: Option<String>, /// Amount to be refunded pub refund_amount: i64, /// Arbitrary metadata required for refund pub connector_metadata: Option<serde_json::Value>, /// refund method pub refund_connector_metadata: Option<pii::SecretSerdeValue>, pub browser_info: Option<BrowserInformation>, /// Charges associated with the payment pub split_refunds: Option<SplitRefundsRequest>, // New amount for amount frame work pub minor_payment_amount: MinorUnit, pub minor_refund_amount: MinorUnit, pub integrity_object: Option<RefundIntegrityObject>, pub refund_status: storage_enums::RefundStatus, pub merchant_account_id: Option<Secret<String>>, pub merchant_config_currency: Option<storage_enums::Currency>, pub capture_method: Option<storage_enums::CaptureMethod>, pub additional_payment_method_data: Option<AdditionalPaymentData>, } #[derive(Debug, Clone, PartialEq)] pub struct RefundIntegrityObject { /// refund currency pub currency: storage_enums::Currency, /// refund amount pub refund_amount: MinorUnit, } #[derive(Debug, serde::Deserialize, Clone)] pub enum SplitRefundsRequest { StripeSplitRefund(StripeSplitRefund), AdyenSplitRefund(common_types::domain::AdyenSplitData), XenditSplitRefund(common_types::domain::XenditSplitSubMerchantData), } #[derive(Debug, serde::Deserialize, Clone)] pub struct StripeSplitRefund { pub charge_id: String, pub transfer_account_id: String, pub charge_type: api_models::enums::PaymentChargeType, pub options: ChargeRefundsOptions, } #[derive(Debug, serde::Deserialize, Clone)] pub struct ChargeRefunds { pub charge_id: String, pub transfer_account_id: String, pub charge_type: api_models::enums::PaymentChargeType, pub options: ChargeRefundsOptions, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, Serialize)] pub enum ChargeRefundsOptions { Destination(DestinationChargeRefund), Direct(DirectChargeRefund), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, Serialize)] pub struct DirectChargeRefund { pub revert_platform_fee: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, Serialize)] pub struct DestinationChargeRefund { pub revert_platform_fee: bool, pub revert_transfer: bool, } #[derive(Debug, Clone)] pub struct AccessTokenAuthenticationRequestData { pub auth_creds: router_data::ConnectorAuthType, } impl TryFrom<router_data::ConnectorAuthType> for AccessTokenAuthenticationRequestData { type Error = ApiErrorResponse; fn try_from(connector_auth: router_data::ConnectorAuthType) -> Result<Self, Self::Error> { Ok(Self { auth_creds: connector_auth, }) } } #[derive(Debug, Clone)] pub struct AccessTokenRequestData { pub app_id: Secret<String>, pub id: Option<Secret<String>>, pub authentication_token: Option<AccessTokenAuthenticationResponse>, // Add more keys if required } // This is for backward compatibility impl TryFrom<router_data::ConnectorAuthType> for AccessTokenRequestData { type Error = ApiErrorResponse; fn try_from(connector_auth: router_data::ConnectorAuthType) -> Result<Self, Self::Error> { match connector_auth { router_data::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { app_id: api_key, id: None, authentication_token: None, }), router_data::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { app_id: api_key, id: Some(key1), authentication_token: None, }), router_data::ConnectorAuthType::SignatureKey { api_key, key1, .. } => Ok(Self { app_id: api_key, id: Some(key1), authentication_token: None, }), router_data::ConnectorAuthType::MultiAuthKey { api_key, key1, .. } => Ok(Self { app_id: api_key, id: Some(key1), authentication_token: None, }), _ => Err(ApiErrorResponse::InvalidDataValue { field_name: "connector_account_details", }), } } } impl TryFrom<( router_data::ConnectorAuthType, Option<AccessTokenAuthenticationResponse>, )> for AccessTokenRequestData { type Error = ApiErrorResponse; fn try_from( (connector_auth, authentication_token): ( router_data::ConnectorAuthType, Option<AccessTokenAuthenticationResponse>, ), ) -> Result<Self, Self::Error> { let mut access_token_request_data = Self::try_from(connector_auth)?; access_token_request_data.authentication_token = authentication_token; Ok(access_token_request_data) } } #[derive(Default, Debug, Clone)] pub struct AcceptDisputeRequestData { pub dispute_id: String, pub connector_dispute_id: String, pub dispute_status: storage_enums::DisputeStatus, } #[derive(Default, Debug, Clone)] pub struct DefendDisputeRequestData { pub dispute_id: String, pub connector_dispute_id: String, } #[derive(Default, Debug, Clone)] pub struct SubmitEvidenceRequestData { pub dispute_id: String, pub dispute_status: storage_enums::DisputeStatus, pub connector_dispute_id: String, pub access_activity_log: Option<String>, pub billing_address: Option<String>, //cancellation policy pub cancellation_policy: Option<Vec<u8>>, pub cancellation_policy_file_type: Option<String>, pub cancellation_policy_provider_file_id: Option<String>, pub cancellation_policy_disclosure: Option<String>, pub cancellation_rebuttal: Option<String>, //customer communication pub customer_communication: Option<Vec<u8>>, pub customer_communication_file_type: Option<String>, pub customer_communication_provider_file_id: Option<String>, pub customer_email_address: Option<String>, pub customer_name: Option<String>, pub customer_purchase_ip: Option<String>, //customer signature pub customer_signature: Option<Vec<u8>>, pub customer_signature_file_type: Option<String>, pub customer_signature_provider_file_id: Option<String>, //product description pub product_description: Option<String>, //receipts pub receipt: Option<Vec<u8>>, pub receipt_file_type: Option<String>, pub receipt_provider_file_id: Option<String>, //refund policy pub refund_policy: Option<Vec<u8>>, pub refund_policy_file_type: Option<String>, pub refund_policy_provider_file_id: Option<String>, pub refund_policy_disclosure: Option<String>, pub refund_refusal_explanation: Option<String>, //service docs pub service_date: Option<String>, pub service_documentation: Option<Vec<u8>>, pub service_documentation_file_type: Option<String>, pub service_documentation_provider_file_id: Option<String>, //shipping details docs pub shipping_address: Option<String>, pub shipping_carrier: Option<String>, pub shipping_date: Option<String>, pub shipping_documentation: Option<Vec<u8>>, pub shipping_documentation_file_type: Option<String>, pub shipping_documentation_provider_file_id: Option<String>, pub shipping_tracking_number: Option<String>, //invoice details pub invoice_showing_distinct_transactions: Option<Vec<u8>>, pub invoice_showing_distinct_transactions_file_type: Option<String>, pub invoice_showing_distinct_transactions_provider_file_id: Option<String>, //subscription details pub recurring_transaction_agreement: Option<Vec<u8>>, pub recurring_transaction_agreement_file_type: Option<String>, pub recurring_transaction_agreement_provider_file_id: Option<String>, //uncategorized details pub uncategorized_file: Option<Vec<u8>>, pub uncategorized_file_type: Option<String>, pub uncategorized_file_provider_file_id: Option<String>, pub uncategorized_text: Option<String>, } #[derive(Debug, Serialize, Clone)] pub struct FetchDisputesRequestData { pub created_from: time::PrimitiveDateTime, pub created_till: time::PrimitiveDateTime, } #[derive(Clone, Debug)] pub struct RetrieveFileRequestData { pub provider_file_id: String, pub connector_dispute_id: Option<String>, } #[serde_as] #[derive(Clone, Debug, Serialize)] pub struct UploadFileRequestData { pub file_key: String, #[serde(skip)] pub file: Vec<u8>, #[serde_as(as = "serde_with::DisplayFromStr")] pub file_type: mime::Mime, pub file_size: i32, pub dispute_id: String, pub connector_dispute_id: String, } #[cfg(feature = "payouts")] #[derive(Debug, Clone)] pub struct PayoutsData { pub payout_id: id_type::PayoutId, pub amount: i64, pub connector_payout_id: Option<String>, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub payout_type: Option<storage_enums::PayoutType>, pub entity_type: storage_enums::PayoutEntityType, pub customer_details: Option<CustomerDetails>, pub vendor_details: Option<api_models::payouts::PayoutVendorAccountDetails>, // New minor amount for amount framework pub minor_amount: MinorUnit, pub priority: Option<storage_enums::PayoutSendPriority>, pub connector_transfer_method_id: Option<String>, pub webhook_url: Option<String>, pub browser_info: Option<BrowserInformation>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Default, Clone)] pub struct CustomerDetails { pub customer_id: Option<id_type::CustomerId>, pub name: Option<Secret<String, masking::WithType>>, pub email: Option<pii::Email>, pub phone: Option<Secret<String, masking::WithType>>, pub phone_country_code: Option<String>, pub tax_registration_id: Option<Secret<String, masking::WithType>>, } #[derive(Debug, Clone)] pub struct VerifyWebhookSourceRequestData { pub webhook_headers: actix_web::http::header::HeaderMap, pub webhook_body: Vec<u8>, pub merchant_secret: api_models::webhooks::ConnectorWebhookSecrets, } #[derive(Debug, Clone)] pub struct MandateRevokeRequestData { pub mandate_id: String, pub connector_mandate_id: Option<String>, } #[derive(Debug, Clone, Serialize)] pub struct PaymentsSessionData { pub amount: i64, pub currency: common_enums::Currency, pub country: Option<common_enums::CountryAlpha2>, pub surcharge_details: Option<SurchargeDetails>, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub email: Option<pii::Email>, // Minor Unit amount for amount frame work pub minor_amount: MinorUnit, pub apple_pay_recurring_details: Option<api_models::payments::ApplePayRecurringPaymentRequest>, pub customer_name: Option<Secret<String>>, pub order_tax_amount: Option<MinorUnit>, pub shipping_cost: Option<MinorUnit>, pub metadata: Option<Secret<serde_json::Value>>, /// The specific payment method type for which the session token is being generated pub payment_method_type: Option<common_enums::PaymentMethodType>, pub payment_method: Option<common_enums::PaymentMethod>, } #[derive(Debug, Clone, Default)] pub struct PaymentsTaxCalculationData { pub amount: MinorUnit, pub currency: storage_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub shipping_address: address::Address, } #[derive(Debug, Clone, Default, Serialize)] pub struct SdkPaymentsSessionUpdateData { pub order_tax_amount: MinorUnit, // amount here would include amount, surcharge_amount, order_tax_amount and shipping_cost pub amount: MinorUnit, /// original amount sent by the merchant pub order_amount: MinorUnit, pub currency: storage_enums::Currency, pub session_id: Option<String>, pub shipping_cost: Option<MinorUnit>, } #[derive(Debug, Clone, Serialize)] pub struct SetupMandateRequestData { pub currency: storage_enums::Currency, pub payment_method_data: PaymentMethodData, pub amount: Option<i64>, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub mandate_id: Option<api_models::payments::MandateIds>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub setup_mandate_details: Option<mandates::MandateData>, pub router_return_url: Option<String>, pub webhook_url: Option<String>, pub browser_info: Option<BrowserInformation>, pub email: Option<pii::Email>, pub customer_name: Option<Secret<String>>, pub return_url: Option<String>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub request_incremental_authorization: bool, pub metadata: Option<pii::SecretSerdeValue>, pub complete_authorize_url: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub enrolled_for_3ds: bool, pub related_transaction_id: Option<String>, // MinorUnit for amount framework pub minor_amount: Option<MinorUnit>, pub shipping_cost: Option<MinorUnit>, pub connector_testing_data: Option<pii::SecretSerdeValue>, pub customer_id: Option<id_type::CustomerId>, pub enable_partial_authorization: Option<common_types::primitive_wrappers::EnablePartialAuthorizationBool>, pub payment_channel: Option<storage_enums::PaymentChannel>, pub is_stored_credential: Option<bool>, } #[derive(Debug, Clone)] pub struct VaultRequestData { pub payment_method_vaulting_data: Option<PaymentMethodVaultingData>, pub connector_vault_id: Option<String>, pub connector_customer_id: Option<String>, } #[derive(Debug, Serialize, Clone)] pub struct DisputeSyncData { pub dispute_id: String, pub connector_dispute_id: String, }
crates/hyperswitch_domain_models/src/router_request_types.rs
hyperswitch_domain_models::src::router_request_types
12,051
true
// File: crates/hyperswitch_domain_models/src/callback_mapper.rs // Module: hyperswitch_domain_models::src::callback_mapper use common_enums::enums as common_enums; use common_types::callback_mapper::CallbackMapperData; #[derive(Clone, Debug, Eq, PartialEq)] pub struct CallbackMapper { pub id: String, pub callback_mapper_id_type: common_enums::CallbackMapperIdType, pub data: CallbackMapperData, pub created_at: time::PrimitiveDateTime, pub last_modified_at: time::PrimitiveDateTime, } impl CallbackMapper { pub fn new( id: String, callback_mapper_id_type: common_enums::CallbackMapperIdType, data: CallbackMapperData, created_at: time::PrimitiveDateTime, last_modified_at: time::PrimitiveDateTime, ) -> Self { Self { id, callback_mapper_id_type, data, created_at, last_modified_at, } } }
crates/hyperswitch_domain_models/src/callback_mapper.rs
hyperswitch_domain_models::src::callback_mapper
206
true
// File: crates/hyperswitch_domain_models/src/payment_methods.rs // Module: hyperswitch_domain_models::src::payment_methods #[cfg(feature = "v2")] use api_models::payment_methods::PaymentMethodsData; use api_models::{customers, payment_methods, payments}; // specific imports because of using the macro use common_enums::enums::MerchantStorageScheme; #[cfg(feature = "v1")] use common_utils::crypto::OptionalEncryptableValue; #[cfg(feature = "v2")] use common_utils::{crypto::Encryptable, encryption::Encryption, types::keymanager::ToEncryptable}; use common_utils::{ errors::{CustomResult, ParsingError, ValidationError}, id_type, pii, type_name, types::keymanager, }; pub use diesel_models::{enums as storage_enums, PaymentMethodUpdate}; use error_stack::ResultExt; #[cfg(feature = "v1")] use masking::ExposeInterface; use masking::{PeekInterface, Secret}; #[cfg(feature = "v1")] use router_env::logger; #[cfg(feature = "v2")] use rustc_hash::FxHashMap; #[cfg(feature = "v2")] use serde_json::Value; use time::PrimitiveDateTime; #[cfg(feature = "v2")] use crate::address::Address; #[cfg(feature = "v1")] use crate::type_encryption::AsyncLift; use crate::{ mandates::{self, CommonMandateReference}, merchant_key_store::MerchantKeyStore, payment_method_data as domain_payment_method_data, transformers::ForeignTryFrom, type_encryption::{crypto_operation, CryptoOperation}, }; #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct VaultId(String); impl VaultId { pub fn get_string_repr(&self) -> &String { &self.0 } pub fn generate(id: String) -> Self { Self(id) } } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct PaymentMethod { pub customer_id: id_type::CustomerId, pub merchant_id: id_type::MerchantId, pub payment_method_id: String, pub accepted_currency: Option<Vec<storage_enums::Currency>>, pub scheme: Option<String>, pub token: Option<String>, pub cardholder_name: Option<Secret<String>>, pub issuer_name: Option<String>, pub issuer_country: Option<String>, pub payer_country: Option<Vec<String>>, pub is_stored: Option<bool>, pub swift_code: Option<String>, pub direct_debit_token: Option<String>, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method: Option<storage_enums::PaymentMethod>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_issuer: Option<String>, pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: OptionalEncryptableValue, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: OptionalEncryptableValue, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: OptionalEncryptableValue, pub vault_source_details: PaymentMethodVaultSourceDetails, } #[cfg(feature = "v2")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct PaymentMethod { /// The identifier for the payment method. Using this recurring payments can be made pub id: id_type::GlobalPaymentMethodId, /// The customer id against which the payment method is saved pub customer_id: id_type::GlobalCustomerId, /// The merchant id against which the payment method is saved pub merchant_id: id_type::MerchantId, /// The merchant connector account id of the external vault where the payment method is saved pub external_vault_source: Option<id_type::MerchantConnectorAccountId>, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method_type: Option<storage_enums::PaymentMethod>, pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, #[encrypt(ty = Value)] pub payment_method_data: Option<Encryptable<PaymentMethodsData>>, pub locker_id: Option<VaultId>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<CommonMandateReference>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, #[encrypt(ty = Value)] pub payment_method_billing_address: Option<Encryptable<Address>>, pub updated_by: Option<String>, pub locker_fingerprint_id: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, #[encrypt(ty = Value)] pub network_token_payment_method_data: Option<Encryptable<domain_payment_method_data::PaymentMethodsData>>, #[encrypt(ty = Value)] pub external_vault_token_data: Option<Encryptable<api_models::payment_methods::ExternalVaultTokenData>>, pub vault_type: Option<storage_enums::VaultType>, } impl PaymentMethod { #[cfg(feature = "v1")] pub fn get_id(&self) -> &String { &self.payment_method_id } #[cfg(feature = "v1")] pub fn get_payment_methods_data( &self, ) -> Option<domain_payment_method_data::PaymentMethodsData> { self.payment_method_data .clone() .map(|value| value.into_inner().expose()) .and_then(|value| { serde_json::from_value::<domain_payment_method_data::PaymentMethodsData>(value) .map_err(|error| { logger::warn!( ?error, "Failed to parse payment method data in payment method info" ); }) .ok() }) } #[cfg(feature = "v2")] pub fn get_id(&self) -> &id_type::GlobalPaymentMethodId { &self.id } #[cfg(feature = "v1")] pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethod> { self.payment_method } #[cfg(feature = "v2")] pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethod> { self.payment_method_type } #[cfg(feature = "v1")] pub fn get_payment_method_subtype(&self) -> Option<storage_enums::PaymentMethodType> { self.payment_method_type } #[cfg(feature = "v2")] pub fn get_payment_method_subtype(&self) -> Option<storage_enums::PaymentMethodType> { self.payment_method_subtype } #[cfg(feature = "v1")] pub fn get_common_mandate_reference(&self) -> Result<CommonMandateReference, ParsingError> { let payments_data = self .connector_mandate_details .clone() .map(|mut mandate_details| { mandate_details .as_object_mut() .map(|obj| obj.remove("payouts")); serde_json::from_value::<mandates::PaymentsMandateReference>(mandate_details) .inspect_err(|err| { router_env::logger::error!("Failed to parse payments data: {:?}", err); }) }) .transpose() .map_err(|err| { router_env::logger::error!("Failed to parse payments data: {:?}", err); ParsingError::StructParseFailure("Failed to parse payments data") })?; let payouts_data = self .connector_mandate_details .clone() .map(|mandate_details| { serde_json::from_value::<Option<CommonMandateReference>>(mandate_details) .inspect_err(|err| { router_env::logger::error!("Failed to parse payouts data: {:?}", err); }) .map(|optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) }) }) .transpose() .map_err(|err| { router_env::logger::error!("Failed to parse payouts data: {:?}", err); ParsingError::StructParseFailure("Failed to parse payouts data") })? .flatten(); Ok(CommonMandateReference { payments: payments_data, payouts: payouts_data, }) } #[cfg(feature = "v2")] pub fn get_common_mandate_reference(&self) -> Result<CommonMandateReference, ParsingError> { if let Some(value) = &self.connector_mandate_details { Ok(value.clone()) } else { Ok(CommonMandateReference { payments: None, payouts: None, }) } } #[cfg(feature = "v2")] pub fn set_payment_method_type(&mut self, payment_method_type: common_enums::PaymentMethod) { self.payment_method_type = Some(payment_method_type); } #[cfg(feature = "v2")] pub fn set_payment_method_subtype( &mut self, payment_method_subtype: common_enums::PaymentMethodType, ) { self.payment_method_subtype = Some(payment_method_subtype); } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl super::behaviour::Conversion for PaymentMethod { type DstType = diesel_models::payment_method::PaymentMethod; type NewDstType = diesel_models::payment_method::PaymentMethodNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let (vault_type, external_vault_source) = self.vault_source_details.into(); Ok(Self::DstType { customer_id: self.customer_id, merchant_id: self.merchant_id, payment_method_id: self.payment_method_id, accepted_currency: self.accepted_currency, scheme: self.scheme, token: self.token, cardholder_name: self.cardholder_name, issuer_name: self.issuer_name, issuer_country: self.issuer_country, payer_country: self.payer_country, is_stored: self.is_stored, swift_code: self.swift_code, direct_debit_token: self.direct_debit_token, created_at: self.created_at, last_modified: self.last_modified, payment_method: self.payment_method, payment_method_type: self.payment_method_type, payment_method_issuer: self.payment_method_issuer, payment_method_issuer_code: self.payment_method_issuer_code, metadata: self.metadata, payment_method_data: self.payment_method_data.map(|val| val.into()), locker_id: self.locker_id, last_used_at: self.last_used_at, connector_mandate_details: self.connector_mandate_details, customer_acceptance: self.customer_acceptance, status: self.status, network_transaction_id: self.network_transaction_id, client_secret: self.client_secret, payment_method_billing_address: self .payment_method_billing_address .map(|val| val.into()), updated_by: self.updated_by, version: self.version, network_token_requestor_reference_id: self.network_token_requestor_reference_id, network_token_locker_id: self.network_token_locker_id, network_token_payment_method_data: self .network_token_payment_method_data .map(|val| val.into()), external_vault_source, vault_type, }) } async fn convert_back( state: &keymanager::KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { // Decrypt encrypted fields first let ( payment_method_data, payment_method_billing_address, network_token_payment_method_data, ) = async { let payment_method_data = item .payment_method_data .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?; let payment_method_billing_address = item .payment_method_billing_address .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?; let network_token_payment_method_data = item .network_token_payment_method_data .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?; Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>(( payment_method_data, payment_method_billing_address, network_token_payment_method_data, )) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting payment method data".to_string(), })?; let vault_source_details = PaymentMethodVaultSourceDetails::try_from(( item.vault_type, item.external_vault_source, ))?; // Construct the domain type Ok(Self { customer_id: item.customer_id, merchant_id: item.merchant_id, payment_method_id: item.payment_method_id, accepted_currency: item.accepted_currency, scheme: item.scheme, token: item.token, cardholder_name: item.cardholder_name, issuer_name: item.issuer_name, issuer_country: item.issuer_country, payer_country: item.payer_country, is_stored: item.is_stored, swift_code: item.swift_code, direct_debit_token: item.direct_debit_token, created_at: item.created_at, last_modified: item.last_modified, payment_method: item.payment_method, payment_method_type: item.payment_method_type, payment_method_issuer: item.payment_method_issuer, payment_method_issuer_code: item.payment_method_issuer_code, metadata: item.metadata, payment_method_data, locker_id: item.locker_id, last_used_at: item.last_used_at, connector_mandate_details: item.connector_mandate_details, customer_acceptance: item.customer_acceptance, status: item.status, network_transaction_id: item.network_transaction_id, client_secret: item.client_secret, payment_method_billing_address, updated_by: item.updated_by, version: item.version, network_token_requestor_reference_id: item.network_token_requestor_reference_id, network_token_locker_id: item.network_token_locker_id, network_token_payment_method_data, vault_source_details, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let (vault_type, external_vault_source) = self.vault_source_details.into(); Ok(Self::NewDstType { customer_id: self.customer_id, merchant_id: self.merchant_id, payment_method_id: self.payment_method_id, accepted_currency: self.accepted_currency, scheme: self.scheme, token: self.token, cardholder_name: self.cardholder_name, issuer_name: self.issuer_name, issuer_country: self.issuer_country, payer_country: self.payer_country, is_stored: self.is_stored, swift_code: self.swift_code, direct_debit_token: self.direct_debit_token, created_at: self.created_at, last_modified: self.last_modified, payment_method: self.payment_method, payment_method_type: self.payment_method_type, payment_method_issuer: self.payment_method_issuer, payment_method_issuer_code: self.payment_method_issuer_code, metadata: self.metadata, payment_method_data: self.payment_method_data.map(|val| val.into()), locker_id: self.locker_id, last_used_at: self.last_used_at, connector_mandate_details: self.connector_mandate_details, customer_acceptance: self.customer_acceptance, status: self.status, network_transaction_id: self.network_transaction_id, client_secret: self.client_secret, payment_method_billing_address: self .payment_method_billing_address .map(|val| val.into()), updated_by: self.updated_by, version: self.version, network_token_requestor_reference_id: self.network_token_requestor_reference_id, network_token_locker_id: self.network_token_locker_id, network_token_payment_method_data: self .network_token_payment_method_data .map(|val| val.into()), external_vault_source, vault_type, }) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl super::behaviour::Conversion for PaymentMethod { type DstType = diesel_models::payment_method::PaymentMethod; type NewDstType = diesel_models::payment_method::PaymentMethodNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(Self::DstType { customer_id: self.customer_id, merchant_id: self.merchant_id, id: self.id, created_at: self.created_at, last_modified: self.last_modified, payment_method_type_v2: self.payment_method_type, payment_method_subtype: self.payment_method_subtype, payment_method_data: self.payment_method_data.map(|val| val.into()), locker_id: self.locker_id.map(|id| id.get_string_repr().clone()), last_used_at: self.last_used_at, connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()), customer_acceptance: self.customer_acceptance, status: self.status, network_transaction_id: self.network_transaction_id, client_secret: self.client_secret, payment_method_billing_address: self .payment_method_billing_address .map(|val| val.into()), updated_by: self.updated_by, locker_fingerprint_id: self.locker_fingerprint_id, version: self.version, network_token_requestor_reference_id: self.network_token_requestor_reference_id, network_token_locker_id: self.network_token_locker_id, network_token_payment_method_data: self .network_token_payment_method_data .map(|val| val.into()), external_vault_source: self.external_vault_source, external_vault_token_data: self.external_vault_token_data.map(|val| val.into()), vault_type: self.vault_type, }) } async fn convert_back( state: &keymanager::KeyManagerState, storage_model: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { use common_utils::ext_traits::ValueExt; async { let decrypted_data = crypto_operation( state, type_name!(Self::DstType), CryptoOperation::BatchDecrypt(EncryptedPaymentMethod::to_encryptable( EncryptedPaymentMethod { payment_method_data: storage_model.payment_method_data, payment_method_billing_address: storage_model .payment_method_billing_address, network_token_payment_method_data: storage_model .network_token_payment_method_data, external_vault_token_data: storage_model.external_vault_token_data, }, )), key_manager_identifier, key.peek(), ) .await .and_then(|val| val.try_into_batchoperation())?; let data = EncryptedPaymentMethod::from_encryptable(decrypted_data) .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Invalid batch operation data")?; let payment_method_billing_address = data .payment_method_billing_address .map(|billing| { billing.deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing Address")?; let payment_method_data = data .payment_method_data .map(|payment_method_data| { payment_method_data .deserialize_inner_value(|value| value.parse_value("Payment Method Data")) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing Payment Method Data")?; let network_token_payment_method_data = data .network_token_payment_method_data .map(|network_token_payment_method_data| { network_token_payment_method_data.deserialize_inner_value(|value| { value.parse_value("Network token Payment Method Data") }) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing Network token Payment Method Data")?; let external_vault_token_data = data .external_vault_token_data .map(|external_vault_token_data| { external_vault_token_data.deserialize_inner_value(|value| { value.parse_value("External Vault Token Data") }) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing External Vault Token Data")?; Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { customer_id: storage_model.customer_id, merchant_id: storage_model.merchant_id, id: storage_model.id, created_at: storage_model.created_at, last_modified: storage_model.last_modified, payment_method_type: storage_model.payment_method_type_v2, payment_method_subtype: storage_model.payment_method_subtype, payment_method_data, locker_id: storage_model.locker_id.map(VaultId::generate), last_used_at: storage_model.last_used_at, connector_mandate_details: storage_model.connector_mandate_details.map(From::from), customer_acceptance: storage_model.customer_acceptance, status: storage_model.status, network_transaction_id: storage_model.network_transaction_id, client_secret: storage_model.client_secret, payment_method_billing_address, updated_by: storage_model.updated_by, locker_fingerprint_id: storage_model.locker_fingerprint_id, version: storage_model.version, network_token_requestor_reference_id: storage_model .network_token_requestor_reference_id, network_token_locker_id: storage_model.network_token_locker_id, network_token_payment_method_data, external_vault_source: storage_model.external_vault_source, external_vault_token_data, vault_type: storage_model.vault_type, }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting payment method data".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(Self::NewDstType { customer_id: self.customer_id, merchant_id: self.merchant_id, id: self.id, created_at: self.created_at, last_modified: self.last_modified, payment_method_type_v2: self.payment_method_type, payment_method_subtype: self.payment_method_subtype, payment_method_data: self.payment_method_data.map(|val| val.into()), locker_id: self.locker_id.map(|id| id.get_string_repr().clone()), last_used_at: self.last_used_at, connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()), customer_acceptance: self.customer_acceptance, status: self.status, network_transaction_id: self.network_transaction_id, client_secret: self.client_secret, payment_method_billing_address: self .payment_method_billing_address .map(|val| val.into()), updated_by: self.updated_by, locker_fingerprint_id: self.locker_fingerprint_id, version: self.version, network_token_requestor_reference_id: self.network_token_requestor_reference_id, network_token_locker_id: self.network_token_locker_id, network_token_payment_method_data: self .network_token_payment_method_data .map(|val| val.into()), external_vault_token_data: self.external_vault_token_data.map(|val| val.into()), vault_type: self.vault_type, }) } } #[cfg(feature = "v2")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct PaymentMethodSession { pub id: id_type::GlobalPaymentMethodSessionId, pub customer_id: id_type::GlobalCustomerId, #[encrypt(ty = Value)] pub billing: Option<Encryptable<Address>>, pub return_url: Option<common_utils::types::Url>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, pub tokenization_data: Option<pii::SecretSerdeValue>, pub expires_at: PrimitiveDateTime, pub associated_payment_methods: Option<Vec<String>>, pub associated_payment: Option<id_type::GlobalPaymentId>, pub associated_token_id: Option<id_type::GlobalTokenId>, } #[cfg(feature = "v2")] #[async_trait::async_trait] impl super::behaviour::Conversion for PaymentMethodSession { type DstType = diesel_models::payment_methods_session::PaymentMethodSession; type NewDstType = diesel_models::payment_methods_session::PaymentMethodSession; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(Self::DstType { id: self.id, customer_id: self.customer_id, billing: self.billing.map(|val| val.into()), psp_tokenization: self.psp_tokenization, network_tokenization: self.network_tokenization, tokenization_data: self.tokenization_data, expires_at: self.expires_at, associated_payment_methods: self.associated_payment_methods, associated_payment: self.associated_payment, return_url: self.return_url, associated_token_id: self.associated_token_id, }) } async fn convert_back( state: &keymanager::KeyManagerState, storage_model: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { use common_utils::ext_traits::ValueExt; async { let decrypted_data = crypto_operation( state, type_name!(Self::DstType), CryptoOperation::BatchDecrypt(EncryptedPaymentMethodSession::to_encryptable( EncryptedPaymentMethodSession { billing: storage_model.billing, }, )), key_manager_identifier, key.peek(), ) .await .and_then(|val| val.try_into_batchoperation())?; let data = EncryptedPaymentMethodSession::from_encryptable(decrypted_data) .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Invalid batch operation data")?; let billing = data .billing .map(|billing| { billing.deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing Address")?; Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { id: storage_model.id, customer_id: storage_model.customer_id, billing, psp_tokenization: storage_model.psp_tokenization, network_tokenization: storage_model.network_tokenization, tokenization_data: storage_model.tokenization_data, expires_at: storage_model.expires_at, associated_payment_methods: storage_model.associated_payment_methods, associated_payment: storage_model.associated_payment, return_url: storage_model.return_url, associated_token_id: storage_model.associated_token_id, }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting payment method data".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(Self::NewDstType { id: self.id, customer_id: self.customer_id, billing: self.billing.map(|val| val.into()), psp_tokenization: self.psp_tokenization, network_tokenization: self.network_tokenization, tokenization_data: self.tokenization_data, expires_at: self.expires_at, associated_payment_methods: self.associated_payment_methods, associated_payment: self.associated_payment, return_url: self.return_url, associated_token_id: self.associated_token_id, }) } } #[async_trait::async_trait] pub trait PaymentMethodInterface { type Error; #[cfg(feature = "v1")] async fn find_payment_method( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentMethod, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_method( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentMethod, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_method_by_locker_id( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, locker_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentMethod, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<PaymentMethod>, Self::Error>; // Need to fix this once we start moving to v2 for payment method #[cfg(feature = "v2")] async fn find_payment_method_list_by_global_customer_id( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<PaymentMethod>, Self::Error>; #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<PaymentMethod>, Self::Error>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<PaymentMethod>, Self::Error>; #[cfg(feature = "v1")] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, Self::Error>; async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, Self::Error>; async fn insert_payment_method( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, payment_method: PaymentMethod, storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentMethod, Self::Error>; async fn update_payment_method( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, payment_method: PaymentMethod, payment_method_update: PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentMethod, Self::Error>; #[cfg(feature = "v2")] async fn delete_payment_method( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, payment_method: PaymentMethod, ) -> CustomResult<PaymentMethod, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_method_by_fingerprint_id( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<PaymentMethod, Self::Error>; #[cfg(feature = "v1")] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<PaymentMethod, Self::Error>; } #[cfg(feature = "v2")] pub enum PaymentMethodsSessionUpdateEnum { GeneralUpdate { billing: Box<Option<Encryptable<Address>>>, psp_tokenization: Option<common_types::payment_methods::PspTokenization>, network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, tokenization_data: Option<pii::SecretSerdeValue>, }, UpdateAssociatedPaymentMethods { associated_payment_methods: Option<Vec<String>>, }, } #[cfg(feature = "v2")] impl From<PaymentMethodsSessionUpdateEnum> for PaymentMethodsSessionUpdateInternal { fn from(update: PaymentMethodsSessionUpdateEnum) -> Self { match update { PaymentMethodsSessionUpdateEnum::GeneralUpdate { billing, psp_tokenization, network_tokenization, tokenization_data, } => Self { billing: *billing, psp_tokenization, network_tokenization, tokenization_data, associated_payment_methods: None, }, PaymentMethodsSessionUpdateEnum::UpdateAssociatedPaymentMethods { associated_payment_methods, } => Self { billing: None, psp_tokenization: None, network_tokenization: None, tokenization_data: None, associated_payment_methods, }, } } } #[cfg(feature = "v2")] impl PaymentMethodSession { pub fn apply_changeset(self, update_session: PaymentMethodsSessionUpdateInternal) -> Self { let Self { id, customer_id, billing, psp_tokenization, network_tokenization, tokenization_data, expires_at, return_url, associated_payment_methods, associated_payment, associated_token_id, } = self; Self { id, customer_id, billing: update_session.billing.or(billing), psp_tokenization: update_session.psp_tokenization.or(psp_tokenization), network_tokenization: update_session.network_tokenization.or(network_tokenization), tokenization_data: update_session.tokenization_data.or(tokenization_data), expires_at, return_url, associated_payment_methods: update_session .associated_payment_methods .or(associated_payment_methods), associated_payment, associated_token_id, } } } #[cfg(feature = "v2")] pub struct PaymentMethodsSessionUpdateInternal { pub billing: Option<Encryptable<Address>>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, pub tokenization_data: Option<pii::SecretSerdeValue>, pub associated_payment_methods: Option<Vec<String>>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct ConnectorCustomerDetails { pub connector_customer_id: String, pub merchant_connector_id: id_type::MerchantConnectorAccountId, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PaymentMethodCustomerMigrate { pub customer: customers::CustomerRequest, pub connector_customer_details: Option<Vec<ConnectorCustomerDetails>>, } #[cfg(feature = "v1")] impl TryFrom<(payment_methods::PaymentMethodRecord, id_type::MerchantId)> for PaymentMethodCustomerMigrate { type Error = error_stack::Report<ValidationError>; fn try_from( value: (payment_methods::PaymentMethodRecord, id_type::MerchantId), ) -> Result<Self, Self::Error> { let (record, merchant_id) = value; let connector_customer_details = record .connector_customer_id .and_then(|connector_customer_id| { // Handle single merchant_connector_id record .merchant_connector_id .as_ref() .map(|merchant_connector_id| { Ok(vec![ConnectorCustomerDetails { connector_customer_id: connector_customer_id.clone(), merchant_connector_id: merchant_connector_id.clone(), }]) }) // Handle comma-separated merchant_connector_ids .or_else(|| { record .merchant_connector_ids .as_ref() .map(|merchant_connector_ids_str| { merchant_connector_ids_str .split(',') .map(|id| id.trim()) .filter(|id| !id.is_empty()) .map(|merchant_connector_id| { id_type::MerchantConnectorAccountId::wrap( merchant_connector_id.to_string(), ) .map_err(|_| { error_stack::report!(ValidationError::InvalidValue { message: format!( "Invalid merchant_connector_account_id: {merchant_connector_id}" ), }) }) .map( |merchant_connector_id| ConnectorCustomerDetails { connector_customer_id: connector_customer_id .clone(), merchant_connector_id, }, ) }) .collect::<Result<Vec<_>, _>>() }) }) }) .transpose()?; Ok(Self { customer: customers::CustomerRequest { customer_id: Some(record.customer_id), merchant_id, name: record.name, email: record.email, phone: record.phone, description: None, phone_country_code: record.phone_country_code, address: Some(payments::AddressDetails { city: record.billing_address_city, country: record.billing_address_country, line1: record.billing_address_line1, line2: record.billing_address_line2, state: record.billing_address_state, line3: record.billing_address_line3, zip: record.billing_address_zip, first_name: record.billing_address_first_name, last_name: record.billing_address_last_name, origin_zip: None, }), metadata: None, tax_registration_id: None, }, connector_customer_details, }) } } #[cfg(feature = "v1")] impl ForeignTryFrom<(&[payment_methods::PaymentMethodRecord], id_type::MerchantId)> for Vec<PaymentMethodCustomerMigrate> { type Error = error_stack::Report<ValidationError>; fn foreign_try_from( (records, merchant_id): (&[payment_methods::PaymentMethodRecord], id_type::MerchantId), ) -> Result<Self, Self::Error> { let (customers_migration, migration_errors): (Self, Vec<_>) = records .iter() .map(|record| { PaymentMethodCustomerMigrate::try_from((record.clone(), merchant_id.clone())) }) .fold((Self::new(), Vec::new()), |mut acc, result| { match result { Ok(customer) => acc.0.push(customer), Err(e) => acc.1.push(e.to_string()), } acc }); migration_errors .is_empty() .then_some(customers_migration) .ok_or_else(|| { error_stack::report!(ValidationError::InvalidValue { message: migration_errors.join(", "), }) }) } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Default)] pub enum PaymentMethodVaultSourceDetails { ExternalVault { external_vault_source: id_type::MerchantConnectorAccountId, }, #[default] InternalVault, } #[cfg(feature = "v1")] impl TryFrom<( Option<storage_enums::VaultType>, Option<id_type::MerchantConnectorAccountId>, )> for PaymentMethodVaultSourceDetails { type Error = error_stack::Report<ValidationError>; fn try_from( value: ( Option<storage_enums::VaultType>, Option<id_type::MerchantConnectorAccountId>, ), ) -> Result<Self, Self::Error> { match value { (Some(storage_enums::VaultType::External), Some(external_vault_source)) => { Ok(Self::ExternalVault { external_vault_source, }) } (Some(storage_enums::VaultType::External), None) => { Err(ValidationError::MissingRequiredField { field_name: "external vault mca id".to_string(), } .into()) } (Some(storage_enums::VaultType::Internal), _) | (None, _) => Ok(Self::InternalVault), // defaulting to internal vault if vault type is none } } } #[cfg(feature = "v1")] impl From<PaymentMethodVaultSourceDetails> for ( Option<storage_enums::VaultType>, Option<id_type::MerchantConnectorAccountId>, ) { fn from(value: PaymentMethodVaultSourceDetails) -> Self { match value { PaymentMethodVaultSourceDetails::ExternalVault { external_vault_source, } => ( Some(storage_enums::VaultType::External), Some(external_vault_source), ), PaymentMethodVaultSourceDetails::InternalVault => { (Some(storage_enums::VaultType::Internal), None) } } } } #[cfg(feature = "v1")] #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use id_type::MerchantConnectorAccountId; use super::*; fn get_payment_method_with_mandate_data( mandate_data: Option<serde_json::Value>, ) -> PaymentMethod { let payment_method = PaymentMethod { customer_id: id_type::CustomerId::default(), merchant_id: id_type::MerchantId::default(), payment_method_id: String::from("abc"), accepted_currency: None, scheme: None, token: None, cardholder_name: None, issuer_name: None, issuer_country: None, payer_country: None, is_stored: None, swift_code: None, direct_debit_token: None, created_at: common_utils::date_time::now(), last_modified: common_utils::date_time::now(), payment_method: None, payment_method_type: None, payment_method_issuer: None, payment_method_issuer_code: None, metadata: None, payment_method_data: None, locker_id: None, last_used_at: common_utils::date_time::now(), connector_mandate_details: mandate_data, customer_acceptance: None, status: storage_enums::PaymentMethodStatus::Active, network_transaction_id: None, client_secret: None, payment_method_billing_address: None, updated_by: None, version: common_enums::ApiVersion::V1, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, vault_source_details: Default::default(), }; payment_method.clone() } #[test] fn test_get_common_mandate_reference_payments_only() { let connector_mandate_details = serde_json::json!({ "mca_kGz30G8B95MxRwmeQqy6": { "mandate_metadata": null, "payment_method_type": null, "connector_mandate_id": "RcBww0a02c-R22w22w22wNJV-V14o20u24y18sTB18sB24y06g04eVZ04e20u14o", "connector_mandate_status": "active", "original_payment_authorized_amount": 51, "original_payment_authorized_currency": "USD", "connector_mandate_request_reference_id": "RowbU9ULN9H59bMhWk" } }); let payment_method = get_payment_method_with_mandate_data(Some(connector_mandate_details)); let result = payment_method.get_common_mandate_reference(); assert!(result.is_ok()); let common_mandate = result.unwrap(); assert!(common_mandate.payments.is_some()); assert!(common_mandate.payouts.is_none()); let payments = common_mandate.payments.unwrap(); let result_mca = MerchantConnectorAccountId::wrap("mca_kGz30G8B95MxRwmeQqy6".to_string()); assert!( result_mca.is_ok(), "Expected Ok, but got Err: {result_mca:?}", ); let mca = result_mca.unwrap(); assert!(payments.0.contains_key(&mca)); } #[test] fn test_get_common_mandate_reference_empty_details() { let payment_method = get_payment_method_with_mandate_data(None); let result = payment_method.get_common_mandate_reference(); assert!(result.is_ok()); let common_mandate = result.unwrap(); assert!(common_mandate.payments.is_none()); assert!(common_mandate.payouts.is_none()); } #[test] fn test_get_common_mandate_reference_payouts_only() { let connector_mandate_details = serde_json::json!({ "payouts": { "mca_DAHVXbXpbYSjnL7fQWEs": { "transfer_method_id": "TRM-678ab3997b16cb7cd" } } }); let payment_method = get_payment_method_with_mandate_data(Some(connector_mandate_details)); let result = payment_method.get_common_mandate_reference(); assert!(result.is_ok()); let common_mandate = result.unwrap(); assert!(common_mandate.payments.is_some()); assert!(common_mandate.payouts.is_some()); let payouts = common_mandate.payouts.unwrap(); let result_mca = MerchantConnectorAccountId::wrap("mca_DAHVXbXpbYSjnL7fQWEs".to_string()); assert!( result_mca.is_ok(), "Expected Ok, but got Err: {result_mca:?}", ); let mca = result_mca.unwrap(); assert!(payouts.0.contains_key(&mca)); } #[test] fn test_get_common_mandate_reference_invalid_data() { let connector_mandate_details = serde_json::json!("invalid"); let payment_method = get_payment_method_with_mandate_data(Some(connector_mandate_details)); let result = payment_method.get_common_mandate_reference(); assert!(result.is_err()); } #[test] fn test_get_common_mandate_reference_with_payments_and_payouts_details() { let connector_mandate_details = serde_json::json!({ "mca_kGz30G8B95MxRwmeQqy6": { "mandate_metadata": null, "payment_method_type": null, "connector_mandate_id": "RcBww0a02c-R22w22w22wNJV-V14o20u24y18sTB18sB24y06g04eVZ04e20u14o", "connector_mandate_status": "active", "original_payment_authorized_amount": 51, "original_payment_authorized_currency": "USD", "connector_mandate_request_reference_id": "RowbU9ULN9H59bMhWk" }, "payouts": { "mca_DAHVXbXpbYSjnL7fQWEs": { "transfer_method_id": "TRM-678ab3997b16cb7cd" } } }); let payment_method = get_payment_method_with_mandate_data(Some(connector_mandate_details)); let result = payment_method.get_common_mandate_reference(); assert!(result.is_ok()); let common_mandate = result.unwrap(); assert!(common_mandate.payments.is_some()); assert!(common_mandate.payouts.is_some()); } }
crates/hyperswitch_domain_models/src/payment_methods.rs
hyperswitch_domain_models::src::payment_methods
10,921
true
// File: crates/hyperswitch_domain_models/src/types.rs // Module: hyperswitch_domain_models::src::types pub use diesel_models::types::OrderDetailsWithAmount; use crate::{ router_data::{AccessToken, AccessTokenAuthenticationResponse, RouterData}, router_data_v2::{self, RouterDataV2}, router_flow_types::{ mandate_revoke::MandateRevoke, revenue_recovery::InvoiceRecordBack, subscriptions::{ GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate, }, AccessTokenAuth, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, Authorize, AuthorizeSessionToken, BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, Execute, ExtendAuthorization, ExternalVaultProxy, GiftCardBalanceCheck, IncrementalAuthorization, PSync, PaymentMethodToken, PostAuthenticate, PostCaptureVoid, PostSessionTokens, PreAuthenticate, PreProcessing, RSync, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, VerifyWebhookSource, Void, }, router_request_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData, VaultResponseData, VerifyWebhookSourceResponseData, }, }; #[cfg(feature = "payouts")] pub use crate::{router_request_types::PayoutsData, router_response_types::PayoutsResponseData}; pub type PaymentsAuthorizeRouterData = RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; pub type ExternalVaultProxyPaymentsRouterData = RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>; pub type PaymentsAuthorizeSessionTokenRouterData = RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsPreProcessingRouterData = RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; pub type PaymentsPreAuthenticateRouterData = RouterData<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>; pub type PaymentsAuthenticateRouterData = RouterData<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>; pub type PaymentsPostAuthenticateRouterData = RouterData<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>; pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsCancelPostCaptureRouterData = RouterData<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type SetupMandateRouterData = RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; pub type RefundExecuteRouterData = RouterData<Execute, RefundsData, RefundsResponseData>; pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>; pub type TokenizationRouterData = RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>; pub type ConnectorCustomerRouterData = RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; pub type PaymentsCompleteAuthorizeRouterData = RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; pub type PaymentsTaxCalculationRouterData = RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; pub type AccessTokenAuthenticationRouterData = RouterData< AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, >; pub type PaymentsGiftCardBalanceCheckRouterData = RouterData< GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, >; pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; pub type PaymentsPostSessionTokensRouterData = RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>; pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>; pub type PaymentsUpdateMetadataRouterData = RouterData<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>; pub type CreateOrderRouterData = RouterData<CreateOrder, CreateOrderRequestData, PaymentsResponseData>; pub type UasPostAuthenticationRouterData = RouterData<PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData>; pub type UasPreAuthenticationRouterData = RouterData<PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData>; pub type UasAuthenticationConfirmationRouterData = RouterData< AuthenticationConfirmation, UasConfirmationRequestData, UasAuthenticationResponseData, >; pub type MandateRevokeRouterData = RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; pub type PaymentsIncrementalAuthorizationRouterData = RouterData< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >; pub type PaymentsExtendAuthorizationRouterData = RouterData<ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData>; pub type SdkSessionUpdateRouterData = RouterData<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>; pub type VerifyWebhookSourceRouterData = RouterData< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >; #[cfg(feature = "payouts")] pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>; pub type InvoiceRecordBackRouterData = RouterData<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>; pub type GetSubscriptionPlansRouterData = RouterData<GetSubscriptionPlans, GetSubscriptionPlansRequest, GetSubscriptionPlansResponse>; pub type GetSubscriptionEstimateRouterData = RouterData< GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse, >; pub type UasAuthenticationRouterData = RouterData<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>; pub type BillingConnectorPaymentsSyncRouterData = RouterData< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, >; pub type BillingConnectorInvoiceSyncRouterData = RouterData< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, >; pub type BillingConnectorInvoiceSyncRouterDataV2 = RouterDataV2< BillingConnectorInvoiceSync, router_data_v2::flow_common_types::BillingConnectorInvoiceSyncFlowData, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, >; pub type BillingConnectorPaymentsSyncRouterDataV2 = RouterDataV2< BillingConnectorPaymentsSync, router_data_v2::flow_common_types::BillingConnectorPaymentsSyncFlowData, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, >; pub type InvoiceRecordBackRouterDataV2 = RouterDataV2< InvoiceRecordBack, router_data_v2::flow_common_types::InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse, >; pub type GetSubscriptionPlanPricesRouterData = RouterData< GetSubscriptionPlanPrices, GetSubscriptionPlanPricesRequest, GetSubscriptionPlanPricesResponse, >; pub type VaultRouterData<F> = RouterData<F, VaultRequestData, VaultResponseData>; pub type VaultRouterDataV2<F> = RouterDataV2< F, router_data_v2::flow_common_types::VaultConnectorFlowData, VaultRequestData, VaultResponseData, >; pub type ExternalVaultProxyPaymentsRouterDataV2 = RouterDataV2< ExternalVaultProxy, router_data_v2::flow_common_types::ExternalVaultProxyFlowData, ExternalVaultProxyPaymentsData, PaymentsResponseData, >; pub type SubscriptionCreateRouterData = RouterData<SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse>;
crates/hyperswitch_domain_models/src/types.rs
hyperswitch_domain_models::src::types
2,035
true
// File: crates/hyperswitch_domain_models/src/refunds.rs // Module: hyperswitch_domain_models::src::refunds #[cfg(feature = "v2")] use crate::business_profile::Profile; #[cfg(feature = "v1")] use crate::errors; #[cfg(feature = "v1")] pub struct RefundListConstraints { pub payment_id: Option<common_utils::id_type::PaymentId>, pub refund_id: Option<String>, pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>, pub limit: Option<i64>, pub offset: Option<i64>, pub time_range: Option<common_utils::types::TimeRange>, pub amount_filter: Option<api_models::payments::AmountFilter>, pub connector: Option<Vec<String>>, pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, pub currency: Option<Vec<common_enums::Currency>>, pub refund_status: Option<Vec<common_enums::RefundStatus>>, } #[cfg(feature = "v2")] pub struct RefundListConstraints { pub payment_id: Option<common_utils::id_type::GlobalPaymentId>, pub refund_id: Option<common_utils::id_type::GlobalRefundId>, pub profile_id: common_utils::id_type::ProfileId, pub limit: Option<i64>, pub offset: Option<i64>, pub time_range: Option<common_utils::types::TimeRange>, pub amount_filter: Option<api_models::payments::AmountFilter>, pub connector: Option<Vec<String>>, pub connector_id_list: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, pub currency: Option<Vec<common_enums::Currency>>, pub refund_status: Option<Vec<common_enums::RefundStatus>>, } #[cfg(feature = "v1")] impl TryFrom<( api_models::refunds::RefundListRequest, Option<Vec<common_utils::id_type::ProfileId>>, )> for RefundListConstraints { type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>; fn try_from( (value, auth_profile_id_list): ( api_models::refunds::RefundListRequest, Option<Vec<common_utils::id_type::ProfileId>>, ), ) -> Result<Self, Self::Error> { let api_models::refunds::RefundListRequest { connector, currency, refund_status, payment_id, refund_id, profile_id, limit, offset, time_range, amount_filter, merchant_connector_id, } = value; let profile_id_from_request_body = profile_id; let profile_id_list = match (profile_id_from_request_body, auth_profile_id_list) { (None, None) => None, (None, Some(auth_profile_id_list)) => Some(auth_profile_id_list), (Some(profile_id_from_request_body), None) => Some(vec![profile_id_from_request_body]), (Some(profile_id_from_request_body), Some(auth_profile_id_list)) => { let profile_id_from_request_body_is_available_in_auth_profile_id_list = auth_profile_id_list.contains(&profile_id_from_request_body); if profile_id_from_request_body_is_available_in_auth_profile_id_list { Some(vec![profile_id_from_request_body]) } else { // This scenario is very unlikely to happen return Err(error_stack::Report::new( errors::api_error_response::ApiErrorResponse::PreconditionFailed { message: format!( "Access not available for the given profile_id {profile_id_from_request_body:?}", ), }, )); } } }; Ok(Self { payment_id, refund_id, profile_id: profile_id_list, limit, offset, time_range, amount_filter, connector, merchant_connector_id, currency, refund_status, }) } } #[cfg(feature = "v2")] impl From<(api_models::refunds::RefundListRequest, Profile)> for RefundListConstraints { fn from((value, profile): (api_models::refunds::RefundListRequest, Profile)) -> Self { let api_models::refunds::RefundListRequest { payment_id, refund_id, connector, currency, refund_status, limit, offset, time_range, amount_filter, connector_id_list, } = value; Self { payment_id, refund_id, profile_id: profile.get_id().to_owned(), limit, offset, time_range, amount_filter, connector, connector_id_list, currency, refund_status, } } }
crates/hyperswitch_domain_models/src/refunds.rs
hyperswitch_domain_models::src::refunds
1,009
true
// File: crates/hyperswitch_domain_models/src/payment_address.rs // Module: hyperswitch_domain_models::src::payment_address use crate::address::Address; #[derive(Clone, Default, Debug, serde::Serialize)] pub struct PaymentAddress { shipping: Option<Address>, billing: Option<Address>, unified_payment_method_billing: Option<Address>, payment_method_billing: Option<Address>, } impl PaymentAddress { pub fn new( shipping: Option<Address>, billing: Option<Address>, payment_method_billing: Option<Address>, should_unify_address: Option<bool>, ) -> Self { // billing -> .billing, this is the billing details passed in the root of payments request // payment_method_billing -> .payment_method_data.billing let unified_payment_method_billing = if should_unify_address.unwrap_or(true) { // Merge the billing details field from both `payment.billing` and `payment.payment_method_data.billing` // The unified payment_method_billing will be used as billing address and passed to the connector module // This unification is required in order to provide backwards compatibility // so that if `payment.billing` is passed it should be sent to the connector module // Unify the billing details with `payment_method_data.billing` payment_method_billing .as_ref() .map(|payment_method_billing| { payment_method_billing .clone() .unify_address(billing.as_ref()) }) .or(billing.clone()) } else { payment_method_billing.clone() }; Self { shipping, billing, unified_payment_method_billing, payment_method_billing, } } pub fn get_shipping(&self) -> Option<&Address> { self.shipping.as_ref() } pub fn get_payment_method_billing(&self) -> Option<&Address> { self.unified_payment_method_billing.as_ref() } /// Unify the billing details from `payment_method_data.[payment_method_data].billing details`. /// Here the fields passed in payment_method_data_billing takes precedence pub fn unify_with_payment_method_data_billing( self, payment_method_data_billing: Option<Address>, ) -> Self { // Unify the billing details with `payment_method_data.billing_details` let unified_payment_method_billing = payment_method_data_billing .map(|payment_method_data_billing| { payment_method_data_billing.unify_address(self.get_payment_method_billing()) }) .or(self.get_payment_method_billing().cloned()); Self { shipping: self.shipping, billing: self.billing, unified_payment_method_billing, payment_method_billing: self.payment_method_billing, } } /// Unify the billing details from `payment_method_data.[payment_method_data].billing details`. /// Here the `self` takes precedence pub fn unify_with_payment_data_billing( self, other_payment_method_billing: Option<Address>, ) -> Self { let unified_payment_method_billing = self .get_payment_method_billing() .map(|payment_method_billing| { payment_method_billing .clone() .unify_address(other_payment_method_billing.as_ref()) }) .or(other_payment_method_billing); Self { shipping: self.shipping, billing: self.billing, unified_payment_method_billing, payment_method_billing: self.payment_method_billing, } } pub fn get_request_payment_method_billing(&self) -> Option<&Address> { self.payment_method_billing.as_ref() } pub fn get_payment_billing(&self) -> Option<&Address> { self.billing.as_ref() } }
crates/hyperswitch_domain_models/src/payment_address.rs
hyperswitch_domain_models::src::payment_address
767
true
// File: crates/hyperswitch_domain_models/src/merchant_account.rs // Module: hyperswitch_domain_models::src::merchant_account use common_utils::{ crypto::{OptionalEncryptableName, OptionalEncryptableValue}, date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, ext_traits::ValueExt, pii, type_name, types::keymanager::{self}, }; use diesel_models::{ enums::MerchantStorageScheme, merchant_account::MerchantAccountUpdateInternal, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use router_env::logger; use crate::{ behaviour::Conversion, merchant_key_store, type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, }; #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct MerchantAccount { merchant_id: common_utils::id_type::MerchantId, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub merchant_name: OptionalEncryptableName, pub merchant_details: OptionalEncryptableValue, pub webhook_details: Option<diesel_models::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: String, pub storage_scheme: MerchantStorageScheme, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub frm_routing_algorithm: Option<serde_json::Value>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub intent_fulfillment_time: Option<i64>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: diesel_models::enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v1")] #[derive(Clone)] /// Set the private fields of merchant account pub struct MerchantAccountSetter { pub merchant_id: common_utils::id_type::MerchantId, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub merchant_name: OptionalEncryptableName, pub merchant_details: OptionalEncryptableValue, pub webhook_details: Option<diesel_models::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: String, pub storage_scheme: MerchantStorageScheme, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub frm_routing_algorithm: Option<serde_json::Value>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub intent_fulfillment_time: Option<i64>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: diesel_models::enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v1")] impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { Self { merchant_id: item.merchant_id, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item.merchant_name, merchant_details: item.merchant_details, webhook_details: item.webhook_details, sub_merchants_enabled: item.sub_merchants_enabled, parent_merchant_id: item.parent_merchant_id, publishable_key: item.publishable_key, storage_scheme: item.storage_scheme, locker_id: item.locker_id, metadata: item.metadata, routing_algorithm: item.routing_algorithm, primary_business_details: item.primary_business_details, frm_routing_algorithm: item.frm_routing_algorithm, created_at: item.created_at, modified_at: item.modified_at, intent_fulfillment_time: item.intent_fulfillment_time, payout_routing_algorithm: item.payout_routing_algorithm, organization_id: item.organization_id, is_recon_enabled: item.is_recon_enabled, default_profile: item.default_profile, recon_status: item.recon_status, payment_link_config: item.payment_link_config, pm_collect_link_config: item.pm_collect_link_config, version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, merchant_account_type: item.merchant_account_type, } } } #[cfg(feature = "v2")] #[derive(Clone)] /// Set the private fields of merchant account pub struct MerchantAccountSetter { pub id: common_utils::id_type::MerchantId, pub merchant_name: OptionalEncryptableName, pub merchant_details: OptionalEncryptableValue, pub publishable_key: String, pub storage_scheme: MerchantStorageScheme, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: diesel_models::enums::ReconStatus, pub is_platform_account: bool, pub version: common_enums::ApiVersion, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v2")] impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { let MerchantAccountSetter { id, merchant_name, merchant_details, publishable_key, storage_scheme, metadata, created_at, modified_at, organization_id, recon_status, is_platform_account, version, product_type, merchant_account_type, } = item; Self { id, merchant_name, merchant_details, publishable_key, storage_scheme, metadata, created_at, modified_at, organization_id, recon_status, is_platform_account, version, product_type, merchant_account_type, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize)] pub struct MerchantAccount { id: common_utils::id_type::MerchantId, pub merchant_name: OptionalEncryptableName, pub merchant_details: OptionalEncryptableValue, pub publishable_key: String, pub storage_scheme: MerchantStorageScheme, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: diesel_models::enums::ReconStatus, pub is_platform_account: bool, pub version: common_enums::ApiVersion, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } impl MerchantAccount { #[cfg(feature = "v1")] /// Get the unique identifier of MerchantAccount pub fn get_id(&self) -> &common_utils::id_type::MerchantId { &self.merchant_id } #[cfg(feature = "v2")] /// Get the unique identifier of MerchantAccount pub fn get_id(&self) -> &common_utils::id_type::MerchantId { &self.id } /// Get the organization_id from MerchantAccount pub fn get_org_id(&self) -> &common_utils::id_type::OrganizationId { &self.organization_id } /// Get the merchant_details from MerchantAccount pub fn get_merchant_details(&self) -> &OptionalEncryptableValue { &self.merchant_details } /// Extract merchant_tax_registration_id from merchant_details pub fn get_merchant_tax_registration_id(&self) -> Option<Secret<String>> { self.merchant_details.as_ref().and_then(|details| { details .get_inner() .peek() .get("merchant_tax_registration_id") .and_then(|id| id.as_str().map(|s| Secret::new(s.to_string()))) }) } /// Check whether the merchant account is a platform account pub fn is_platform_account(&self) -> bool { matches!( self.merchant_account_type, common_enums::MerchantAccountType::Platform ) } } #[cfg(feature = "v1")] #[allow(clippy::large_enum_variant)] #[derive(Debug, Clone)] pub enum MerchantAccountUpdate { Update { merchant_name: OptionalEncryptableName, merchant_details: OptionalEncryptableValue, return_url: Option<String>, webhook_details: Option<diesel_models::business_profile::WebhookDetails>, sub_merchants_enabled: Option<bool>, parent_merchant_id: Option<common_utils::id_type::MerchantId>, enable_payment_response_hash: Option<bool>, payment_response_hash_key: Option<String>, redirect_to_merchant_with_http_post: Option<bool>, publishable_key: Option<String>, locker_id: Option<String>, metadata: Option<pii::SecretSerdeValue>, routing_algorithm: Option<serde_json::Value>, primary_business_details: Option<serde_json::Value>, intent_fulfillment_time: Option<i64>, frm_routing_algorithm: Option<serde_json::Value>, payout_routing_algorithm: Option<serde_json::Value>, default_profile: Option<Option<common_utils::id_type::ProfileId>>, payment_link_config: Option<serde_json::Value>, pm_collect_link_config: Option<serde_json::Value>, }, StorageSchemeUpdate { storage_scheme: MerchantStorageScheme, }, ReconUpdate { recon_status: diesel_models::enums::ReconStatus, }, UnsetDefaultProfile, ModifiedAtUpdate, ToPlatformAccount, } #[cfg(feature = "v2")] #[derive(Debug, Clone)] pub enum MerchantAccountUpdate { Update { merchant_name: OptionalEncryptableName, merchant_details: OptionalEncryptableValue, publishable_key: Option<String>, metadata: Option<Box<pii::SecretSerdeValue>>, }, StorageSchemeUpdate { storage_scheme: MerchantStorageScheme, }, ReconUpdate { recon_status: diesel_models::enums::ReconStatus, }, ModifiedAtUpdate, ToPlatformAccount, } #[cfg(feature = "v1")] impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { fn from(merchant_account_update: MerchantAccountUpdate) -> Self { let now = date_time::now(); match merchant_account_update { MerchantAccountUpdate::Update { merchant_name, merchant_details, webhook_details, return_url, routing_algorithm, sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, publishable_key, locker_id, metadata, primary_business_details, intent_fulfillment_time, frm_routing_algorithm, payout_routing_algorithm, default_profile, payment_link_config, pm_collect_link_config, } => Self { merchant_name: merchant_name.map(Encryption::from), merchant_details: merchant_details.map(Encryption::from), frm_routing_algorithm, webhook_details, routing_algorithm, sub_merchants_enabled, parent_merchant_id, return_url, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, publishable_key, locker_id, metadata, primary_business_details, modified_at: now, intent_fulfillment_time, payout_routing_algorithm, default_profile, payment_link_config, pm_collect_link_config, storage_scheme: None, organization_id: None, is_recon_enabled: None, recon_status: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self { storage_scheme: Some(storage_scheme), modified_at: now, merchant_name: None, merchant_details: None, return_url: None, webhook_details: None, sub_merchants_enabled: None, parent_merchant_id: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, publishable_key: None, locker_id: None, metadata: None, routing_algorithm: None, primary_business_details: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: None, is_recon_enabled: None, default_profile: None, recon_status: None, payment_link_config: None, pm_collect_link_config: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::ReconUpdate { recon_status } => Self { recon_status: Some(recon_status), modified_at: now, merchant_name: None, merchant_details: None, return_url: None, webhook_details: None, sub_merchants_enabled: None, parent_merchant_id: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, publishable_key: None, storage_scheme: None, locker_id: None, metadata: None, routing_algorithm: None, primary_business_details: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: None, is_recon_enabled: None, default_profile: None, payment_link_config: None, pm_collect_link_config: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::UnsetDefaultProfile => Self { default_profile: Some(None), modified_at: now, merchant_name: None, merchant_details: None, return_url: None, webhook_details: None, sub_merchants_enabled: None, parent_merchant_id: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, publishable_key: None, storage_scheme: None, locker_id: None, metadata: None, routing_algorithm: None, primary_business_details: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: None, is_recon_enabled: None, recon_status: None, payment_link_config: None, pm_collect_link_config: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::ModifiedAtUpdate => Self { modified_at: now, merchant_name: None, merchant_details: None, return_url: None, webhook_details: None, sub_merchants_enabled: None, parent_merchant_id: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, publishable_key: None, storage_scheme: None, locker_id: None, metadata: None, routing_algorithm: None, primary_business_details: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: None, is_recon_enabled: None, default_profile: None, recon_status: None, payment_link_config: None, pm_collect_link_config: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::ToPlatformAccount => Self { modified_at: now, merchant_name: None, merchant_details: None, return_url: None, webhook_details: None, sub_merchants_enabled: None, parent_merchant_id: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, publishable_key: None, storage_scheme: None, locker_id: None, metadata: None, routing_algorithm: None, primary_business_details: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: None, is_recon_enabled: None, default_profile: None, recon_status: None, payment_link_config: None, pm_collect_link_config: None, is_platform_account: Some(true), product_type: None, }, } } } #[cfg(feature = "v2")] impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { fn from(merchant_account_update: MerchantAccountUpdate) -> Self { let now = date_time::now(); match merchant_account_update { MerchantAccountUpdate::Update { merchant_name, merchant_details, publishable_key, metadata, } => Self { merchant_name: merchant_name.map(Encryption::from), merchant_details: merchant_details.map(Encryption::from), publishable_key, metadata: metadata.map(|metadata| *metadata), modified_at: now, storage_scheme: None, organization_id: None, recon_status: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self { storage_scheme: Some(storage_scheme), modified_at: now, merchant_name: None, merchant_details: None, publishable_key: None, metadata: None, organization_id: None, recon_status: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::ReconUpdate { recon_status } => Self { recon_status: Some(recon_status), modified_at: now, merchant_name: None, merchant_details: None, publishable_key: None, storage_scheme: None, metadata: None, organization_id: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::ModifiedAtUpdate => Self { modified_at: now, merchant_name: None, merchant_details: None, publishable_key: None, storage_scheme: None, metadata: None, organization_id: None, recon_status: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::ToPlatformAccount => Self { modified_at: now, merchant_name: None, merchant_details: None, publishable_key: None, storage_scheme: None, metadata: None, organization_id: None, recon_status: None, is_platform_account: Some(true), product_type: None, }, } } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl Conversion for MerchantAccount { type DstType = diesel_models::merchant_account::MerchantAccount; type NewDstType = diesel_models::merchant_account::MerchantAccountNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let id = self.get_id().to_owned(); let setter = diesel_models::merchant_account::MerchantAccountSetter { id, merchant_name: self.merchant_name.map(|name| name.into()), merchant_details: self.merchant_details.map(|details| details.into()), publishable_key: Some(self.publishable_key), storage_scheme: self.storage_scheme, metadata: self.metadata, created_at: self.created_at, modified_at: self.modified_at, organization_id: self.organization_id, recon_status: self.recon_status, version: common_types::consts::API_VERSION, is_platform_account: self.is_platform_account, product_type: self.product_type, merchant_account_type: self.merchant_account_type, }; Ok(diesel_models::MerchantAccount::from(setter)) } async fn convert_back( state: &keymanager::KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let id = item.get_id().to_owned(); let publishable_key = item.publishable_key .ok_or(ValidationError::MissingRequiredField { field_name: "publishable_key".to_string(), })?; async { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { id, merchant_name: item .merchant_name .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, merchant_details: item .merchant_details .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, publishable_key, storage_scheme: item.storage_scheme, metadata: item.metadata, created_at: item.created_at, modified_at: item.modified_at, organization_id: item.organization_id, recon_status: item.recon_status, is_platform_account: item.is_platform_account, version: item.version, product_type: item.product_type, merchant_account_type: item.merchant_account_type.unwrap_or_default(), }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting merchant data".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(diesel_models::merchant_account::MerchantAccountNew { id: self.id, merchant_name: self.merchant_name.map(Encryption::from), merchant_details: self.merchant_details.map(Encryption::from), publishable_key: Some(self.publishable_key), metadata: self.metadata, created_at: now, modified_at: now, organization_id: self.organization_id, recon_status: self.recon_status, version: common_types::consts::API_VERSION, is_platform_account: self.is_platform_account, product_type: self .product_type .or(Some(common_enums::MerchantProductType::Orchestration)), merchant_account_type: self.merchant_account_type, }) } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl Conversion for MerchantAccount { type DstType = diesel_models::merchant_account::MerchantAccount; type NewDstType = diesel_models::merchant_account::MerchantAccountNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let setter = diesel_models::merchant_account::MerchantAccountSetter { merchant_id: self.merchant_id, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, merchant_name: self.merchant_name.map(|name| name.into()), merchant_details: self.merchant_details.map(|details| details.into()), webhook_details: self.webhook_details, sub_merchants_enabled: self.sub_merchants_enabled, parent_merchant_id: self.parent_merchant_id, publishable_key: Some(self.publishable_key), storage_scheme: self.storage_scheme, locker_id: self.locker_id, metadata: self.metadata, routing_algorithm: self.routing_algorithm, primary_business_details: self.primary_business_details, created_at: self.created_at, modified_at: self.modified_at, intent_fulfillment_time: self.intent_fulfillment_time, frm_routing_algorithm: self.frm_routing_algorithm, payout_routing_algorithm: self.payout_routing_algorithm, organization_id: self.organization_id, is_recon_enabled: self.is_recon_enabled, default_profile: self.default_profile, recon_status: self.recon_status, payment_link_config: self.payment_link_config, pm_collect_link_config: self.pm_collect_link_config, version: self.version, is_platform_account: self.is_platform_account, product_type: self.product_type, merchant_account_type: self.merchant_account_type, }; Ok(diesel_models::MerchantAccount::from(setter)) } async fn convert_back( state: &keymanager::KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let merchant_id = item.get_id().to_owned(); let publishable_key = item.publishable_key .ok_or(ValidationError::MissingRequiredField { field_name: "publishable_key".to_string(), })?; async { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { merchant_id, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item .merchant_name .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, merchant_details: item .merchant_details .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, webhook_details: item.webhook_details, sub_merchants_enabled: item.sub_merchants_enabled, parent_merchant_id: item.parent_merchant_id, publishable_key, storage_scheme: item.storage_scheme, locker_id: item.locker_id, metadata: item.metadata, routing_algorithm: item.routing_algorithm, frm_routing_algorithm: item.frm_routing_algorithm, primary_business_details: item.primary_business_details, created_at: item.created_at, modified_at: item.modified_at, intent_fulfillment_time: item.intent_fulfillment_time, payout_routing_algorithm: item.payout_routing_algorithm, organization_id: item.organization_id, is_recon_enabled: item.is_recon_enabled, default_profile: item.default_profile, recon_status: item.recon_status, payment_link_config: item.payment_link_config, pm_collect_link_config: item.pm_collect_link_config, version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, merchant_account_type: item.merchant_account_type.unwrap_or_default(), }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting merchant data".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(diesel_models::merchant_account::MerchantAccountNew { id: Some(self.merchant_id.clone()), merchant_id: self.merchant_id, merchant_name: self.merchant_name.map(Encryption::from), merchant_details: self.merchant_details.map(Encryption::from), return_url: self.return_url, webhook_details: self.webhook_details, sub_merchants_enabled: self.sub_merchants_enabled, parent_merchant_id: self.parent_merchant_id, enable_payment_response_hash: Some(self.enable_payment_response_hash), payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: Some(self.redirect_to_merchant_with_http_post), publishable_key: Some(self.publishable_key), locker_id: self.locker_id, metadata: self.metadata, routing_algorithm: self.routing_algorithm, primary_business_details: self.primary_business_details, created_at: now, modified_at: now, intent_fulfillment_time: self.intent_fulfillment_time, frm_routing_algorithm: self.frm_routing_algorithm, payout_routing_algorithm: self.payout_routing_algorithm, organization_id: self.organization_id, is_recon_enabled: self.is_recon_enabled, default_profile: self.default_profile, recon_status: self.recon_status, payment_link_config: self.payment_link_config, pm_collect_link_config: self.pm_collect_link_config, version: common_types::consts::API_VERSION, is_platform_account: self.is_platform_account, product_type: self .product_type .or(Some(common_enums::MerchantProductType::Orchestration)), merchant_account_type: self.merchant_account_type, }) } } impl MerchantAccount { pub fn get_compatible_connector(&self) -> Option<api_models::enums::Connector> { let metadata: Option<api_models::admin::MerchantAccountMetadata> = self.metadata.as_ref().and_then(|meta| { meta.clone() .parse_value("MerchantAccountMetadata") .map_err(|err| logger::error!("Failed to deserialize {:?}", err)) .ok() }); metadata.and_then(|a| a.compatible_connector) } } #[async_trait::async_trait] pub trait MerchantAccountInterface where MerchantAccount: Conversion< DstType = diesel_models::merchant_account::MerchantAccount, NewDstType = diesel_models::merchant_account::MerchantAccountNew, >, { type Error; async fn insert_merchant( &self, state: &keymanager::KeyManagerState, merchant_account: MerchantAccount, merchant_key_store: &merchant_key_store::MerchantKeyStore, ) -> CustomResult<MerchantAccount, Self::Error>; async fn find_merchant_account_by_merchant_id( &self, state: &keymanager::KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &merchant_key_store::MerchantKeyStore, ) -> CustomResult<MerchantAccount, Self::Error>; async fn update_all_merchant_account( &self, merchant_account: MerchantAccountUpdate, ) -> CustomResult<usize, Self::Error>; async fn update_merchant( &self, state: &keymanager::KeyManagerState, this: MerchantAccount, merchant_account: MerchantAccountUpdate, merchant_key_store: &merchant_key_store::MerchantKeyStore, ) -> CustomResult<MerchantAccount, Self::Error>; async fn update_specific_fields_in_merchant( &self, state: &keymanager::KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account: MerchantAccountUpdate, merchant_key_store: &merchant_key_store::MerchantKeyStore, ) -> CustomResult<MerchantAccount, Self::Error>; async fn find_merchant_account_by_publishable_key( &self, state: &keymanager::KeyManagerState, publishable_key: &str, ) -> CustomResult<(MerchantAccount, merchant_key_store::MerchantKeyStore), Self::Error>; #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, state: &keymanager::KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<MerchantAccount>, Self::Error>; async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, Self::Error>; #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, state: &keymanager::KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<MerchantAccount>, Self::Error>; #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, state: &keymanager::KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, Self::Error, >; }
crates/hyperswitch_domain_models/src/merchant_account.rs
hyperswitch_domain_models::src::merchant_account
7,422
true
// File: crates/hyperswitch_domain_models/src/router_data_v2.rs // Module: hyperswitch_domain_models::src::router_data_v2 pub mod flow_common_types; use std::{marker::PhantomData, ops::Deref}; use common_utils::id_type; #[cfg(feature = "frm")] pub use flow_common_types::FrmFlowData; #[cfg(feature = "payouts")] pub use flow_common_types::PayoutFlowData; pub use flow_common_types::{ AccessTokenFlowData, AuthenticationTokenFlowData, DisputesFlowData, ExternalAuthenticationFlowData, ExternalVaultProxyFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, UasFlowData, VaultConnectorFlowData, WebhookSourceVerifyData, }; use crate::router_data::{ConnectorAuthType, ErrorResponse}; #[derive(Debug, Clone)] pub struct RouterDataV2<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse> { pub flow: PhantomData<Flow>, pub tenant_id: id_type::TenantId, pub resource_common_data: ResourceCommonData, pub connector_auth_type: ConnectorAuthType, /// Contains flow-specific data required to construct a request and send it to the connector. pub request: FlowSpecificRequest, /// Contains flow-specific data that the connector responds with. pub response: Result<FlowSpecificResponse, ErrorResponse>, } impl<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse> Deref for RouterDataV2<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse> { type Target = ResourceCommonData; fn deref(&self) -> &Self::Target { &self.resource_common_data } }
crates/hyperswitch_domain_models/src/router_data_v2.rs
hyperswitch_domain_models::src::router_data_v2
373
true
// File: crates/hyperswitch_domain_models/src/payouts.rs // Module: hyperswitch_domain_models::src::payouts pub mod payout_attempt; #[allow(clippy::module_inception)] pub mod payouts; use common_enums as storage_enums; use common_utils::{consts, id_type}; use time::PrimitiveDateTime; pub enum PayoutFetchConstraints { Single { payout_id: id_type::PayoutId }, List(Box<PayoutListParams>), } pub struct PayoutListParams { pub offset: u32, pub starting_at: Option<PrimitiveDateTime>, pub ending_at: Option<PrimitiveDateTime>, pub connector: Option<Vec<api_models::enums::PayoutConnectors>>, pub currency: Option<Vec<storage_enums::Currency>>, pub status: Option<Vec<storage_enums::PayoutStatus>>, pub payout_method: Option<Vec<common_enums::PayoutType>>, pub profile_id: Option<id_type::ProfileId>, pub customer_id: Option<id_type::CustomerId>, pub starting_after_id: Option<id_type::PayoutId>, pub ending_before_id: Option<id_type::PayoutId>, pub entity_type: Option<common_enums::PayoutEntityType>, pub limit: Option<u32>, pub merchant_order_reference_id: Option<String>, } impl From<api_models::payouts::PayoutListConstraints> for PayoutFetchConstraints { fn from(value: api_models::payouts::PayoutListConstraints) -> Self { Self::List(Box::new(PayoutListParams { offset: 0, starting_at: value .time_range .map_or(value.created, |t| Some(t.start_time)), ending_at: value.time_range.and_then(|t| t.end_time), connector: None, currency: None, status: None, payout_method: None, profile_id: None, customer_id: value.customer_id, starting_after_id: value.starting_after, ending_before_id: value.ending_before, entity_type: None, merchant_order_reference_id: None, limit: Some(std::cmp::min( value.limit, consts::PAYOUTS_LIST_MAX_LIMIT_GET, )), })) } } impl From<common_utils::types::TimeRange> for PayoutFetchConstraints { fn from(value: common_utils::types::TimeRange) -> Self { Self::List(Box::new(PayoutListParams { offset: 0, starting_at: Some(value.start_time), ending_at: value.end_time, connector: None, currency: None, status: None, payout_method: None, profile_id: None, customer_id: None, starting_after_id: None, ending_before_id: None, entity_type: None, merchant_order_reference_id: None, limit: None, })) } } impl From<api_models::payouts::PayoutListFilterConstraints> for PayoutFetchConstraints { fn from(value: api_models::payouts::PayoutListFilterConstraints) -> Self { if let Some(payout_id) = value.payout_id { Self::Single { payout_id } } else { Self::List(Box::new(PayoutListParams { offset: value.offset.unwrap_or_default(), starting_at: value.time_range.map(|t| t.start_time), ending_at: value.time_range.and_then(|t| t.end_time), connector: value.connector, currency: value.currency, status: value.status, payout_method: value.payout_method, profile_id: value.profile_id, customer_id: value.customer_id, starting_after_id: None, ending_before_id: None, entity_type: value.entity_type, merchant_order_reference_id: value.merchant_order_reference_id, limit: Some(std::cmp::min( value.limit, consts::PAYOUTS_LIST_MAX_LIMIT_POST, )), })) } } }
crates/hyperswitch_domain_models/src/payouts.rs
hyperswitch_domain_models::src::payouts
862
true
// File: crates/hyperswitch_domain_models/src/cards_info.rs // Module: hyperswitch_domain_models::src::cards_info use common_utils::errors; use diesel_models::cards_info; #[async_trait::async_trait] pub trait CardsInfoInterface { type Error; async fn get_card_info( &self, _card_iin: &str, ) -> errors::CustomResult<Option<cards_info::CardInfo>, Self::Error>; async fn add_card_info( &self, data: cards_info::CardInfo, ) -> errors::CustomResult<cards_info::CardInfo, Self::Error>; async fn update_card_info( &self, card_iin: String, data: cards_info::UpdateCardInfo, ) -> errors::CustomResult<cards_info::CardInfo, Self::Error>; }
crates/hyperswitch_domain_models/src/cards_info.rs
hyperswitch_domain_models::src::cards_info
182
true
// File: crates/hyperswitch_domain_models/src/merchant_connector_account.rs // Module: hyperswitch_domain_models::src::merchant_connector_account #[cfg(feature = "v2")] use std::collections::HashMap; use common_utils::{ crypto::Encryptable, date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, ext_traits::ValueExt, id_type, pii, type_name, types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, }; #[cfg(feature = "v2")] use diesel_models::merchant_connector_account::{ BillingAccountReference as DieselBillingAccountReference, MerchantConnectorAccountFeatureMetadata as DieselMerchantConnectorAccountFeatureMetadata, RevenueRecoveryMetadata as DieselRevenueRecoveryMetadata, }; use diesel_models::{ enums, merchant_connector_account::{self as storage, MerchantConnectorAccountUpdateInternal}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use rustc_hash::FxHashMap; use serde_json::Value; use super::behaviour; #[cfg(feature = "v2")] use crate::errors::api_error_response; use crate::{ mandates::CommonMandateReference, merchant_key_store::MerchantKeyStore, router_data, type_encryption::{crypto_operation, CryptoOperation}, }; #[cfg(feature = "v1")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct MerchantConnectorAccount { pub merchant_id: id_type::MerchantId, pub connector_name: String, #[encrypt] pub connector_account_details: Encryptable<Secret<Value>>, pub test_mode: Option<bool>, pub disabled: Option<bool>, pub merchant_connector_id: id_type::MerchantConnectorAccountId, pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, pub connector_type: enums::ConnectorType, pub metadata: Option<pii::SecretSerdeValue>, pub frm_configs: Option<Vec<pii::SecretSerdeValue>>, pub connector_label: Option<String>, pub business_country: Option<enums::CountryAlpha2>, pub business_label: Option<String>, pub business_sub_label: Option<String>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_webhook_details: Option<pii::SecretSerdeValue>, pub profile_id: id_type::ProfileId, pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: enums::ConnectorStatus, #[encrypt] pub connector_wallets_details: Option<Encryptable<Secret<Value>>>, #[encrypt] pub additional_merchant_data: Option<Encryptable<Secret<Value>>>, pub version: common_enums::ApiVersion, } #[cfg(feature = "v1")] impl MerchantConnectorAccount { pub fn get_id(&self) -> id_type::MerchantConnectorAccountId { self.merchant_connector_id.clone() } pub fn get_connector_account_details( &self, ) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError> { self.connector_account_details .get_inner() .clone() .parse_value("ConnectorAuthType") } pub fn get_connector_wallets_details(&self) -> Option<Secret<Value>> { self.connector_wallets_details.as_deref().cloned() } pub fn get_connector_test_mode(&self) -> Option<bool> { self.test_mode } pub fn get_connector_name_as_string(&self) -> String { self.connector_name.clone() } pub fn get_metadata(&self) -> Option<Secret<Value>> { self.metadata.clone() } } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub enum MerchantConnectorAccountTypeDetails { MerchantConnectorAccount(Box<MerchantConnectorAccount>), MerchantConnectorDetails(common_types::domain::MerchantConnectorAuthDetails), } #[cfg(feature = "v2")] impl MerchantConnectorAccountTypeDetails { pub fn get_connector_account_details( &self, ) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { merchant_connector_account .connector_account_details .peek() .clone() .parse_value("ConnectorAuthType") } Self::MerchantConnectorDetails(merchant_connector_details) => { merchant_connector_details .merchant_connector_creds .peek() .clone() .parse_value("ConnectorAuthType") } } } pub fn is_disabled(&self) -> bool { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { merchant_connector_account.disabled.unwrap_or(false) } Self::MerchantConnectorDetails(_) => false, } } pub fn get_metadata(&self) -> Option<Secret<Value>> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { merchant_connector_account.metadata.to_owned() } Self::MerchantConnectorDetails(_) => None, } } pub fn get_id(&self) -> Option<id_type::MerchantConnectorAccountId> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { Some(merchant_connector_account.id.clone()) } Self::MerchantConnectorDetails(_) => None, } } pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { Some(merchant_connector_account.get_id()) } Self::MerchantConnectorDetails(_) => None, } } pub fn get_connector_name(&self) -> Option<common_enums::connector_enums::Connector> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { Some(merchant_connector_account.connector_name) } Self::MerchantConnectorDetails(merchant_connector_details) => { Some(merchant_connector_details.connector_name) } } } pub fn get_connector_name_as_string(&self) -> String { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { merchant_connector_account.connector_name.to_string() } Self::MerchantConnectorDetails(merchant_connector_details) => { merchant_connector_details.connector_name.to_string() } } } pub fn get_inner_db_merchant_connector_account(&self) -> Option<&MerchantConnectorAccount> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { Some(merchant_connector_account) } Self::MerchantConnectorDetails(_) => None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct MerchantConnectorAccount { pub id: id_type::MerchantConnectorAccountId, pub merchant_id: id_type::MerchantId, pub connector_name: common_enums::connector_enums::Connector, #[encrypt] pub connector_account_details: Encryptable<Secret<Value>>, pub disabled: Option<bool>, pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, pub connector_type: enums::ConnectorType, pub metadata: Option<pii::SecretSerdeValue>, pub frm_configs: Option<Vec<pii::SecretSerdeValue>>, pub connector_label: Option<String>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_webhook_details: Option<pii::SecretSerdeValue>, pub profile_id: id_type::ProfileId, pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: enums::ConnectorStatus, #[encrypt] pub connector_wallets_details: Option<Encryptable<Secret<Value>>>, #[encrypt] pub additional_merchant_data: Option<Encryptable<Secret<Value>>>, pub version: common_enums::ApiVersion, pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorAccount { pub fn get_retry_threshold(&self) -> Option<u16> { self.feature_metadata .as_ref() .and_then(|metadata| metadata.revenue_recovery.as_ref()) .map(|recovery| recovery.billing_connector_retry_threshold) } pub fn get_id(&self) -> id_type::MerchantConnectorAccountId { self.id.clone() } pub fn get_metadata(&self) -> Option<pii::SecretSerdeValue> { self.metadata.clone() } pub fn is_disabled(&self) -> bool { self.disabled.unwrap_or(false) } pub fn get_connector_account_details( &self, ) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError> { use common_utils::ext_traits::ValueExt; self.connector_account_details .get_inner() .clone() .parse_value("ConnectorAuthType") } pub fn get_connector_wallets_details(&self) -> Option<Secret<Value>> { self.connector_wallets_details.as_deref().cloned() } pub fn get_connector_test_mode(&self) -> Option<bool> { todo!() } pub fn get_connector_name_as_string(&self) -> String { self.connector_name.clone().to_string() } #[cfg(feature = "v2")] pub fn get_connector_name(&self) -> common_enums::connector_enums::Connector { self.connector_name } pub fn get_payment_merchant_connector_account_id_using_account_reference_id( &self, account_reference_id: String, ) -> Option<id_type::MerchantConnectorAccountId> { self.feature_metadata.as_ref().and_then(|metadata| { metadata.revenue_recovery.as_ref().and_then(|recovery| { recovery .mca_reference .billing_to_recovery .get(&account_reference_id) .cloned() }) }) } pub fn get_account_reference_id_using_payment_merchant_connector_account_id( &self, payment_merchant_connector_account_id: id_type::MerchantConnectorAccountId, ) -> Option<String> { self.feature_metadata.as_ref().and_then(|metadata| { metadata.revenue_recovery.as_ref().and_then(|recovery| { recovery .mca_reference .recovery_to_billing .get(&payment_merchant_connector_account_id) .cloned() }) }) } } #[cfg(feature = "v2")] /// Holds the payment methods enabled for a connector along with the connector name /// This struct is a flattened representation of the payment methods enabled for a connector #[derive(Debug)] pub struct PaymentMethodsEnabledForConnector { pub payment_methods_enabled: common_types::payment_methods::RequestPaymentMethodTypes, pub payment_method: common_enums::PaymentMethod, pub connector: common_enums::connector_enums::Connector, pub merchant_connector_id: id_type::MerchantConnectorAccountId, } #[cfg(feature = "v2")] #[derive(Debug, Clone)] pub struct MerchantConnectorAccountFeatureMetadata { pub revenue_recovery: Option<RevenueRecoveryMetadata>, } #[cfg(feature = "v2")] #[derive(Debug, Clone)] pub struct RevenueRecoveryMetadata { pub max_retry_count: u16, pub billing_connector_retry_threshold: u16, pub mca_reference: AccountReferenceMap, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize)] pub struct ExternalVaultConnectorMetadata { pub proxy_url: common_utils::types::Url, pub certificate: Secret<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone)] pub struct AccountReferenceMap { pub recovery_to_billing: HashMap<id_type::MerchantConnectorAccountId, String>, pub billing_to_recovery: HashMap<String, id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] impl AccountReferenceMap { pub fn new( hash_map: HashMap<id_type::MerchantConnectorAccountId, String>, ) -> Result<Self, api_error_response::ApiErrorResponse> { Self::validate(&hash_map)?; let recovery_to_billing = hash_map.clone(); let mut billing_to_recovery = HashMap::new(); for (key, value) in &hash_map { billing_to_recovery.insert(value.clone(), key.clone()); } Ok(Self { recovery_to_billing, billing_to_recovery, }) } fn validate( hash_map: &HashMap<id_type::MerchantConnectorAccountId, String>, ) -> Result<(), api_error_response::ApiErrorResponse> { let mut seen_values = std::collections::HashSet::new(); // To check uniqueness of values for value in hash_map.values() { if !seen_values.insert(value.clone()) { return Err(api_error_response::ApiErrorResponse::InvalidRequestData { message: "Duplicate account reference IDs found in Recovery feature metadata. Each account reference ID must be unique.".to_string(), }); } } Ok(()) } } #[cfg(feature = "v2")] /// Holds the payment methods enabled for a connector pub struct FlattenedPaymentMethodsEnabled { pub payment_methods_enabled: Vec<PaymentMethodsEnabledForConnector>, } #[cfg(feature = "v2")] impl FlattenedPaymentMethodsEnabled { /// This functions flattens the payment methods enabled from the connector accounts /// Retains the connector name and payment method in every flattened element pub fn from_payment_connectors_list(payment_connectors: Vec<MerchantConnectorAccount>) -> Self { let payment_methods_enabled_flattened_with_connector = payment_connectors .into_iter() .map(|connector| { ( connector .payment_methods_enabled .clone() .unwrap_or_default(), connector.connector_name, connector.get_id(), ) }) .flat_map( |(payment_method_enabled, connector, merchant_connector_id)| { payment_method_enabled .into_iter() .flat_map(move |payment_method| { let request_payment_methods_enabled = payment_method.payment_method_subtypes.unwrap_or_default(); let length = request_payment_methods_enabled.len(); request_payment_methods_enabled .into_iter() .zip(std::iter::repeat_n( ( connector, merchant_connector_id.clone(), payment_method.payment_method_type, ), length, )) }) }, ) .map( |(request_payment_methods, (connector, merchant_connector_id, payment_method))| { PaymentMethodsEnabledForConnector { payment_methods_enabled: request_payment_methods, connector, payment_method, merchant_connector_id, } }, ) .collect(); Self { payment_methods_enabled: payment_methods_enabled_flattened_with_connector, } } } #[cfg(feature = "v1")] #[derive(Debug)] pub enum MerchantConnectorAccountUpdate { Update { connector_type: Option<enums::ConnectorType>, connector_name: Option<String>, connector_account_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>, test_mode: Option<bool>, disabled: Option<bool>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, metadata: Option<pii::SecretSerdeValue>, frm_configs: Option<Vec<pii::SecretSerdeValue>>, connector_webhook_details: Box<Option<pii::SecretSerdeValue>>, applepay_verified_domains: Option<Vec<String>>, pm_auth_config: Box<Option<pii::SecretSerdeValue>>, connector_label: Option<String>, status: Option<enums::ConnectorStatus>, connector_wallets_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>, additional_merchant_data: Box<Option<Encryptable<pii::SecretSerdeValue>>>, }, ConnectorWalletDetailsUpdate { connector_wallets_details: Encryptable<pii::SecretSerdeValue>, }, } #[cfg(feature = "v2")] #[derive(Debug)] pub enum MerchantConnectorAccountUpdate { Update { connector_type: Option<enums::ConnectorType>, connector_account_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>, disabled: Option<bool>, payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, metadata: Option<pii::SecretSerdeValue>, frm_configs: Option<Vec<pii::SecretSerdeValue>>, connector_webhook_details: Box<Option<pii::SecretSerdeValue>>, applepay_verified_domains: Option<Vec<String>>, pm_auth_config: Box<Option<pii::SecretSerdeValue>>, connector_label: Option<String>, status: Option<enums::ConnectorStatus>, connector_wallets_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>, additional_merchant_data: Box<Option<Encryptable<pii::SecretSerdeValue>>>, feature_metadata: Box<Option<MerchantConnectorAccountFeatureMetadata>>, }, ConnectorWalletDetailsUpdate { connector_wallets_details: Encryptable<pii::SecretSerdeValue>, }, } #[cfg(feature = "v1")] #[async_trait::async_trait] impl behaviour::Conversion for MerchantConnectorAccount { type DstType = storage::MerchantConnectorAccount; type NewDstType = storage::MerchantConnectorAccountNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(storage::MerchantConnectorAccount { merchant_id: self.merchant_id, connector_name: self.connector_name, connector_account_details: self.connector_account_details.into(), test_mode: self.test_mode, disabled: self.disabled, merchant_connector_id: self.merchant_connector_id.clone(), id: Some(self.merchant_connector_id), payment_methods_enabled: self.payment_methods_enabled, connector_type: self.connector_type, metadata: self.metadata, frm_configs: None, frm_config: self.frm_configs, business_country: self.business_country, business_label: self.business_label, connector_label: self.connector_label, business_sub_label: self.business_sub_label, created_at: self.created_at, modified_at: self.modified_at, connector_webhook_details: self.connector_webhook_details, profile_id: Some(self.profile_id), applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, status: self.status, connector_wallets_details: self.connector_wallets_details.map(Encryption::from), additional_merchant_data: self.additional_merchant_data.map(|data| data.into()), version: self.version, }) } async fn convert_back( state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> { let identifier = Identifier::Merchant(other.merchant_id.clone()); let decrypted_data = crypto_operation( state, type_name!(Self::DstType), CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable( EncryptedMerchantConnectorAccount { connector_account_details: other.connector_account_details, additional_merchant_data: other.additional_merchant_data, connector_wallets_details: other.connector_wallets_details, }, )), identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting connector account details".to_string(), })?; let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting connector account details".to_string(), })?; Ok(Self { merchant_id: other.merchant_id, connector_name: other.connector_name, connector_account_details: decrypted_data.connector_account_details, test_mode: other.test_mode, disabled: other.disabled, merchant_connector_id: other.merchant_connector_id, payment_methods_enabled: other.payment_methods_enabled, connector_type: other.connector_type, metadata: other.metadata, frm_configs: other.frm_config, business_country: other.business_country, business_label: other.business_label, connector_label: other.connector_label, business_sub_label: other.business_sub_label, created_at: other.created_at, modified_at: other.modified_at, connector_webhook_details: other.connector_webhook_details, profile_id: other .profile_id .ok_or(ValidationError::MissingRequiredField { field_name: "profile_id".to_string(), })?, applepay_verified_domains: other.applepay_verified_domains, pm_auth_config: other.pm_auth_config, status: other.status, connector_wallets_details: decrypted_data.connector_wallets_details, additional_merchant_data: decrypted_data.additional_merchant_data, version: other.version, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(Self::NewDstType { merchant_id: Some(self.merchant_id), connector_name: Some(self.connector_name), connector_account_details: Some(self.connector_account_details.into()), test_mode: self.test_mode, disabled: self.disabled, merchant_connector_id: self.merchant_connector_id.clone(), id: Some(self.merchant_connector_id), payment_methods_enabled: self.payment_methods_enabled, connector_type: Some(self.connector_type), metadata: self.metadata, frm_configs: None, frm_config: self.frm_configs, business_country: self.business_country, business_label: self.business_label, connector_label: self.connector_label, business_sub_label: self.business_sub_label, created_at: now, modified_at: now, connector_webhook_details: self.connector_webhook_details, profile_id: Some(self.profile_id), applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, status: self.status, connector_wallets_details: self.connector_wallets_details.map(Encryption::from), additional_merchant_data: self.additional_merchant_data.map(|data| data.into()), version: self.version, }) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl behaviour::Conversion for MerchantConnectorAccount { type DstType = storage::MerchantConnectorAccount; type NewDstType = storage::MerchantConnectorAccountNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(storage::MerchantConnectorAccount { id: self.id, merchant_id: self.merchant_id, connector_name: self.connector_name, connector_account_details: self.connector_account_details.into(), disabled: self.disabled, payment_methods_enabled: self.payment_methods_enabled, connector_type: self.connector_type, metadata: self.metadata, frm_config: self.frm_configs, connector_label: self.connector_label, created_at: self.created_at, modified_at: self.modified_at, connector_webhook_details: self.connector_webhook_details, profile_id: self.profile_id, applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, status: self.status, connector_wallets_details: self.connector_wallets_details.map(Encryption::from), additional_merchant_data: self.additional_merchant_data.map(|data| data.into()), version: self.version, feature_metadata: self.feature_metadata.map(From::from), }) } async fn convert_back( state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> { let identifier = Identifier::Merchant(other.merchant_id.clone()); let decrypted_data = crypto_operation( state, type_name!(Self::DstType), CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable( EncryptedMerchantConnectorAccount { connector_account_details: other.connector_account_details, additional_merchant_data: other.additional_merchant_data, connector_wallets_details: other.connector_wallets_details, }, )), identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting connector account details".to_string(), })?; let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting connector account details".to_string(), })?; Ok(Self { id: other.id, merchant_id: other.merchant_id, connector_name: other.connector_name, connector_account_details: decrypted_data.connector_account_details, disabled: other.disabled, payment_methods_enabled: other.payment_methods_enabled, connector_type: other.connector_type, metadata: other.metadata, frm_configs: other.frm_config, connector_label: other.connector_label, created_at: other.created_at, modified_at: other.modified_at, connector_webhook_details: other.connector_webhook_details, profile_id: other.profile_id, applepay_verified_domains: other.applepay_verified_domains, pm_auth_config: other.pm_auth_config, status: other.status, connector_wallets_details: decrypted_data.connector_wallets_details, additional_merchant_data: decrypted_data.additional_merchant_data, version: other.version, feature_metadata: other.feature_metadata.map(From::from), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(Self::NewDstType { id: self.id, merchant_id: Some(self.merchant_id), connector_name: Some(self.connector_name), connector_account_details: Some(self.connector_account_details.into()), disabled: self.disabled, payment_methods_enabled: self.payment_methods_enabled, connector_type: Some(self.connector_type), metadata: self.metadata, frm_config: self.frm_configs, connector_label: self.connector_label, created_at: now, modified_at: now, connector_webhook_details: self.connector_webhook_details, profile_id: self.profile_id, applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, status: self.status, connector_wallets_details: self.connector_wallets_details.map(Encryption::from), additional_merchant_data: self.additional_merchant_data.map(|data| data.into()), version: self.version, feature_metadata: self.feature_metadata.map(From::from), }) } } #[cfg(feature = "v1")] impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInternal { fn from(merchant_connector_account_update: MerchantConnectorAccountUpdate) -> Self { match merchant_connector_account_update { MerchantConnectorAccountUpdate::Update { connector_type, connector_name, connector_account_details, test_mode, disabled, merchant_connector_id, payment_methods_enabled, metadata, frm_configs, connector_webhook_details, applepay_verified_domains, pm_auth_config, connector_label, status, connector_wallets_details, additional_merchant_data, } => Self { connector_type, connector_name, connector_account_details: connector_account_details.map(Encryption::from), test_mode, disabled, merchant_connector_id, payment_methods_enabled, metadata, frm_configs: None, frm_config: frm_configs, modified_at: Some(date_time::now()), connector_webhook_details: *connector_webhook_details, applepay_verified_domains, pm_auth_config: *pm_auth_config, connector_label, status, connector_wallets_details: connector_wallets_details.map(Encryption::from), additional_merchant_data: additional_merchant_data.map(Encryption::from), }, MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate { connector_wallets_details, } => Self { connector_wallets_details: Some(Encryption::from(connector_wallets_details)), connector_type: None, connector_name: None, connector_account_details: None, connector_label: None, test_mode: None, disabled: None, merchant_connector_id: None, payment_methods_enabled: None, frm_configs: None, metadata: None, modified_at: None, connector_webhook_details: None, frm_config: None, applepay_verified_domains: None, pm_auth_config: None, status: None, additional_merchant_data: None, }, } } } #[cfg(feature = "v2")] impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInternal { fn from(merchant_connector_account_update: MerchantConnectorAccountUpdate) -> Self { match merchant_connector_account_update { MerchantConnectorAccountUpdate::Update { connector_type, connector_account_details, disabled, payment_methods_enabled, metadata, frm_configs, connector_webhook_details, applepay_verified_domains, pm_auth_config, connector_label, status, connector_wallets_details, additional_merchant_data, feature_metadata, } => Self { connector_type, connector_account_details: connector_account_details.map(Encryption::from), disabled, payment_methods_enabled, metadata, frm_config: frm_configs, modified_at: Some(date_time::now()), connector_webhook_details: *connector_webhook_details, applepay_verified_domains, pm_auth_config: *pm_auth_config, connector_label, status, connector_wallets_details: connector_wallets_details.map(Encryption::from), additional_merchant_data: additional_merchant_data.map(Encryption::from), feature_metadata: feature_metadata.map(From::from), }, MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate { connector_wallets_details, } => Self { connector_wallets_details: Some(Encryption::from(connector_wallets_details)), connector_type: None, connector_account_details: None, connector_label: None, disabled: None, payment_methods_enabled: None, metadata: None, modified_at: None, connector_webhook_details: None, frm_config: None, applepay_verified_domains: None, pm_auth_config: None, status: None, additional_merchant_data: None, feature_metadata: None, }, } } } common_utils::create_list_wrapper!( MerchantConnectorAccounts, MerchantConnectorAccount, impl_functions: { fn filter_and_map<'a, T>( &'a self, filter: impl Fn(&'a MerchantConnectorAccount) -> bool, func: impl Fn(&'a MerchantConnectorAccount) -> T, ) -> rustc_hash::FxHashSet<T> where T: std::hash::Hash + Eq, { self.0 .iter() .filter(|mca| filter(mca)) .map(func) .collect::<rustc_hash::FxHashSet<_>>() } pub fn filter_by_profile<'a, T>( &'a self, profile_id: &'a id_type::ProfileId, func: impl Fn(&'a MerchantConnectorAccount) -> T, ) -> rustc_hash::FxHashSet<T> where T: std::hash::Hash + Eq, { self.filter_and_map(|mca| mca.profile_id == *profile_id, func) } #[cfg(feature = "v2")] pub fn get_connector_and_supporting_payment_method_type_for_session_call( &self, ) -> Vec<(&MerchantConnectorAccount, common_enums::PaymentMethodType, common_enums::PaymentMethod)> { // This vector is created to work around lifetimes let ref_vector = Vec::default(); let connector_and_supporting_payment_method_type = self.iter().flat_map(|connector_account| { connector_account .payment_methods_enabled.as_ref() .unwrap_or(&Vec::default()) .iter() .flat_map(|payment_method_types| payment_method_types.payment_method_subtypes.as_ref().unwrap_or(&ref_vector).iter().map(|payment_method_subtype| (payment_method_subtype, payment_method_types.payment_method_type)).collect::<Vec<_>>()) .filter(|(payment_method_types_enabled, _)| { payment_method_types_enabled.payment_experience == Some(api_models::enums::PaymentExperience::InvokeSdkClient) }) .map(|(payment_method_subtypes, payment_method_type)| { (connector_account, payment_method_subtypes.payment_method_subtype, payment_method_type) }) .collect::<Vec<_>>() }).collect(); connector_and_supporting_payment_method_type } pub fn filter_based_on_profile_and_connector_type( self, profile_id: &id_type::ProfileId, connector_type: common_enums::ConnectorType, ) -> Self { self.into_iter() .filter(|mca| &mca.profile_id == profile_id && mca.connector_type == connector_type) .collect() } pub fn is_merchant_connector_account_id_in_connector_mandate_details( &self, profile_id: Option<&id_type::ProfileId>, connector_mandate_details: &CommonMandateReference, ) -> bool { let mca_ids = self .iter() .filter(|mca| { mca.disabled.is_some_and(|disabled| !disabled) && profile_id.is_some_and(|profile_id| *profile_id == mca.profile_id) }) .map(|mca| mca.get_id()) .collect::<std::collections::HashSet<_>>(); connector_mandate_details .payments .as_ref() .as_ref().is_some_and(|payments| { payments.0.keys().any(|mca_id| mca_ids.contains(mca_id)) }) } } ); #[cfg(feature = "v2")] impl From<MerchantConnectorAccountFeatureMetadata> for DieselMerchantConnectorAccountFeatureMetadata { fn from(feature_metadata: MerchantConnectorAccountFeatureMetadata) -> Self { let revenue_recovery = feature_metadata.revenue_recovery.map(|recovery_metadata| { DieselRevenueRecoveryMetadata { max_retry_count: recovery_metadata.max_retry_count, billing_connector_retry_threshold: recovery_metadata .billing_connector_retry_threshold, billing_account_reference: DieselBillingAccountReference( recovery_metadata.mca_reference.recovery_to_billing, ), } }); Self { revenue_recovery } } } #[cfg(feature = "v2")] impl From<DieselMerchantConnectorAccountFeatureMetadata> for MerchantConnectorAccountFeatureMetadata { fn from(feature_metadata: DieselMerchantConnectorAccountFeatureMetadata) -> Self { let revenue_recovery = feature_metadata.revenue_recovery.map(|recovery_metadata| { let mut billing_to_recovery = HashMap::new(); for (key, value) in &recovery_metadata.billing_account_reference.0 { billing_to_recovery.insert(value.to_string(), key.clone()); } RevenueRecoveryMetadata { max_retry_count: recovery_metadata.max_retry_count, billing_connector_retry_threshold: recovery_metadata .billing_connector_retry_threshold, mca_reference: AccountReferenceMap { recovery_to_billing: recovery_metadata.billing_account_reference.0, billing_to_recovery, }, } }); Self { revenue_recovery } } } #[async_trait::async_trait] pub trait MerchantConnectorAccountInterface where MerchantConnectorAccount: behaviour::Conversion< DstType = storage::MerchantConnectorAccount, NewDstType = storage::MerchantConnectorAccountNew, >, { type Error; #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, connector_label: &str, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccount, Self::Error>; #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccount, Self::Error>; #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<MerchantConnectorAccount>, Self::Error>; async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: MerchantConnectorAccount, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccount, Self::Error>; #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccount, Self::Error>; #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccount, Self::Error>; async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, get_disabled: bool, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccounts, Self::Error>; #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<MerchantConnectorAccount>, Self::Error>; async fn list_enabled_connector_accounts_by_profile_id( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, key_store: &MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<MerchantConnectorAccount>, Self::Error>; async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: MerchantConnectorAccount, merchant_connector_account: MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccount, Self::Error>; async fn update_multiple_merchant_connector_accounts( &self, this: Vec<( MerchantConnectorAccount, MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), Self::Error>; #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error>; #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error>; }
crates/hyperswitch_domain_models/src/merchant_connector_account.rs
hyperswitch_domain_models::src::merchant_connector_account
8,515
true
// File: crates/hyperswitch_domain_models/src/configs.rs // Module: hyperswitch_domain_models::src::configs use common_utils::errors::CustomResult; use diesel_models::configs as storage; #[async_trait::async_trait] pub trait ConfigInterface { type Error; async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, Self::Error>; async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error>; async fn find_config_by_key_unwrap_or( &self, key: &str, // If the config is not found it will be created with the default value. default_config: Option<String>, ) -> CustomResult<storage::Config, Self::Error>; async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, Self::Error>; async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, Self::Error>; async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, Self::Error>; async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error>; }
crates/hyperswitch_domain_models/src/configs.rs
hyperswitch_domain_models::src::configs
322
true
// File: crates/hyperswitch_domain_models/src/payments.rs // Module: hyperswitch_domain_models::src::payments #[cfg(feature = "v2")] use std::marker::PhantomData; #[cfg(feature = "v2")] use api_models::payments::{ConnectorMetadata, SessionToken, VaultSessionDetails}; use common_types::primitive_wrappers; #[cfg(feature = "v1")] use common_types::primitive_wrappers::{ AlwaysRequestExtendedAuthorization, EnableOvercaptureBool, RequestExtendedAuthorizationBool, }; use common_utils::{ self, crypto::Encryptable, encryption::Encryption, errors::CustomResult, ext_traits::ValueExt, id_type, pii, types::{keymanager::ToEncryptable, CreatedBy, MinorUnit}, }; use diesel_models::payment_intent::TaxDetails; #[cfg(feature = "v2")] use error_stack::ResultExt; use masking::Secret; use router_derive::ToEncryption; use rustc_hash::FxHashMap; use serde_json::Value; use time::PrimitiveDateTime; pub mod payment_attempt; pub mod payment_intent; use common_enums as storage_enums; #[cfg(feature = "v2")] use diesel_models::types::{FeatureMetadata, OrderDetailsWithAmount}; use self::payment_attempt::PaymentAttempt; #[cfg(feature = "v2")] use crate::{ address::Address, business_profile, customer, errors, merchant_connector_account, merchant_connector_account::MerchantConnectorAccountTypeDetails, merchant_context, payment_address, payment_method_data, payment_methods, revenue_recovery, routing, ApiModelToDieselModelConvertor, }; #[cfg(feature = "v1")] use crate::{payment_method_data, RemoteStorageObject}; #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)] pub struct PaymentIntent { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub shipping_cost: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, pub metadata: Option<Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub active_attempt: RemoteStorageObject<PaymentAttempt>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<Value>, pub connector_metadata: Option<Value>, pub feature_metadata: Option<Value>, pub attempt_count: i16, pub profile_id: Option<id_type::ProfileId>, pub payment_link_id: Option<String>, // 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>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub fingerprint_id: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub frm_metadata: Option<pii::SecretSerdeValue>, #[encrypt] pub customer_details: Option<Encryptable<Secret<Value>>>, #[encrypt] pub billing_details: Option<Encryptable<Secret<Value>>>, pub merchant_order_reference_id: Option<String>, #[encrypt] pub shipping_details: Option<Encryptable<Secret<Value>>>, pub is_payment_processor_token_flow: Option<bool>, pub organization_id: id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub processor_merchant_id: id_type::MerchantId, pub created_by: Option<CreatedBy>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub is_payment_id_from_merchant: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub tax_status: Option<storage_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, pub enable_overcapture: Option<EnableOvercaptureBool>, pub mit_category: Option<common_enums::MitCategory>, } impl PaymentIntent { #[cfg(feature = "v1")] pub fn get_id(&self) -> &id_type::PaymentId { &self.payment_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &id_type::GlobalPaymentId { &self.id } #[cfg(feature = "v2")] /// This is the url to which the customer will be redirected to, to complete the redirection flow pub fn create_start_redirection_url( &self, base_url: &str, publishable_key: String, ) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> { let start_redirection_url = &format!( "{}/v2/payments/{}/start-redirection?publishable_key={}&profile_id={}", base_url, self.get_id().get_string_repr(), publishable_key, self.profile_id.get_string_repr() ); url::Url::parse(start_redirection_url) .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Error creating start redirection url") } #[cfg(feature = "v1")] pub fn get_request_extended_authorization_bool_if_connector_supports( &self, connector: common_enums::connector_enums::Connector, always_request_extended_authorization_optional: Option<AlwaysRequestExtendedAuthorization>, payment_method_optional: Option<common_enums::PaymentMethod>, payment_method_type_optional: Option<common_enums::PaymentMethodType>, ) -> Option<RequestExtendedAuthorizationBool> { use router_env::logger; let is_extended_authorization_supported_by_connector = || { let supported_pms = connector.get_payment_methods_supporting_extended_authorization(); let supported_pmts = connector.get_payment_method_types_supporting_extended_authorization(); // check if payment method or payment method type is supported by the connector logger::info!( "Extended Authentication Connector:{:?}, Supported payment methods: {:?}, Supported payment method types: {:?}, Payment method Selected: {:?}, Payment method type Selected: {:?}", connector, supported_pms, supported_pmts, payment_method_optional, payment_method_type_optional ); match (payment_method_optional, payment_method_type_optional) { (Some(payment_method), Some(payment_method_type)) => { supported_pms.contains(&payment_method) && supported_pmts.contains(&payment_method_type) } (Some(payment_method), None) => supported_pms.contains(&payment_method), (None, Some(payment_method_type)) => supported_pmts.contains(&payment_method_type), (None, None) => false, } }; let intent_request_extended_authorization_optional = self.request_extended_authorization; let is_extended_authorization_requested = intent_request_extended_authorization_optional .map(|should_request_extended_authorization| *should_request_extended_authorization) .or(always_request_extended_authorization_optional.map( |should_always_request_extended_authorization| { *should_always_request_extended_authorization }, )); is_extended_authorization_requested .map(|requested| { if requested { is_extended_authorization_supported_by_connector() } else { false } }) .map(RequestExtendedAuthorizationBool::from) } #[cfg(feature = "v1")] pub fn get_enable_overcapture_bool_if_connector_supports( &self, connector: common_enums::connector_enums::Connector, always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, capture_method: &Option<common_enums::CaptureMethod>, ) -> Option<EnableOvercaptureBool> { let is_overcapture_supported_by_connector = connector.is_overcapture_supported_by_connector(); if matches!(capture_method, Some(common_enums::CaptureMethod::Manual)) && is_overcapture_supported_by_connector { self.enable_overcapture .or_else(|| always_enable_overcapture.map(EnableOvercaptureBool::from)) } else { None } } #[cfg(feature = "v2")] /// This is the url to which the customer will be redirected to, after completing the redirection flow pub fn create_finish_redirection_url( &self, base_url: &str, publishable_key: &str, ) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> { let finish_redirection_url = format!( "{base_url}/v2/payments/{}/finish-redirection/{publishable_key}/{}", self.id.get_string_repr(), self.profile_id.get_string_repr() ); url::Url::parse(&finish_redirection_url) .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Error creating finish redirection url") } pub fn parse_and_get_metadata<T>( &self, type_name: &'static str, ) -> CustomResult<Option<T>, common_utils::errors::ParsingError> where T: for<'de> masking::Deserialize<'de>, { self.metadata .clone() .map(|metadata| metadata.parse_value(type_name)) .transpose() } #[cfg(feature = "v1")] pub fn merge_metadata( &self, request_metadata: Value, ) -> Result<Value, common_utils::errors::ParsingError> { if !request_metadata.is_null() { match (&self.metadata, &request_metadata) { (Some(Value::Object(existing_map)), Value::Object(req_map)) => { let mut merged = existing_map.clone(); merged.extend(req_map.clone()); Ok(Value::Object(merged)) } (None, Value::Object(_)) => Ok(request_metadata), _ => { router_env::logger::error!( "Expected metadata to be an object, got: {:?}", request_metadata ); Err(common_utils::errors::ParsingError::UnknownError) } } } else { router_env::logger::error!("Metadata does not contain any key"); Err(common_utils::errors::ParsingError::UnknownError) } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize)] pub struct AmountDetails { /// The amount of the order in the lowest denomination of currency pub order_amount: MinorUnit, /// The currency of the order 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 details related to the order. This will be calculated by the external tax provider pub tax_details: Option<TaxDetails>, /// The action to whether calculate tax by calling external tax provider or not pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not pub skip_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 captured for the order. This is the sum of all the captured amounts for the order. /// For automatic captures, this will be the same as net amount for the order pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { /// Get the action to whether calculate surcharge or not as a boolean value fn get_surcharge_action_as_bool(&self) -> bool { self.skip_surcharge_calculation.as_bool() } /// Get the action to whether calculate external tax or not as a boolean value pub fn get_external_tax_action_as_bool(&self) -> bool { self.skip_external_tax_calculation.as_bool() } /// Calculate the net amount for the order pub fn calculate_net_amount(&self) -> MinorUnit { self.order_amount + self.shipping_cost.unwrap_or(MinorUnit::zero()) + self.surcharge_amount.unwrap_or(MinorUnit::zero()) + self.tax_on_surcharge.unwrap_or(MinorUnit::zero()) } pub fn create_attempt_amount_details( &self, confirm_intent_request: &api_models::payments::PaymentsConfirmIntentRequest, ) -> payment_attempt::AttemptAmountDetails { let net_amount = self.calculate_net_amount(); let surcharge_amount = match self.skip_surcharge_calculation { common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount, common_enums::SurchargeCalculationOverride::Calculate => None, }; let tax_on_surcharge = match self.skip_surcharge_calculation { common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge, common_enums::SurchargeCalculationOverride::Calculate => None, }; let order_tax_amount = match self.skip_external_tax_calculation { common_enums::TaxCalculationOverride::Skip => { self.tax_details.as_ref().and_then(|tax_details| { tax_details.get_tax_amount(Some(confirm_intent_request.payment_method_subtype)) }) } common_enums::TaxCalculationOverride::Calculate => None, }; payment_attempt::AttemptAmountDetails::from(payment_attempt::AttemptAmountDetailsSetter { net_amount, amount_to_capture: None, surcharge_amount, tax_on_surcharge, // This will be updated when we receive response from the connector amount_capturable: MinorUnit::zero(), shipping_cost: self.shipping_cost, order_tax_amount, }) } pub fn proxy_create_attempt_amount_details( &self, _confirm_intent_request: &api_models::payments::ProxyPaymentsRequest, ) -> payment_attempt::AttemptAmountDetails { let net_amount = self.calculate_net_amount(); let surcharge_amount = match self.skip_surcharge_calculation { common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount, common_enums::SurchargeCalculationOverride::Calculate => None, }; let tax_on_surcharge = match self.skip_surcharge_calculation { common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge, common_enums::SurchargeCalculationOverride::Calculate => None, }; let order_tax_amount = match self.skip_external_tax_calculation { common_enums::TaxCalculationOverride::Skip => self .tax_details .as_ref() .and_then(|tax_details| tax_details.get_tax_amount(None)), common_enums::TaxCalculationOverride::Calculate => None, }; payment_attempt::AttemptAmountDetails::from(payment_attempt::AttemptAmountDetailsSetter { net_amount, amount_to_capture: None, surcharge_amount, tax_on_surcharge, // This will be updated when we receive response from the connector amount_capturable: MinorUnit::zero(), shipping_cost: self.shipping_cost, order_tax_amount, }) } pub fn update_from_request(self, req: &api_models::payments::AmountDetailsUpdate) -> Self { Self { order_amount: req .order_amount() .unwrap_or(self.order_amount.into()) .into(), currency: req.currency().unwrap_or(self.currency), shipping_cost: req.shipping_cost().or(self.shipping_cost), tax_details: req .order_tax_amount() .map(|order_tax_amount| TaxDetails { default: Some(diesel_models::DefaultTax { order_tax_amount }), payment_method_type: None, }) .or(self.tax_details), skip_external_tax_calculation: req .skip_external_tax_calculation() .unwrap_or(self.skip_external_tax_calculation), skip_surcharge_calculation: req .skip_surcharge_calculation() .unwrap_or(self.skip_surcharge_calculation), surcharge_amount: req.surcharge_amount().or(self.surcharge_amount), tax_on_surcharge: req.tax_on_surcharge().or(self.tax_on_surcharge), amount_captured: self.amount_captured, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)] pub struct PaymentIntent { /// The global identifier for the payment intent. This is generated by the system. /// The format of the global id is `{cell_id:5}_pay_{time_ordered_uuid:32}`. pub id: id_type::GlobalPaymentId, /// The identifier for the merchant. This is automatically derived from the api key used to create the payment. pub merchant_id: id_type::MerchantId, /// The status of payment intent. pub status: storage_enums::IntentStatus, /// The amount related details of the payment pub amount_details: AmountDetails, /// The total amount captured for the order. This is the sum of all the captured amounts for the order. pub amount_captured: Option<MinorUnit>, /// The identifier for the customer. This is the identifier for the customer in the merchant's system. pub customer_id: Option<id_type::GlobalCustomerId>, /// The description of the order. This will be passed to connectors which support description. pub description: Option<common_utils::types::Description>, /// The return url for the payment. This is the url to which the user will be redirected after the payment is completed. pub return_url: Option<common_utils::types::Url>, /// The metadata for the payment intent. This is the metadata that will be passed to the connectors. pub metadata: Option<pii::SecretSerdeValue>, /// The statement descriptor for the order, this will be displayed in the user's bank statement. pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// The time at which the order was created #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The time at which the order was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: storage_enums::FutureUsage, /// The active attempt for the payment intent. This is the payment attempt that is currently active for the payment intent. pub active_attempt_id: Option<id_type::GlobalAttemptId>, /// This field represents whether there are attempt groups for this payment intent. Used in split payments workflow pub active_attempt_id_type: common_enums::ActiveAttemptIDType, /// The ID of the active attempt group for the payment intent pub active_attempts_group_id: Option<String>, /// The order details for the payment. pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// This is the list of payment method types that are allowed for the payment intent. /// This field allows the merchant to restrict the payment methods that can be used for the payment intent. pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// This metadata contains connector-specific details like Apple Pay certificates, Airwallex data, Noon order category, Braintree merchant account ID, and Adyen testing data pub connector_metadata: Option<ConnectorMetadata>, pub feature_metadata: Option<FeatureMetadata>, /// Number of attempts that have been made for the order pub attempt_count: i16, /// The profile id for the payment. pub profile_id: id_type::ProfileId, /// The payment link id for the payment. This is generated only if `enable_payment_link` is set to true. pub payment_link_id: Option<String>, /// This 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 frm_merchant_decision: Option<common_enums::MerchantDecision>, /// Denotes the last instance which updated the payment pub updated_by: String, /// Denotes whether merchant requested for incremental authorization to be enabled for this payment. pub request_incremental_authorization: storage_enums::RequestIncrementalAuthorization, /// Denotes whether merchant requested for split payments to be enabled for this payment pub split_txns_enabled: storage_enums::SplitTxnsEnabled, /// Denotes the number of authorizations that have been made for the payment. pub authorization_count: Option<i32>, /// Denotes the client secret expiry for the payment. This is the time at which the client secret will expire. #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, /// Denotes whether merchant requested for 3ds authentication to be enabled for this payment. pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, /// Metadata related to fraud and risk management pub frm_metadata: Option<pii::SecretSerdeValue>, /// The details of the customer in a denormalized form. Only a subset of fields are stored. #[encrypt] pub customer_details: Option<Encryptable<Secret<Value>>>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The billing address for the order in a denormalized form. #[encrypt(ty = Value)] pub billing_address: Option<Encryptable<Address>>, /// The shipping address for the order in a denormalized form. #[encrypt(ty = Value)] pub shipping_address: Option<Encryptable<Address>>, /// Capture method for the payment pub capture_method: storage_enums::CaptureMethod, /// Authentication type that is requested by the merchant for this payment. pub authentication_type: Option<common_enums::AuthenticationType>, /// This contains the pre routing results that are done when routing is done during listing the payment methods. pub prerouting_algorithm: Option<routing::PaymentRoutingInfo>, /// The organization id for the payment. This is derived from the merchant account pub organization_id: id_type::OrganizationId, /// Denotes the request by the merchant whether to enable a payment link for this payment. pub enable_payment_link: common_enums::EnablePaymentLinkRequest, /// Denotes the request by the merchant whether to apply MIT exemption for this payment pub apply_mit_exemption: common_enums::MitExemptionRequest, /// Denotes whether the customer is present during the payment flow. This information may be used for 3ds authentication pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// Denotes the override for payment link configuration pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>, /// The straight through routing algorithm id that is used for this payment. This overrides the default routing algorithm that is configured in business profile. pub routing_algorithm_id: Option<id_type::RoutingId>, /// Split Payment Data pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, /// merchant who owns the credentials of the processor, i.e. processor owner pub processor_merchant_id: id_type::MerchantId, /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) pub created_by: Option<CreatedBy>, /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, /// Indicates whether the payment_id was provided by the merchant (true), /// or generated internally by Hyperswitch (false) pub is_payment_id_from_merchant: Option<bool>, /// Denotes whether merchant requested for partial authorization to be enabled for this payment. pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, } #[cfg(feature = "v2")] impl PaymentIntent { /// Extract customer_id from payment intent feature metadata pub fn extract_connector_customer_id_from_payment_intent( &self, ) -> Result<String, common_utils::errors::ValidationError> { self.feature_metadata .as_ref() .and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref()) .map(|recovery| { recovery .billing_connector_payment_details .connector_customer_id .clone() }) .ok_or( common_utils::errors::ValidationError::MissingRequiredField { field_name: "connector_customer_id".to_string(), }, ) } fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> { self.feature_metadata .as_ref() .and_then(|metadata| metadata.get_payment_method_sub_type()) } fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod> { self.feature_metadata .as_ref() .and_then(|metadata| metadata.get_payment_method_type()) } pub fn get_connector_customer_id_from_feature_metadata(&self) -> Option<String> { self.feature_metadata .as_ref() .and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref()) .map(|recovery_metadata| { recovery_metadata .billing_connector_payment_details .connector_customer_id .clone() }) } pub fn get_billing_merchant_connector_account_id( &self, ) -> Option<id_type::MerchantConnectorAccountId> { self.feature_metadata.as_ref().and_then(|feature_metadata| { feature_metadata.get_billing_merchant_connector_account_id() }) } fn get_request_incremental_authorization_value( request: &api_models::payments::PaymentsCreateIntentRequest, ) -> CustomResult< common_enums::RequestIncrementalAuthorization, errors::api_error_response::ApiErrorResponse, > { request.request_incremental_authorization .map(|request_incremental_authorization| { if request_incremental_authorization == common_enums::RequestIncrementalAuthorization::True { if request.capture_method == Some(common_enums::CaptureMethod::Automatic) { Err(errors::api_error_response::ApiErrorResponse::InvalidRequestData { message: "incremental authorization is not supported when capture_method is automatic".to_owned() })? } Ok(common_enums::RequestIncrementalAuthorization::True) } else { Ok(common_enums::RequestIncrementalAuthorization::False) } }) .unwrap_or(Ok(common_enums::RequestIncrementalAuthorization::default())) } pub async fn create_domain_model_from_request( payment_id: &id_type::GlobalPaymentId, merchant_context: &merchant_context::MerchantContext, profile: &business_profile::Profile, request: api_models::payments::PaymentsCreateIntentRequest, decrypted_payment_intent: DecryptedPaymentIntent, ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> { let request_incremental_authorization = Self::get_request_incremental_authorization_value(&request)?; let allowed_payment_method_types = request.allowed_payment_method_types; let session_expiry = common_utils::date_time::now().saturating_add(time::Duration::seconds( request.session_expiry.map(i64::from).unwrap_or( profile .session_expiry .unwrap_or(common_utils::consts::DEFAULT_SESSION_EXPIRY), ), )); let order_details = request.order_details.map(|order_details| { order_details .into_iter() .map(|order_detail| Secret::new(OrderDetailsWithAmount::convert_from(order_detail))) .collect() }); Ok(Self { id: payment_id.clone(), merchant_id: merchant_context.get_merchant_account().get_id().clone(), // Intent status would be RequiresPaymentMethod because we are creating a new payment intent status: common_enums::IntentStatus::RequiresPaymentMethod, amount_details: AmountDetails::from(request.amount_details), amount_captured: None, customer_id: request.customer_id, description: request.description, return_url: request.return_url, metadata: request.metadata, statement_descriptor: request.statement_descriptor, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), last_synced: None, setup_future_usage: request.setup_future_usage.unwrap_or_default(), active_attempt_id: None, active_attempt_id_type: common_enums::ActiveAttemptIDType::AttemptID, active_attempts_group_id: None, order_details, allowed_payment_method_types, connector_metadata: request.connector_metadata, feature_metadata: request.feature_metadata.map(FeatureMetadata::convert_from), // Attempt count is 0 in create intent as no attempt is made yet attempt_count: 0, profile_id: profile.get_id().clone(), payment_link_id: None, frm_merchant_decision: None, updated_by: merchant_context .get_merchant_account() .storage_scheme .to_string(), request_incremental_authorization, // Authorization count is 0 in create intent as no authorization is made yet authorization_count: Some(0), session_expiry, request_external_three_ds_authentication: request .request_external_three_ds_authentication .unwrap_or_default(), split_txns_enabled: profile.split_txns_enabled, frm_metadata: request.frm_metadata, customer_details: None, merchant_reference_id: request.merchant_reference_id, billing_address: decrypted_payment_intent .billing_address .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?, shipping_address: decrypted_payment_intent .shipping_address .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode shipping address")?, capture_method: request.capture_method.unwrap_or_default(), authentication_type: request.authentication_type, prerouting_algorithm: None, organization_id: merchant_context .get_merchant_account() .organization_id .clone(), enable_payment_link: request.payment_link_enabled.unwrap_or_default(), apply_mit_exemption: request.apply_mit_exemption.unwrap_or_default(), customer_present: request.customer_present.unwrap_or_default(), payment_link_config: request .payment_link_config .map(ApiModelToDieselModelConvertor::convert_from), routing_algorithm_id: request.routing_algorithm_id, split_payments: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, processor_merchant_id: merchant_context.get_merchant_account().get_id().clone(), created_by: None, is_iframe_redirection_enabled: None, is_payment_id_from_merchant: None, enable_partial_authorization: request.enable_partial_authorization, }) } pub fn get_revenue_recovery_metadata( &self, ) -> Option<diesel_models::types::PaymentRevenueRecoveryMetadata> { self.feature_metadata .as_ref() .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone()) } pub fn get_feature_metadata(&self) -> Option<FeatureMetadata> { self.feature_metadata.clone() } pub fn create_revenue_recovery_attempt_data( &self, revenue_recovery_metadata: api_models::payments::PaymentRevenueRecoveryMetadata, billing_connector_account: &merchant_connector_account::MerchantConnectorAccount, card_info: api_models::payments::AdditionalCardInfo, payment_processor_token: &str, ) -> CustomResult< revenue_recovery::RevenueRecoveryAttemptData, errors::api_error_response::ApiErrorResponse, > { let merchant_reference_id = self.merchant_reference_id.clone().ok_or_else(|| { error_stack::report!( errors::api_error_response::ApiErrorResponse::GenericNotFoundError { message: "mandate reference id not found".to_string() } ) })?; let connector_account_reference_id = billing_connector_account .get_account_reference_id_using_payment_merchant_connector_account_id( revenue_recovery_metadata.active_attempt_payment_connector_id, ) .ok_or_else(|| { error_stack::report!( errors::api_error_response::ApiErrorResponse::GenericNotFoundError { message: "connector account reference id not found".to_string() } ) })?; Ok(revenue_recovery::RevenueRecoveryAttemptData { amount: self.amount_details.order_amount, currency: self.amount_details.currency, merchant_reference_id, connector_transaction_id: None, // No connector id error_code: None, error_message: None, processor_payment_method_token: payment_processor_token.to_string(), connector_customer_id: revenue_recovery_metadata .billing_connector_payment_details .connector_customer_id, connector_account_reference_id, transaction_created_at: None, // would unwrap_or as now status: common_enums::AttemptStatus::Started, payment_method_type: self .get_payment_method_type() .unwrap_or(revenue_recovery_metadata.payment_method_type), payment_method_sub_type: self .get_payment_method_sub_type() .unwrap_or(revenue_recovery_metadata.payment_method_subtype), network_advice_code: None, network_decline_code: None, network_error_message: None, retry_count: None, invoice_next_billing_time: None, invoice_billing_started_at_time: None, // No charge id is present here since it is an internal payment and we didn't call connector yet. charge_id: None, card_info: card_info.clone(), }) } pub fn get_optional_customer_id( &self, ) -> CustomResult<Option<id_type::CustomerId>, common_utils::errors::ValidationError> { self.customer_id .as_ref() .map(|customer_id| id_type::CustomerId::try_from(customer_id.clone())) .transpose() } pub fn get_currency(&self) -> storage_enums::Currency { self.amount_details.currency } } #[cfg(feature = "v1")] #[derive(Default, Debug, Clone, serde::Serialize)] pub struct HeaderPayload { pub payment_confirm_source: Option<common_enums::PaymentSource>, pub client_source: Option<String>, pub client_version: Option<String>, pub x_hs_latency: Option<bool>, pub browser_name: Option<common_enums::BrowserName>, pub x_client_platform: Option<common_enums::ClientPlatform>, pub x_merchant_domain: Option<String>, pub locale: Option<String>, pub x_app_id: Option<String>, pub x_redirect_uri: Option<String>, pub x_reference_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ClickToPayMetaData { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, pub dpa_client_id: Option<String>, } // TODO: uncomment fields as necessary #[cfg(feature = "v2")] #[derive(Default, Debug, Clone, serde::Serialize)] pub struct HeaderPayload { /// The source with which the payment is confirmed. pub payment_confirm_source: Option<common_enums::PaymentSource>, // pub client_source: Option<String>, // pub client_version: Option<String>, pub x_hs_latency: Option<bool>, pub browser_name: Option<common_enums::BrowserName>, pub x_client_platform: Option<common_enums::ClientPlatform>, pub x_merchant_domain: Option<String>, pub locale: Option<String>, pub x_app_id: Option<String>, pub x_redirect_uri: Option<String>, pub x_reference_id: Option<String>, } impl HeaderPayload { pub fn with_source(payment_confirm_source: common_enums::PaymentSource) -> Self { Self { payment_confirm_source: Some(payment_confirm_source), ..Default::default() } } } #[cfg(feature = "v2")] #[derive(Clone)] pub struct PaymentIntentData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub sessions_token: Vec<SessionToken>, pub client_secret: Option<Secret<String>>, pub vault_session_details: Option<VaultSessionDetails>, pub connector_customer_id: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone)] pub struct PaymentAttemptListData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_attempt_list: Vec<PaymentAttempt>, } // TODO: Check if this can be merged with existing payment data #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct PaymentConfirmData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, pub payment_method_data: Option<payment_method_data::PaymentMethodData>, pub payment_address: payment_address::PaymentAddress, pub mandate_data: Option<api_models::payments::MandateIds>, pub payment_method: Option<payment_methods::PaymentMethod>, pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, pub external_vault_pmd: Option<payment_method_data::ExternalVaultPaymentMethodData>, /// The webhook url of the merchant, to which the connector will send the webhook. pub webhook_url: Option<String>, } #[cfg(feature = "v2")] impl<F: Clone> PaymentConfirmData<F> { pub fn get_connector_customer_id( &self, customer: Option<&customer::Customer>, merchant_connector_account: &MerchantConnectorAccountTypeDetails, ) -> Option<String> { match merchant_connector_account { MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(_) => customer .and_then(|customer| customer.get_connector_customer_id(merchant_connector_account)) .map(|id| id.to_string()) .or_else(|| { self.payment_intent .get_connector_customer_id_from_feature_metadata() }), MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None, } } pub fn update_payment_method_data( &mut self, payment_method_data: payment_method_data::PaymentMethodData, ) { self.payment_method_data = Some(payment_method_data); } pub fn update_payment_method_and_pm_id( &mut self, payment_method_id: id_type::GlobalPaymentMethodId, payment_method: payment_methods::PaymentMethod, ) { self.payment_attempt.payment_method_id = Some(payment_method_id); self.payment_method = Some(payment_method); } } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct PaymentStatusData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, pub payment_address: payment_address::PaymentAddress, pub attempts: Option<Vec<PaymentAttempt>>, /// Should the payment status be synced with connector /// This will depend on the payment status and the force sync flag in the request pub should_sync_with_connector: bool, pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[cfg(feature = "v2")] #[derive(Clone)] pub struct PaymentCaptureData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, } #[cfg(feature = "v2")] #[derive(Clone)] pub struct PaymentCancelData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, } #[cfg(feature = "v2")] impl<F> PaymentStatusData<F> where F: Clone, { pub fn get_payment_id(&self) -> &id_type::GlobalPaymentId { &self.payment_intent.id } } #[cfg(feature = "v2")] #[derive(Clone)] pub struct PaymentAttemptRecordData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, pub revenue_recovery_data: RevenueRecoveryData, pub payment_address: payment_address::PaymentAddress, } #[cfg(feature = "v2")] #[derive(Clone)] pub struct RevenueRecoveryData { pub billing_connector_id: id_type::MerchantConnectorAccountId, pub processor_payment_method_token: String, pub connector_customer_id: String, pub retry_count: Option<u16>, pub invoice_next_billing_time: Option<PrimitiveDateTime>, pub triggered_by: storage_enums::enums::TriggeredBy, pub card_network: Option<common_enums::CardNetwork>, pub card_issuer: Option<String>, } #[cfg(feature = "v2")] impl<F> PaymentAttemptRecordData<F> where F: Clone, { pub fn get_updated_feature_metadata( &self, ) -> CustomResult<Option<FeatureMetadata>, errors::api_error_response::ApiErrorResponse> { let payment_intent_feature_metadata = self.payment_intent.get_feature_metadata(); let revenue_recovery = self.payment_intent.get_revenue_recovery_metadata(); let payment_attempt_connector = self.payment_attempt.connector.clone(); let feature_metadata_first_pg_error_code = revenue_recovery .as_ref() .and_then(|data| data.first_payment_attempt_pg_error_code.clone()); let (first_pg_error_code, first_network_advice_code, first_network_decline_code) = feature_metadata_first_pg_error_code.map_or_else( || { let first_pg_error_code = self .payment_attempt .error .as_ref() .map(|error| error.code.clone()); let first_network_advice_code = self .payment_attempt .error .as_ref() .and_then(|error| error.network_advice_code.clone()); let first_network_decline_code = self .payment_attempt .error .as_ref() .and_then(|error| error.network_decline_code.clone()); ( first_pg_error_code, first_network_advice_code, first_network_decline_code, ) }, |pg_code| { let advice_code = revenue_recovery .as_ref() .and_then(|data| data.first_payment_attempt_network_advice_code.clone()); let decline_code = revenue_recovery .as_ref() .and_then(|data| data.first_payment_attempt_network_decline_code.clone()); (Some(pg_code), advice_code, decline_code) }, ); let billing_connector_payment_method_details = Some( diesel_models::types::BillingConnectorPaymentMethodDetails::Card( diesel_models::types::BillingConnectorAdditionalCardInfo { card_network: self.revenue_recovery_data.card_network.clone(), card_issuer: self.revenue_recovery_data.card_issuer.clone(), }, ), ); let payment_revenue_recovery_metadata = match payment_attempt_connector { Some(connector) => Some(diesel_models::types::PaymentRevenueRecoveryMetadata { // Update retry count by one. total_retry_count: revenue_recovery.as_ref().map_or( self.revenue_recovery_data .retry_count .map_or_else(|| 1, |retry_count| retry_count), |data| (data.total_retry_count + 1), ), // Since this is an external system call, marking this payment_connector_transmission to ConnectorCallSucceeded. payment_connector_transmission: common_enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, billing_connector_id: self.revenue_recovery_data.billing_connector_id.clone(), active_attempt_payment_connector_id: self .payment_attempt .get_attempt_merchant_connector_account_id()?, billing_connector_payment_details: diesel_models::types::BillingConnectorPaymentDetails { payment_processor_token: self .revenue_recovery_data .processor_payment_method_token .clone(), connector_customer_id: self .revenue_recovery_data .connector_customer_id .clone(), }, payment_method_type: self.payment_attempt.payment_method_type, payment_method_subtype: self.payment_attempt.payment_method_subtype, connector: connector.parse().map_err(|err| { router_env::logger::error!(?err, "Failed to parse connector string to enum"); errors::api_error_response::ApiErrorResponse::InternalServerError })?, invoice_next_billing_time: self.revenue_recovery_data.invoice_next_billing_time, invoice_billing_started_at_time: self .revenue_recovery_data .invoice_next_billing_time, billing_connector_payment_method_details, first_payment_attempt_network_advice_code: first_network_advice_code, first_payment_attempt_network_decline_code: first_network_decline_code, first_payment_attempt_pg_error_code: first_pg_error_code, }), None => Err(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Connector not found in payment attempt")?, }; Ok(Some(FeatureMetadata { redirect_response: payment_intent_feature_metadata .as_ref() .and_then(|data| data.redirect_response.clone()), search_tags: payment_intent_feature_metadata .as_ref() .and_then(|data| data.search_tags.clone()), apple_pay_recurring_details: payment_intent_feature_metadata .as_ref() .and_then(|data| data.apple_pay_recurring_details.clone()), payment_revenue_recovery_metadata, })) } } #[derive(Default, Clone, serde::Serialize, Debug)] pub struct CardAndNetworkTokenDataForVault { pub card_data: payment_method_data::Card, pub network_token: NetworkTokenDataForVault, } #[derive(Default, Clone, serde::Serialize, Debug)] pub struct NetworkTokenDataForVault { pub network_token_data: payment_method_data::NetworkTokenData, pub network_token_req_ref_id: String, } #[derive(Default, Clone, serde::Serialize, Debug)] pub struct CardDataForVault { pub card_data: payment_method_data::Card, pub network_token_req_ref_id: Option<String>, } #[derive(Clone, serde::Serialize, Debug)] pub enum VaultOperation { ExistingVaultData(VaultData), SaveCardData(CardDataForVault), SaveCardAndNetworkTokenData(Box<CardAndNetworkTokenDataForVault>), } impl VaultOperation { pub fn get_updated_vault_data( existing_vault_data: Option<&Self>, payment_method_data: &payment_method_data::PaymentMethodData, ) -> Option<Self> { match (existing_vault_data, payment_method_data) { (None, payment_method_data::PaymentMethodData::Card(card)) => { Some(Self::ExistingVaultData(VaultData::Card(card.clone()))) } (None, payment_method_data::PaymentMethodData::NetworkToken(nt_data)) => Some( Self::ExistingVaultData(VaultData::NetworkToken(nt_data.clone())), ), (Some(Self::ExistingVaultData(vault_data)), payment_method_data) => { match (vault_data, payment_method_data) { ( VaultData::Card(card), payment_method_data::PaymentMethodData::NetworkToken(nt_data), ) => Some(Self::ExistingVaultData(VaultData::CardAndNetworkToken( Box::new(CardAndNetworkTokenData { card_data: card.clone(), network_token_data: nt_data.clone(), }), ))), ( VaultData::NetworkToken(nt_data), payment_method_data::PaymentMethodData::Card(card), ) => Some(Self::ExistingVaultData(VaultData::CardAndNetworkToken( Box::new(CardAndNetworkTokenData { card_data: card.clone(), network_token_data: nt_data.clone(), }), ))), _ => Some(Self::ExistingVaultData(vault_data.clone())), } } //payment_method_data is not card or network token _ => None, } } } #[derive(Clone, serde::Serialize, Debug)] pub enum VaultData { Card(payment_method_data::Card), NetworkToken(payment_method_data::NetworkTokenData), CardAndNetworkToken(Box<CardAndNetworkTokenData>), } #[derive(Default, Clone, serde::Serialize, Debug)] pub struct CardAndNetworkTokenData { pub card_data: payment_method_data::Card, pub network_token_data: payment_method_data::NetworkTokenData, } impl VaultData { pub fn get_card_vault_data(&self) -> Option<payment_method_data::Card> { match self { Self::Card(card_data) => Some(card_data.clone()), Self::NetworkToken(_network_token_data) => None, Self::CardAndNetworkToken(vault_data) => Some(vault_data.card_data.clone()), } } pub fn get_network_token_data(&self) -> Option<payment_method_data::NetworkTokenData> { match self { Self::Card(_card_data) => None, Self::NetworkToken(network_token_data) => Some(network_token_data.clone()), Self::CardAndNetworkToken(vault_data) => Some(vault_data.network_token_data.clone()), } } }
crates/hyperswitch_domain_models/src/payments.rs
hyperswitch_domain_models::src::payments
11,156
true
// File: crates/hyperswitch_domain_models/src/transformers.rs // Module: hyperswitch_domain_models::src::transformers pub trait ForeignFrom<F> { fn foreign_from(from: F) -> Self; } pub trait ForeignTryFrom<F>: Sized { type Error; fn foreign_try_from(from: F) -> Result<Self, Self::Error>; }
crates/hyperswitch_domain_models/src/transformers.rs
hyperswitch_domain_models::src::transformers
79
true
// File: crates/hyperswitch_domain_models/src/merchant_context.rs // Module: hyperswitch_domain_models::src::merchant_context pub use crate::{merchant_account::MerchantAccount, merchant_key_store::MerchantKeyStore}; /// `MerchantContext` represents the authentication and operational context for a merchant. /// /// This enum encapsulates the merchant's account information and cryptographic keys /// needed for secure operations. Currently supports only normal merchant operations, /// but the enum structure allows for future expansion to different merchant types for example a /// **platform** context. #[derive(Clone, Debug)] pub enum MerchantContext { /// Represents a normal operation merchant context. NormalMerchant(Box<Context>), } /// `Context` holds the merchant account details and cryptographic key store. #[derive(Clone, Debug)] pub struct Context(pub MerchantAccount, pub MerchantKeyStore); impl MerchantContext { pub fn get_merchant_account(&self) -> &MerchantAccount { match self { Self::NormalMerchant(merchant_account) => &merchant_account.0, } } pub fn get_merchant_key_store(&self) -> &MerchantKeyStore { match self { Self::NormalMerchant(merchant_account) => &merchant_account.1, } } }
crates/hyperswitch_domain_models/src/merchant_context.rs
hyperswitch_domain_models::src::merchant_context
259
true
// File: crates/hyperswitch_domain_models/src/lib.rs // Module: hyperswitch_domain_models::src::lib pub mod address; pub mod api; pub mod authentication; pub mod behaviour; pub mod bulk_tokenization; pub mod business_profile; pub mod callback_mapper; pub mod card_testing_guard_data; pub mod cards_info; pub mod chat; pub mod configs; pub mod connector_endpoints; pub mod consts; pub mod customer; pub mod disputes; pub mod errors; pub mod ext_traits; pub mod gsm; pub mod invoice; pub mod mandates; pub mod master_key; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_context; pub mod merchant_key_store; pub mod network_tokenization; pub mod payment_address; pub mod payment_method_data; pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; pub mod refunds; pub mod relay; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] pub mod revenue_recovery; pub mod router_data; pub mod router_data_v2; pub mod router_flow_types; pub mod router_request_types; pub mod router_response_types; pub mod routing; pub mod subscription; #[cfg(feature = "tokenization_v2")] pub mod tokenization; pub mod transformers; pub mod type_encryption; pub mod types; pub mod vault; #[cfg(not(feature = "payouts"))] pub trait PayoutAttemptInterface {} #[cfg(not(feature = "payouts"))] pub trait PayoutsInterface {} use api_models::payments::{ ApplePayRecurringDetails as ApiApplePayRecurringDetails, ApplePayRegularBillingDetails as ApiApplePayRegularBillingDetails, FeatureMetadata as ApiFeatureMetadata, OrderDetailsWithAmount as ApiOrderDetailsWithAmount, RecurringPaymentIntervalUnit as ApiRecurringPaymentIntervalUnit, RedirectResponse as ApiRedirectResponse, }; #[cfg(feature = "v2")] use api_models::payments::{ BillingConnectorAdditionalCardInfo as ApiBillingConnectorAdditionalCardInfo, BillingConnectorPaymentDetails as ApiBillingConnectorPaymentDetails, BillingConnectorPaymentMethodDetails as ApiBillingConnectorPaymentMethodDetails, PaymentRevenueRecoveryMetadata as ApiRevenueRecoveryMetadata, }; use diesel_models::types::{ ApplePayRecurringDetails, ApplePayRegularBillingDetails, FeatureMetadata, OrderDetailsWithAmount, RecurringPaymentIntervalUnit, RedirectResponse, }; #[cfg(feature = "v2")] use diesel_models::types::{ BillingConnectorAdditionalCardInfo, BillingConnectorPaymentDetails, BillingConnectorPaymentMethodDetails, PaymentRevenueRecoveryMetadata, }; #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub enum RemoteStorageObject<T: ForeignIDRef> { ForeignID(String), Object(T), } impl<T: ForeignIDRef> From<T> for RemoteStorageObject<T> { fn from(value: T) -> Self { Self::Object(value) } } pub trait ForeignIDRef { fn foreign_id(&self) -> String; } impl<T: ForeignIDRef> RemoteStorageObject<T> { pub fn get_id(&self) -> String { match self { Self::ForeignID(id) => id.clone(), Self::Object(i) => i.foreign_id(), } } } use std::fmt::Debug; pub trait ApiModelToDieselModelConvertor<F> { /// Convert from a foreign type to the current type fn convert_from(from: F) -> Self; fn convert_back(self) -> F; } #[cfg(feature = "v1")] impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata { fn convert_from(from: ApiFeatureMetadata) -> Self { let ApiFeatureMetadata { redirect_response, search_tags, apple_pay_recurring_details, } = from; Self { redirect_response: redirect_response.map(RedirectResponse::convert_from), search_tags, apple_pay_recurring_details: apple_pay_recurring_details .map(ApplePayRecurringDetails::convert_from), gateway_system: None, } } fn convert_back(self) -> ApiFeatureMetadata { let Self { redirect_response, search_tags, apple_pay_recurring_details, .. } = self; ApiFeatureMetadata { redirect_response: redirect_response .map(|redirect_response| redirect_response.convert_back()), search_tags, apple_pay_recurring_details: apple_pay_recurring_details .map(|value| value.convert_back()), } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata { fn convert_from(from: ApiFeatureMetadata) -> Self { let ApiFeatureMetadata { redirect_response, search_tags, apple_pay_recurring_details, revenue_recovery: payment_revenue_recovery_metadata, } = from; Self { redirect_response: redirect_response.map(RedirectResponse::convert_from), search_tags, apple_pay_recurring_details: apple_pay_recurring_details .map(ApplePayRecurringDetails::convert_from), payment_revenue_recovery_metadata: payment_revenue_recovery_metadata .map(PaymentRevenueRecoveryMetadata::convert_from), } } fn convert_back(self) -> ApiFeatureMetadata { let Self { redirect_response, search_tags, apple_pay_recurring_details, payment_revenue_recovery_metadata, } = self; ApiFeatureMetadata { redirect_response: redirect_response .map(|redirect_response| redirect_response.convert_back()), search_tags, apple_pay_recurring_details: apple_pay_recurring_details .map(|value| value.convert_back()), revenue_recovery: payment_revenue_recovery_metadata.map(|value| value.convert_back()), } } } impl ApiModelToDieselModelConvertor<ApiRedirectResponse> for RedirectResponse { fn convert_from(from: ApiRedirectResponse) -> Self { let ApiRedirectResponse { param, json_payload, } = from; Self { param, json_payload, } } fn convert_back(self) -> ApiRedirectResponse { let Self { param, json_payload, } = self; ApiRedirectResponse { param, json_payload, } } } impl ApiModelToDieselModelConvertor<ApiRecurringPaymentIntervalUnit> for RecurringPaymentIntervalUnit { fn convert_from(from: ApiRecurringPaymentIntervalUnit) -> Self { match from { ApiRecurringPaymentIntervalUnit::Year => Self::Year, ApiRecurringPaymentIntervalUnit::Month => Self::Month, ApiRecurringPaymentIntervalUnit::Day => Self::Day, ApiRecurringPaymentIntervalUnit::Hour => Self::Hour, ApiRecurringPaymentIntervalUnit::Minute => Self::Minute, } } fn convert_back(self) -> ApiRecurringPaymentIntervalUnit { match self { Self::Year => ApiRecurringPaymentIntervalUnit::Year, Self::Month => ApiRecurringPaymentIntervalUnit::Month, Self::Day => ApiRecurringPaymentIntervalUnit::Day, Self::Hour => ApiRecurringPaymentIntervalUnit::Hour, Self::Minute => ApiRecurringPaymentIntervalUnit::Minute, } } } impl ApiModelToDieselModelConvertor<ApiApplePayRegularBillingDetails> for ApplePayRegularBillingDetails { fn convert_from(from: ApiApplePayRegularBillingDetails) -> Self { Self { label: from.label, recurring_payment_start_date: from.recurring_payment_start_date, recurring_payment_end_date: from.recurring_payment_end_date, recurring_payment_interval_unit: from .recurring_payment_interval_unit .map(RecurringPaymentIntervalUnit::convert_from), recurring_payment_interval_count: from.recurring_payment_interval_count, } } fn convert_back(self) -> ApiApplePayRegularBillingDetails { ApiApplePayRegularBillingDetails { label: self.label, recurring_payment_start_date: self.recurring_payment_start_date, recurring_payment_end_date: self.recurring_payment_end_date, recurring_payment_interval_unit: self .recurring_payment_interval_unit .map(|value| value.convert_back()), recurring_payment_interval_count: self.recurring_payment_interval_count, } } } impl ApiModelToDieselModelConvertor<ApiApplePayRecurringDetails> for ApplePayRecurringDetails { fn convert_from(from: ApiApplePayRecurringDetails) -> Self { Self { payment_description: from.payment_description, regular_billing: ApplePayRegularBillingDetails::convert_from(from.regular_billing), billing_agreement: from.billing_agreement, management_url: from.management_url, } } fn convert_back(self) -> ApiApplePayRecurringDetails { ApiApplePayRecurringDetails { payment_description: self.payment_description, regular_billing: self.regular_billing.convert_back(), billing_agreement: self.billing_agreement, management_url: self.management_url, } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<ApiBillingConnectorAdditionalCardInfo> for BillingConnectorAdditionalCardInfo { fn convert_from(from: ApiBillingConnectorAdditionalCardInfo) -> Self { Self { card_issuer: from.card_issuer, card_network: from.card_network, } } fn convert_back(self) -> ApiBillingConnectorAdditionalCardInfo { ApiBillingConnectorAdditionalCardInfo { card_issuer: self.card_issuer, card_network: self.card_network, } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<ApiBillingConnectorPaymentMethodDetails> for BillingConnectorPaymentMethodDetails { fn convert_from(from: ApiBillingConnectorPaymentMethodDetails) -> Self { match from { ApiBillingConnectorPaymentMethodDetails::Card(data) => { Self::Card(BillingConnectorAdditionalCardInfo::convert_from(data)) } } } fn convert_back(self) -> ApiBillingConnectorPaymentMethodDetails { match self { Self::Card(data) => ApiBillingConnectorPaymentMethodDetails::Card(data.convert_back()), } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentRevenueRecoveryMetadata { fn convert_from(from: ApiRevenueRecoveryMetadata) -> Self { Self { total_retry_count: from.total_retry_count, payment_connector_transmission: from.payment_connector_transmission.unwrap_or_default(), billing_connector_id: from.billing_connector_id, active_attempt_payment_connector_id: from.active_attempt_payment_connector_id, billing_connector_payment_details: BillingConnectorPaymentDetails::convert_from( from.billing_connector_payment_details, ), payment_method_type: from.payment_method_type, payment_method_subtype: from.payment_method_subtype, connector: from.connector, invoice_next_billing_time: from.invoice_next_billing_time, billing_connector_payment_method_details: from .billing_connector_payment_method_details .map(BillingConnectorPaymentMethodDetails::convert_from), first_payment_attempt_network_advice_code: from .first_payment_attempt_network_advice_code, first_payment_attempt_network_decline_code: from .first_payment_attempt_network_decline_code, first_payment_attempt_pg_error_code: from.first_payment_attempt_pg_error_code, invoice_billing_started_at_time: from.invoice_billing_started_at_time, } } fn convert_back(self) -> ApiRevenueRecoveryMetadata { ApiRevenueRecoveryMetadata { total_retry_count: self.total_retry_count, payment_connector_transmission: Some(self.payment_connector_transmission), billing_connector_id: self.billing_connector_id, active_attempt_payment_connector_id: self.active_attempt_payment_connector_id, billing_connector_payment_details: self .billing_connector_payment_details .convert_back(), payment_method_type: self.payment_method_type, payment_method_subtype: self.payment_method_subtype, connector: self.connector, invoice_next_billing_time: self.invoice_next_billing_time, billing_connector_payment_method_details: self .billing_connector_payment_method_details .map(|data| data.convert_back()), first_payment_attempt_network_advice_code: self .first_payment_attempt_network_advice_code, first_payment_attempt_network_decline_code: self .first_payment_attempt_network_decline_code, first_payment_attempt_pg_error_code: self.first_payment_attempt_pg_error_code, invoice_billing_started_at_time: self.invoice_billing_started_at_time, } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<ApiBillingConnectorPaymentDetails> for BillingConnectorPaymentDetails { fn convert_from(from: ApiBillingConnectorPaymentDetails) -> Self { Self { payment_processor_token: from.payment_processor_token, connector_customer_id: from.connector_customer_id, } } fn convert_back(self) -> ApiBillingConnectorPaymentDetails { ApiBillingConnectorPaymentDetails { payment_processor_token: self.payment_processor_token, connector_customer_id: self.connector_customer_id, } } } impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsWithAmount { fn convert_from(from: ApiOrderDetailsWithAmount) -> Self { let ApiOrderDetailsWithAmount { product_name, quantity, amount, requires_shipping, product_img_link, product_id, category, sub_category, brand, product_type, product_tax_code, tax_rate, total_tax_amount, description, sku, upc, commodity_code, unit_of_measure, total_amount, unit_discount_amount, } = from; Self { product_name, quantity, amount, requires_shipping, product_img_link, product_id, category, sub_category, brand, product_type, product_tax_code, tax_rate, total_tax_amount, description, sku, upc, commodity_code, unit_of_measure, total_amount, unit_discount_amount, } } fn convert_back(self) -> ApiOrderDetailsWithAmount { let Self { product_name, quantity, amount, requires_shipping, product_img_link, product_id, category, sub_category, brand, product_type, product_tax_code, tax_rate, total_tax_amount, description, sku, upc, commodity_code, unit_of_measure, total_amount, unit_discount_amount, } = self; ApiOrderDetailsWithAmount { product_name, quantity, amount, requires_shipping, product_img_link, product_id, category, sub_category, brand, product_type, product_tax_code, tax_rate, total_tax_amount, description, sku, upc, commodity_code, unit_of_measure, total_amount, unit_discount_amount, } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> for diesel_models::payment_intent::PaymentLinkConfigRequestForPayments { fn convert_from(item: api_models::admin::PaymentLinkConfigRequest) -> Self { Self { theme: item.theme, logo: item.logo, seller_name: item.seller_name, sdk_layout: item.sdk_layout, display_sdk_only: item.display_sdk_only, enabled_saved_payment_method: item.enabled_saved_payment_method, hide_card_nickname_field: item.hide_card_nickname_field, show_card_form_by_default: item.show_card_form_by_default, details_layout: item.details_layout, transaction_details: item.transaction_details.map(|transaction_details| { transaction_details .into_iter() .map(|transaction_detail| { diesel_models::PaymentLinkTransactionDetails::convert_from( transaction_detail, ) }) .collect() }), background_image: item.background_image.map(|background_image| { diesel_models::business_profile::PaymentLinkBackgroundImageConfig::convert_from( background_image, ) }), payment_button_text: item.payment_button_text, custom_message_for_card_terms: item.custom_message_for_card_terms, payment_button_colour: item.payment_button_colour, skip_status_screen: item.skip_status_screen, background_colour: item.background_colour, payment_button_text_colour: item.payment_button_text_colour, sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, payment_form_header_text: item.payment_form_header_text, payment_form_label_type: item.payment_form_label_type, show_card_terms: item.show_card_terms, is_setup_mandate_flow: item.is_setup_mandate_flow, color_icon_card_cvc_error: item.color_icon_card_cvc_error, } } fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest { let Self { theme, logo, seller_name, sdk_layout, display_sdk_only, enabled_saved_payment_method, hide_card_nickname_field, show_card_form_by_default, transaction_details, background_image, details_layout, payment_button_text, custom_message_for_card_terms, payment_button_colour, skip_status_screen, background_colour, payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, payment_form_header_text, payment_form_label_type, show_card_terms, is_setup_mandate_flow, color_icon_card_cvc_error, } = self; api_models::admin::PaymentLinkConfigRequest { theme, logo, seller_name, sdk_layout, display_sdk_only, enabled_saved_payment_method, hide_card_nickname_field, show_card_form_by_default, details_layout, transaction_details: transaction_details.map(|transaction_details| { transaction_details .into_iter() .map(|transaction_detail| transaction_detail.convert_back()) .collect() }), background_image: background_image .map(|background_image| background_image.convert_back()), payment_button_text, custom_message_for_card_terms, payment_button_colour, skip_status_screen, background_colour, payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, payment_form_header_text, payment_form_label_type, show_card_terms, is_setup_mandate_flow, color_icon_card_cvc_error, } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkTransactionDetails> for diesel_models::PaymentLinkTransactionDetails { fn convert_from(from: api_models::admin::PaymentLinkTransactionDetails) -> Self { Self { key: from.key, value: from.value, ui_configuration: from .ui_configuration .map(diesel_models::TransactionDetailsUiConfiguration::convert_from), } } fn convert_back(self) -> api_models::admin::PaymentLinkTransactionDetails { let Self { key, value, ui_configuration, } = self; api_models::admin::PaymentLinkTransactionDetails { key, value, ui_configuration: ui_configuration .map(|ui_configuration| ui_configuration.convert_back()), } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkBackgroundImageConfig> for diesel_models::business_profile::PaymentLinkBackgroundImageConfig { fn convert_from(from: api_models::admin::PaymentLinkBackgroundImageConfig) -> Self { Self { url: from.url, position: from.position, size: from.size, } } fn convert_back(self) -> api_models::admin::PaymentLinkBackgroundImageConfig { let Self { url, position, size, } = self; api_models::admin::PaymentLinkBackgroundImageConfig { url, position, size, } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<api_models::admin::TransactionDetailsUiConfiguration> for diesel_models::TransactionDetailsUiConfiguration { fn convert_from(from: api_models::admin::TransactionDetailsUiConfiguration) -> Self { Self { position: from.position, is_key_bold: from.is_key_bold, is_value_bold: from.is_value_bold, } } fn convert_back(self) -> api_models::admin::TransactionDetailsUiConfiguration { let Self { position, is_key_bold, is_value_bold, } = self; api_models::admin::TransactionDetailsUiConfiguration { position, is_key_bold, is_value_bold, } } } #[cfg(feature = "v2")] impl From<api_models::payments::AmountDetails> for payments::AmountDetails { fn from(amount_details: api_models::payments::AmountDetails) -> Self { Self { order_amount: amount_details.order_amount().into(), currency: amount_details.currency(), shipping_cost: amount_details.shipping_cost(), tax_details: amount_details.order_tax_amount().map(|order_tax_amount| { diesel_models::TaxDetails { default: Some(diesel_models::DefaultTax { order_tax_amount }), payment_method_type: None, } }), skip_external_tax_calculation: amount_details.skip_external_tax_calculation(), skip_surcharge_calculation: amount_details.skip_surcharge_calculation(), surcharge_amount: amount_details.surcharge_amount(), tax_on_surcharge: amount_details.tax_on_surcharge(), // We will not receive this in the request. This will be populated after calling the connector / processor amount_captured: None, } } } #[cfg(feature = "v2")] impl From<payments::AmountDetails> for api_models::payments::AmountDetailsSetter { fn from(amount_details: payments::AmountDetails) -> Self { Self { order_amount: amount_details.order_amount.into(), currency: amount_details.currency, shipping_cost: amount_details.shipping_cost, order_tax_amount: amount_details .tax_details .and_then(|tax_detail| tax_detail.get_default_tax_amount()), skip_external_tax_calculation: amount_details.skip_external_tax_calculation, skip_surcharge_calculation: amount_details.skip_surcharge_calculation, surcharge_amount: amount_details.surcharge_amount, tax_on_surcharge: amount_details.tax_on_surcharge, } } } #[cfg(feature = "v2")] impl From<&api_models::payments::PaymentAttemptAmountDetails> for payments::payment_attempt::AttemptAmountDetailsSetter { fn from(amount: &api_models::payments::PaymentAttemptAmountDetails) -> Self { Self { net_amount: amount.net_amount, amount_to_capture: amount.amount_to_capture, surcharge_amount: amount.surcharge_amount, tax_on_surcharge: amount.tax_on_surcharge, amount_capturable: amount.amount_capturable, shipping_cost: amount.shipping_cost, order_tax_amount: amount.order_tax_amount, } } } #[cfg(feature = "v2")] impl From<&payments::payment_attempt::AttemptAmountDetailsSetter> for api_models::payments::PaymentAttemptAmountDetails { fn from(amount: &payments::payment_attempt::AttemptAmountDetailsSetter) -> Self { Self { net_amount: amount.net_amount, amount_to_capture: amount.amount_to_capture, surcharge_amount: amount.surcharge_amount, tax_on_surcharge: amount.tax_on_surcharge, amount_capturable: amount.amount_capturable, shipping_cost: amount.shipping_cost, order_tax_amount: amount.order_tax_amount, } } } #[cfg(feature = "v2")] impl From<&api_models::payments::RecordAttemptErrorDetails> for payments::payment_attempt::ErrorDetails { fn from(error: &api_models::payments::RecordAttemptErrorDetails) -> Self { Self { code: error.code.clone(), message: error.message.clone(), reason: Some(error.message.clone()), unified_code: None, unified_message: None, network_advice_code: error.network_advice_code.clone(), network_decline_code: error.network_decline_code.clone(), network_error_message: error.network_error_message.clone(), } } }
crates/hyperswitch_domain_models/src/lib.rs
hyperswitch_domain_models::src::lib
5,232
true
// File: crates/hyperswitch_domain_models/src/connector_endpoints.rs // Module: hyperswitch_domain_models::src::connector_endpoints //! Configs interface use common_enums::{connector_enums, ApplicationError}; use common_utils::errors::CustomResult; use masking::Secret; use router_derive; use serde::Deserialize; use crate::errors::api_error_response; // 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 authipay: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub affirm: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub archipel: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub barclaycard: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub blackhawknetwork: ConnectorParams, pub calida: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub breadpay: ConnectorParams, pub cashtocode: ConnectorParams, pub celero: ConnectorParams, pub chargebee: ConnectorParams, pub checkbook: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub custombilling: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub dwolla: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub finix: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub flexiti: ConnectorParams, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub gigadat: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub hyperswitch_vault: ConnectorParams, pub hyperwallet: ConnectorParams, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub cardinal: NoParams, pub katapult: ConnectorParams, pub klarna: ConnectorParams, pub loonio: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub mpgs: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub nordea: ConnectorParams, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payload: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paysafe: ConnectorParams, pub paystack: ConnectorParams, pub paytm: ConnectorParams, pub payu: ConnectorParams, pub peachpayments: ConnectorParams, pub phonepe: 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 santander: ConnectorParams, pub shift4: ConnectorParams, pub sift: ConnectorParams, pub silverflow: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub tesouro: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub tokenex: ConnectorParams, pub tokenio: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub trustpayments: ConnectorParams, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub vgs: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub worldpayvantiv: ConnectorParamsWithThreeUrls, pub worldpayxml: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } impl Connectors { pub fn get_connector_params( &self, connector: connector_enums::Connector, ) -> CustomResult<ConnectorParams, api_error_response::ApiErrorResponse> { match connector { connector_enums::Connector::Recurly => Ok(self.recurly.clone()), connector_enums::Connector::Stripebilling => Ok(self.stripebilling.clone()), connector_enums::Connector::Chargebee => Ok(self.chargebee.clone()), _ => Err(api_error_response::ApiErrorResponse::IncorrectConnectorNameGiven.into()), } } } /// 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, }
crates/hyperswitch_domain_models/src/connector_endpoints.rs
hyperswitch_domain_models::src::connector_endpoints
2,082
true
// File: crates/hyperswitch_domain_models/src/router_flow_types.rs // Module: hyperswitch_domain_models::src::router_flow_types pub mod access_token_auth; pub mod authentication; pub mod dispute; pub mod files; pub mod fraud_check; pub mod mandate_revoke; pub mod payments; pub mod payouts; pub mod refunds; pub mod revenue_recovery; pub mod subscriptions; pub mod unified_authentication_service; pub mod vault; pub mod webhooks; pub use access_token_auth::*; pub use dispute::*; pub use files::*; pub use fraud_check::*; pub use payments::*; pub use payouts::*; pub use refunds::*; pub use revenue_recovery::*; pub use subscriptions::*; pub use unified_authentication_service::*; pub use vault::*; pub use webhooks::*;
crates/hyperswitch_domain_models/src/router_flow_types.rs
hyperswitch_domain_models::src::router_flow_types
150
true
// File: crates/hyperswitch_domain_models/src/network_tokenization.rs // Module: hyperswitch_domain_models::src::network_tokenization #[cfg(feature = "v1")] use cards::CardNumber; #[cfg(feature = "v2")] use cards::NetworkToken; #[cfg(feature = "v1")] pub type NetworkTokenNumber = CardNumber; #[cfg(feature = "v2")] pub type NetworkTokenNumber = NetworkToken;
crates/hyperswitch_domain_models/src/network_tokenization.rs
hyperswitch_domain_models::src::network_tokenization
92
true
// File: crates/hyperswitch_domain_models/src/disputes.rs // Module: hyperswitch_domain_models::src::disputes use crate::errors; pub struct DisputeListConstraints { pub dispute_id: Option<String>, pub payment_id: Option<common_utils::id_type::PaymentId>, pub limit: Option<u32>, pub offset: Option<u32>, pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>, pub dispute_status: Option<Vec<common_enums::DisputeStatus>>, pub dispute_stage: Option<Vec<common_enums::DisputeStage>>, pub reason: Option<String>, pub connector: Option<Vec<String>>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub currency: Option<Vec<common_enums::Currency>>, pub time_range: Option<common_utils::types::TimeRange>, } impl TryFrom<( api_models::disputes::DisputeListGetConstraints, Option<Vec<common_utils::id_type::ProfileId>>, )> for DisputeListConstraints { type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>; fn try_from( (value, auth_profile_id_list): ( api_models::disputes::DisputeListGetConstraints, Option<Vec<common_utils::id_type::ProfileId>>, ), ) -> Result<Self, Self::Error> { let api_models::disputes::DisputeListGetConstraints { dispute_id, payment_id, limit, offset, profile_id, dispute_status, dispute_stage, reason, connector, merchant_connector_id, currency, time_range, } = value; let profile_id_from_request_body = profile_id; // Match both the profile ID from the request body and the list of authenticated profile IDs coming from auth layer let profile_id_list = match (profile_id_from_request_body, auth_profile_id_list) { (None, None) => None, // Case when the request body profile ID is None, but authenticated profile IDs are available, return the auth list (None, Some(auth_profile_id_list)) => Some(auth_profile_id_list), // Case when the request body profile ID is provided, but the auth list is None, create a vector with the request body profile ID (Some(profile_id_from_request_body), None) => Some(vec![profile_id_from_request_body]), (Some(profile_id_from_request_body), Some(auth_profile_id_list)) => { // Check if the profile ID from the request body is present in the authenticated profile ID list let profile_id_from_request_body_is_available_in_auth_profile_id_list = auth_profile_id_list.contains(&profile_id_from_request_body); if profile_id_from_request_body_is_available_in_auth_profile_id_list { Some(vec![profile_id_from_request_body]) } else { // If the profile ID is not valid, return an error indicating access is not available return Err(error_stack::Report::new( errors::api_error_response::ApiErrorResponse::PreconditionFailed { message: format!( "Access not available for the given profile_id {profile_id_from_request_body:?}", ), }, )); } } }; Ok(Self { dispute_id, payment_id, limit, offset, profile_id: profile_id_list, dispute_status, dispute_stage, reason, connector, merchant_connector_id, currency, time_range, }) } }
crates/hyperswitch_domain_models/src/disputes.rs
hyperswitch_domain_models::src::disputes
760
true
// File: crates/hyperswitch_domain_models/src/subscription.rs // Module: hyperswitch_domain_models::src::subscription use common_utils::{ errors::{CustomResult, ValidationError}, events::ApiEventMetric, generate_id_with_default_len, pii::SecretSerdeValue, types::keymanager::{self, KeyManagerState}, }; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; use time::PrimitiveDateTime; use crate::{errors::api_error_response::ApiErrorResponse, merchant_key_store::MerchantKeyStore}; const SECRET_SPLIT: &str = "_secret"; #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct ClientSecret(String); impl ClientSecret { pub fn new(secret: String) -> Self { Self(secret) } pub fn get_subscription_id(&self) -> error_stack::Result<String, ApiErrorResponse> { let sub_id = self .0 .split(SECRET_SPLIT) .next() .ok_or(ApiErrorResponse::MissingRequiredField { field_name: "client_secret", }) .attach_printable("Failed to extract subscription_id from client_secret")?; Ok(sub_id.to_string()) } } impl std::fmt::Display for ClientSecret { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl ApiEventMetric for ClientSecret {} impl From<api_models::subscription::ClientSecret> for ClientSecret { fn from(api_secret: api_models::subscription::ClientSecret) -> Self { Self::new(api_secret.as_str().to_string()) } } impl From<ClientSecret> for api_models::subscription::ClientSecret { fn from(domain_secret: ClientSecret) -> Self { Self::new(domain_secret.to_string()) } } #[derive(Clone, Debug, serde::Serialize)] pub struct Subscription { pub id: common_utils::id_type::SubscriptionId, pub status: String, pub billing_processor: Option<String>, pub payment_method_id: Option<String>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub client_secret: Option<String>, pub connector_subscription_id: Option<String>, pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: common_utils::id_type::CustomerId, pub metadata: Option<SecretSerdeValue>, pub created_at: PrimitiveDateTime, pub modified_at: PrimitiveDateTime, pub profile_id: common_utils::id_type::ProfileId, pub merchant_reference_id: Option<String>, pub plan_id: Option<String>, pub item_price_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize)] pub enum SubscriptionStatus { Active, Created, InActive, Pending, Trial, Paused, Unpaid, Onetime, Cancelled, Failed, } impl std::fmt::Display for SubscriptionStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Active => write!(f, "Active"), Self::Created => write!(f, "Created"), Self::InActive => write!(f, "InActive"), Self::Pending => write!(f, "Pending"), Self::Trial => write!(f, "Trial"), Self::Paused => write!(f, "Paused"), Self::Unpaid => write!(f, "Unpaid"), Self::Onetime => write!(f, "Onetime"), Self::Cancelled => write!(f, "Cancelled"), Self::Failed => write!(f, "Failed"), } } } impl Subscription { pub fn generate_and_set_client_secret(&mut self) -> Secret<String> { let client_secret = generate_id_with_default_len(&format!("{}_secret", self.id.get_string_repr())); self.client_secret = Some(client_secret.clone()); Secret::new(client_secret) } } #[async_trait::async_trait] impl super::behaviour::Conversion for Subscription { type DstType = diesel_models::subscription::Subscription; type NewDstType = diesel_models::subscription::SubscriptionNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let now = common_utils::date_time::now(); Ok(diesel_models::subscription::Subscription { id: self.id, status: self.status, billing_processor: self.billing_processor, payment_method_id: self.payment_method_id, merchant_connector_id: self.merchant_connector_id, client_secret: self.client_secret, connector_subscription_id: self.connector_subscription_id, merchant_id: self.merchant_id, customer_id: self.customer_id, metadata: self.metadata.map(|m| m.expose()), created_at: now, modified_at: now, profile_id: self.profile_id, merchant_reference_id: self.merchant_reference_id, plan_id: self.plan_id, item_price_id: self.item_price_id, }) } async fn convert_back( _state: &KeyManagerState, item: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { Ok(Self { id: item.id, status: item.status, billing_processor: item.billing_processor, payment_method_id: item.payment_method_id, merchant_connector_id: item.merchant_connector_id, client_secret: item.client_secret, connector_subscription_id: item.connector_subscription_id, merchant_id: item.merchant_id, customer_id: item.customer_id, metadata: item.metadata.map(SecretSerdeValue::new), created_at: item.created_at, modified_at: item.modified_at, profile_id: item.profile_id, merchant_reference_id: item.merchant_reference_id, plan_id: item.plan_id, item_price_id: item.item_price_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::subscription::SubscriptionNew::new( self.id, self.status, self.billing_processor, self.payment_method_id, self.merchant_connector_id, self.client_secret, self.connector_subscription_id, self.merchant_id, self.customer_id, self.metadata, self.profile_id, self.merchant_reference_id, self.plan_id, self.item_price_id, )) } } #[async_trait::async_trait] pub trait SubscriptionInterface { type Error; async fn insert_subscription_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_new: Subscription, ) -> CustomResult<Subscription, Self::Error>; async fn find_by_merchant_id_subscription_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, ) -> CustomResult<Subscription, Self::Error>; async fn update_subscription_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, data: SubscriptionUpdate, ) -> CustomResult<Subscription, Self::Error>; } pub struct SubscriptionUpdate { pub connector_subscription_id: Option<String>, pub payment_method_id: Option<String>, pub status: Option<String>, pub modified_at: PrimitiveDateTime, pub plan_id: Option<String>, pub item_price_id: Option<String>, } impl SubscriptionUpdate { pub fn new( connector_subscription_id: Option<String>, payment_method_id: Option<Secret<String>>, status: Option<String>, plan_id: Option<String>, item_price_id: Option<String>, ) -> Self { Self { connector_subscription_id, payment_method_id: payment_method_id.map(|pmid| pmid.peek().clone()), status, modified_at: common_utils::date_time::now(), plan_id, item_price_id, } } } #[async_trait::async_trait] impl super::behaviour::Conversion for SubscriptionUpdate { type DstType = diesel_models::subscription::SubscriptionUpdate; type NewDstType = diesel_models::subscription::SubscriptionUpdate; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::subscription::SubscriptionUpdate { connector_subscription_id: self.connector_subscription_id, payment_method_id: self.payment_method_id, status: self.status, modified_at: self.modified_at, plan_id: self.plan_id, item_price_id: self.item_price_id, }) } async fn convert_back( _state: &KeyManagerState, item: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { Ok(Self { connector_subscription_id: item.connector_subscription_id, payment_method_id: item.payment_method_id, status: item.status, modified_at: item.modified_at, plan_id: item.plan_id, item_price_id: item.item_price_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::subscription::SubscriptionUpdate { connector_subscription_id: self.connector_subscription_id, payment_method_id: self.payment_method_id, status: self.status, modified_at: self.modified_at, plan_id: self.plan_id, item_price_id: self.item_price_id, }) } }
crates/hyperswitch_domain_models/src/subscription.rs
hyperswitch_domain_models::src::subscription
2,116
true
// File: crates/hyperswitch_domain_models/src/address.rs // Module: hyperswitch_domain_models::src::address use masking::{PeekInterface, Secret}; #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct Address { pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, pub email: Option<common_utils::pii::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 .as_ref() .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self .email .clone() .or(other.and_then(|other| other.email.clone())), phone: { self.phone .clone() .and_then(|phone_details| { if phone_details.number.is_some() { Some(phone_details) } else { None } }) .or_else(|| other.and_then(|other| other.phone.clone())) }, } } } #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq)] pub struct AddressDetails { pub city: Option<String>, pub country: Option<common_enums::CountryAlpha2>, pub line1: Option<Secret<String>>, pub line2: Option<Secret<String>>, pub line3: Option<Secret<String>>, pub zip: Option<Secret<String>>, pub state: Option<Secret<String>>, pub first_name: Option<Secret<String>>, pub last_name: Option<Secret<String>>, pub origin_zip: 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, } } /// Unify the address details, giving priority to `self` when details are present in both 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.peek().trim().is_empty()) { (self.first_name.clone(), self.last_name.clone()) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.clone().or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.clone().or(other.line1.clone()), line2: self.line2.clone().or(other.line2.clone()), line3: self.line3.clone().or(other.line3.clone()), zip: self.zip.clone().or(other.zip.clone()), state: self.state.clone().or(other.state.clone()), origin_zip: self.origin_zip.clone().or(other.origin_zip.clone()), } } else { self.clone() } } } #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { pub number: Option<Secret<String>>, pub country_code: Option<String>, } impl From<api_models::payments::Address> for Address { fn from(address: api_models::payments::Address) -> Self { Self { address: address.address.map(AddressDetails::from), phone: address.phone.map(PhoneDetails::from), email: address.email, } } } impl From<api_models::payments::AddressDetails> for AddressDetails { fn from(address: api_models::payments::AddressDetails) -> Self { Self { city: address.city, country: address.country, line1: address.line1, line2: address.line2, line3: address.line3, zip: address.zip, state: address.state, first_name: address.first_name, last_name: address.last_name, origin_zip: address.origin_zip, } } } impl From<api_models::payments::PhoneDetails> for PhoneDetails { fn from(phone: api_models::payments::PhoneDetails) -> Self { Self { number: phone.number, country_code: phone.country_code, } } } impl From<Address> for api_models::payments::Address { fn from(address: Address) -> Self { Self { address: address .address .map(api_models::payments::AddressDetails::from), phone: address.phone.map(api_models::payments::PhoneDetails::from), email: address.email, } } } impl From<AddressDetails> for api_models::payments::AddressDetails { fn from(address: AddressDetails) -> Self { Self { city: address.city, country: address.country, line1: address.line1, line2: address.line2, line3: address.line3, zip: address.zip, state: address.state, first_name: address.first_name, last_name: address.last_name, origin_zip: address.origin_zip, } } } impl From<PhoneDetails> for api_models::payments::PhoneDetails { fn from(phone: PhoneDetails) -> Self { Self { number: phone.number, country_code: phone.country_code, } } }
crates/hyperswitch_domain_models/src/address.rs
hyperswitch_domain_models::src::address
1,268
true
// File: crates/hyperswitch_domain_models/src/bulk_tokenization.rs // Module: hyperswitch_domain_models::src::bulk_tokenization use api_models::{payment_methods as payment_methods_api, payments as payments_api}; use cards::CardNumber; use common_enums as enums; use common_utils::{ errors, ext_traits::OptionExt, id_type, pii, transformers::{ForeignFrom, ForeignTryFrom}, }; use error_stack::report; use crate::{ address::{Address, AddressDetails, PhoneDetails}, router_request_types::CustomerDetails, }; #[derive(Debug)] pub struct CardNetworkTokenizeRequest { pub data: TokenizeDataRequest, pub customer: CustomerDetails, pub billing: Option<Address>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_issuer: Option<String>, } #[derive(Debug)] pub enum TokenizeDataRequest { Card(TokenizeCardRequest), ExistingPaymentMethod(TokenizePaymentMethodRequest), } #[derive(Clone, Debug)] pub struct TokenizeCardRequest { pub raw_card_number: CardNumber, pub card_expiry_month: masking::Secret<String>, pub card_expiry_year: masking::Secret<String>, pub card_cvc: Option<masking::Secret<String>>, pub card_holder_name: Option<masking::Secret<String>>, pub nick_name: Option<masking::Secret<String>>, pub card_issuing_country: Option<String>, pub card_network: Option<enums::CardNetwork>, pub card_issuer: Option<String>, pub card_type: Option<payment_methods_api::CardType>, } #[derive(Clone, Debug)] pub struct TokenizePaymentMethodRequest { pub payment_method_id: String, pub card_cvc: Option<masking::Secret<String>>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct CardNetworkTokenizeRecord { // Card details pub raw_card_number: Option<CardNumber>, pub card_expiry_month: Option<masking::Secret<String>>, pub card_expiry_year: Option<masking::Secret<String>>, pub card_cvc: Option<masking::Secret<String>>, pub card_holder_name: Option<masking::Secret<String>>, pub nick_name: Option<masking::Secret<String>>, pub card_issuing_country: Option<String>, pub card_network: Option<enums::CardNetwork>, pub card_issuer: Option<String>, pub card_type: Option<payment_methods_api::CardType>, // Payment method details pub payment_method_id: Option<String>, pub payment_method_type: Option<payment_methods_api::CardType>, pub payment_method_issuer: Option<String>, // Customer details pub customer_id: id_type::CustomerId, #[serde(rename = "name")] pub customer_name: Option<masking::Secret<String>>, #[serde(rename = "email")] pub customer_email: Option<pii::Email>, #[serde(rename = "phone")] pub customer_phone: Option<masking::Secret<String>>, #[serde(rename = "phone_country_code")] pub customer_phone_country_code: Option<String>, #[serde(rename = "tax_registration_id")] pub customer_tax_registration_id: Option<masking::Secret<String>>, // Billing details pub billing_address_city: Option<String>, pub billing_address_country: Option<enums::CountryAlpha2>, pub billing_address_line1: Option<masking::Secret<String>>, pub billing_address_line2: Option<masking::Secret<String>>, pub billing_address_line3: Option<masking::Secret<String>>, pub billing_address_zip: Option<masking::Secret<String>>, pub billing_address_state: Option<masking::Secret<String>>, pub billing_address_first_name: Option<masking::Secret<String>>, pub billing_address_last_name: Option<masking::Secret<String>>, pub billing_phone_number: Option<masking::Secret<String>>, pub billing_phone_country_code: Option<String>, pub billing_email: Option<pii::Email>, // Other details pub line_number: Option<u64>, pub merchant_id: Option<id_type::MerchantId>, } impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::CustomerDetails { fn foreign_from(record: &CardNetworkTokenizeRecord) -> Self { Self { id: record.customer_id.clone(), name: record.customer_name.clone(), email: record.customer_email.clone(), phone: record.customer_phone.clone(), phone_country_code: record.customer_phone_country_code.clone(), tax_registration_id: record.customer_tax_registration_id.clone(), } } } impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::Address { fn foreign_from(record: &CardNetworkTokenizeRecord) -> Self { Self { address: Some(payments_api::AddressDetails { first_name: record.billing_address_first_name.clone(), last_name: record.billing_address_last_name.clone(), line1: record.billing_address_line1.clone(), line2: record.billing_address_line2.clone(), line3: record.billing_address_line3.clone(), city: record.billing_address_city.clone(), zip: record.billing_address_zip.clone(), state: record.billing_address_state.clone(), country: record.billing_address_country, origin_zip: None, }), phone: Some(payments_api::PhoneDetails { number: record.billing_phone_number.clone(), country_code: record.billing_phone_country_code.clone(), }), email: record.billing_email.clone(), } } } impl ForeignTryFrom<CardNetworkTokenizeRecord> for payment_methods_api::CardNetworkTokenizeRequest { type Error = error_stack::Report<errors::ValidationError>; fn foreign_try_from(record: CardNetworkTokenizeRecord) -> Result<Self, Self::Error> { let billing = Some(payments_api::Address::foreign_from(&record)); let customer = payments_api::CustomerDetails::foreign_from(&record); let merchant_id = record.merchant_id.get_required_value("merchant_id")?; match ( record.raw_card_number, record.card_expiry_month, record.card_expiry_year, record.payment_method_id, ) { (Some(raw_card_number), Some(card_expiry_month), Some(card_expiry_year), None) => { Ok(Self { merchant_id, data: payment_methods_api::TokenizeDataRequest::Card( payment_methods_api::TokenizeCardRequest { raw_card_number, card_expiry_month, card_expiry_year, card_cvc: record.card_cvc, card_holder_name: record.card_holder_name, nick_name: record.nick_name, card_issuing_country: record.card_issuing_country, card_network: record.card_network, card_issuer: record.card_issuer, card_type: record.card_type.clone(), }, ), billing, customer, metadata: None, payment_method_issuer: record.payment_method_issuer, }) } (None, None, None, Some(payment_method_id)) => Ok(Self { merchant_id, data: payment_methods_api::TokenizeDataRequest::ExistingPaymentMethod( payment_methods_api::TokenizePaymentMethodRequest { payment_method_id, card_cvc: record.card_cvc, }, ), billing, customer, metadata: None, payment_method_issuer: record.payment_method_issuer, }), _ => Err(report!(errors::ValidationError::InvalidValue { message: "Invalid record in bulk tokenization - expected one of card details or payment method details".to_string() })), } } } impl ForeignFrom<&TokenizeCardRequest> for payment_methods_api::MigrateCardDetail { fn foreign_from(card: &TokenizeCardRequest) -> Self { Self { card_number: masking::Secret::new(card.raw_card_number.get_card_no()), card_exp_month: card.card_expiry_month.clone(), card_exp_year: card.card_expiry_year.clone(), card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), card_issuing_country: card.card_issuing_country.clone(), card_network: card.card_network.clone(), card_issuer: card.card_issuer.clone(), card_type: card .card_type .as_ref() .map(|card_type| card_type.to_string()), } } } impl ForeignTryFrom<CustomerDetails> for payments_api::CustomerDetails { type Error = error_stack::Report<errors::ValidationError>; fn foreign_try_from(customer: CustomerDetails) -> Result<Self, Self::Error> { Ok(Self { id: customer.customer_id.get_required_value("customer_id")?, name: customer.name, email: customer.email, phone: customer.phone, phone_country_code: customer.phone_country_code, tax_registration_id: customer.tax_registration_id, }) } } impl ForeignFrom<payment_methods_api::CardNetworkTokenizeRequest> for CardNetworkTokenizeRequest { fn foreign_from(req: payment_methods_api::CardNetworkTokenizeRequest) -> Self { Self { data: TokenizeDataRequest::foreign_from(req.data), customer: CustomerDetails::foreign_from(req.customer), billing: req.billing.map(ForeignFrom::foreign_from), metadata: req.metadata, payment_method_issuer: req.payment_method_issuer, } } } impl ForeignFrom<payment_methods_api::TokenizeDataRequest> for TokenizeDataRequest { fn foreign_from(req: payment_methods_api::TokenizeDataRequest) -> Self { match req { payment_methods_api::TokenizeDataRequest::Card(card) => { Self::Card(TokenizeCardRequest { raw_card_number: card.raw_card_number, card_expiry_month: card.card_expiry_month, card_expiry_year: card.card_expiry_year, card_cvc: card.card_cvc, card_holder_name: card.card_holder_name, nick_name: card.nick_name, card_issuing_country: card.card_issuing_country, card_network: card.card_network, card_issuer: card.card_issuer, card_type: card.card_type, }) } payment_methods_api::TokenizeDataRequest::ExistingPaymentMethod(pm) => { Self::ExistingPaymentMethod(TokenizePaymentMethodRequest { payment_method_id: pm.payment_method_id, card_cvc: pm.card_cvc, }) } } } } impl ForeignFrom<payments_api::CustomerDetails> for CustomerDetails { fn foreign_from(req: payments_api::CustomerDetails) -> Self { Self { customer_id: Some(req.id), name: req.name, email: req.email, phone: req.phone, phone_country_code: req.phone_country_code, tax_registration_id: req.tax_registration_id, } } } impl ForeignFrom<payments_api::Address> for Address { fn foreign_from(req: payments_api::Address) -> Self { Self { address: req.address.map(ForeignFrom::foreign_from), phone: req.phone.map(ForeignFrom::foreign_from), email: req.email, } } } impl ForeignFrom<payments_api::AddressDetails> for AddressDetails { fn foreign_from(req: payments_api::AddressDetails) -> Self { Self { city: req.city, country: req.country, line1: req.line1, line2: req.line2, line3: req.line3, zip: req.zip, state: req.state, first_name: req.first_name, last_name: req.last_name, origin_zip: req.origin_zip, } } } impl ForeignFrom<payments_api::PhoneDetails> for PhoneDetails { fn foreign_from(req: payments_api::PhoneDetails) -> Self { Self { number: req.number, country_code: req.country_code, } } }
crates/hyperswitch_domain_models/src/bulk_tokenization.rs
hyperswitch_domain_models::src::bulk_tokenization
2,544
true
// File: crates/hyperswitch_domain_models/src/type_encryption.rs // Module: hyperswitch_domain_models::src::type_encryption use async_trait::async_trait; use common_utils::{ crypto, encryption::Encryption, errors::{self, CustomResult}, ext_traits::AsyncExt, metrics::utils::record_operation_time, types::keymanager::{Identifier, KeyManagerState}, }; use encrypt::TypeEncryption; use masking::Secret; use router_env::{instrument, tracing}; use rustc_hash::FxHashMap; mod encrypt { use async_trait::async_trait; use common_utils::{ crypto, encryption::Encryption, errors::{self, CustomResult}, ext_traits::ByteSliceExt, keymanager::call_encryption_service, transformers::{ForeignFrom, ForeignTryFrom}, types::keymanager::{ BatchDecryptDataResponse, BatchEncryptDataRequest, BatchEncryptDataResponse, DecryptDataResponse, EncryptDataRequest, EncryptDataResponse, Identifier, KeyManagerState, TransientBatchDecryptDataRequest, TransientDecryptDataRequest, }, }; use error_stack::ResultExt; use http::Method; use masking::{PeekInterface, Secret}; use router_env::{instrument, logger, tracing}; use rustc_hash::FxHashMap; use super::{metrics, EncryptedJsonType}; #[async_trait] pub trait TypeEncryption< T, V: crypto::EncodeMessage + crypto::DecodeMessage, S: masking::Strategy<T>, >: Sized { async fn encrypt_via_api( state: &KeyManagerState, masked_data: Secret<T, S>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError>; async fn decrypt_via_api( state: &KeyManagerState, encrypted_data: Encryption, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError>; async fn encrypt( masked_data: Secret<T, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError>; async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError>; async fn batch_encrypt_via_api( state: &KeyManagerState, masked_data: FxHashMap<String, Secret<T, S>>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; async fn batch_decrypt_via_api( state: &KeyManagerState, encrypted_data: FxHashMap<String, Encryption>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; async fn batch_encrypt( masked_data: FxHashMap<String, Secret<T, S>>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; async fn batch_decrypt( encrypted_data: FxHashMap<String, Encryption>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; } fn is_encryption_service_enabled(_state: &KeyManagerState) -> bool { #[cfg(feature = "encryption_service")] { _state.enabled } #[cfg(not(feature = "encryption_service"))] { false } } #[async_trait] impl< V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, S: masking::Strategy<String> + Send + Sync, > TypeEncryption<String, V, S> for crypto::Encryptable<Secret<String, S>> { // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt_via_api( state: &KeyManagerState, masked_data: Secret<String, S>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::encrypt(masked_data, key, crypt_algo).await } else { let result: Result< EncryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/encrypt", EncryptDataRequest::from((masked_data.clone(), identifier)), ) .await; match result { Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), Err(err) => { logger::error!("Encryption error {:?}", err); metrics::ENCRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Encryption"); Self::encrypt(masked_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt_via_api( state: &KeyManagerState, encrypted_data: Encryption, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::decrypt(encrypted_data, key, crypt_algo).await } else { let result: Result< DecryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/decrypt", TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), ) .await; let decrypted = match result { Ok(decrypted_data) => { ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) } Err(err) => { logger::error!("Decryption error {:?}", err); Err(err.change_context(errors::CryptoError::DecodingFailed)) } }; match decrypted { Ok(de) => Ok(de), Err(_) => { metrics::DECRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Decryption"); Self::decrypt(encrypted_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt( masked_data: Secret<String, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]); let encrypted_data = crypt_algo.encode_message(key, masked_data.peek().as_bytes())?; Ok(Self::new(masked_data, encrypted_data.into())) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]); let encrypted = encrypted_data.into_inner(); let data = crypt_algo.decode_message(key, encrypted.clone())?; let value: String = std::str::from_utf8(&data) .change_context(errors::CryptoError::DecodingFailed)? .to_string(); Ok(Self::new(value.into(), encrypted)) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt_via_api( state: &KeyManagerState, masked_data: FxHashMap<String, Secret<String, S>>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::batch_encrypt(masked_data, key, crypt_algo).await } else { let result: Result< BatchEncryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/encrypt", BatchEncryptDataRequest::from((masked_data.clone(), identifier)), ) .await; match result { Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), Err(err) => { metrics::ENCRYPTION_API_FAILURES.add(1, &[]); logger::error!("Encryption error {:?}", err); logger::info!("Fall back to Application Encryption"); Self::batch_encrypt(masked_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt_via_api( state: &KeyManagerState, encrypted_data: FxHashMap<String, Encryption>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::batch_decrypt(encrypted_data, key, crypt_algo).await } else { let result: Result< BatchDecryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/decrypt", TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), ) .await; let decrypted = match result { Ok(decrypted_data) => { ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) } Err(err) => { logger::error!("Decryption error {:?}", err); Err(err.change_context(errors::CryptoError::DecodingFailed)) } }; match decrypted { Ok(de) => Ok(de), Err(_) => { metrics::DECRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Decryption"); Self::batch_decrypt(encrypted_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt( masked_data: FxHashMap<String, Secret<String, S>>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]); masked_data .into_iter() .map(|(k, v)| { Ok(( k, Self::new( v.clone(), crypt_algo.encode_message(key, v.peek().as_bytes())?.into(), ), )) }) .collect() } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt( encrypted_data: FxHashMap<String, Encryption>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]); encrypted_data .into_iter() .map(|(k, v)| { let data = crypt_algo.decode_message(key, v.clone().into_inner())?; let value: String = std::str::from_utf8(&data) .change_context(errors::CryptoError::DecodingFailed)? .to_string(); Ok((k, Self::new(value.into(), v.into_inner()))) }) .collect() } } #[async_trait] impl< V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, S: masking::Strategy<serde_json::Value> + Send + Sync, > TypeEncryption<serde_json::Value, V, S> for crypto::Encryptable<Secret<serde_json::Value, S>> { // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt_via_api( state: &KeyManagerState, masked_data: Secret<serde_json::Value, S>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::encrypt(masked_data, key, crypt_algo).await } else { let result: Result< EncryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/encrypt", EncryptDataRequest::from((masked_data.clone(), identifier)), ) .await; match result { Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), Err(err) => { logger::error!("Encryption error {:?}", err); metrics::ENCRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Encryption"); Self::encrypt(masked_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt_via_api( state: &KeyManagerState, encrypted_data: Encryption, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::decrypt(encrypted_data, key, crypt_algo).await } else { let result: Result< DecryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/decrypt", TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), ) .await; let decrypted = match result { Ok(decrypted_data) => { ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) } Err(err) => { logger::error!("Decryption error {:?}", err); Err(err.change_context(errors::CryptoError::EncodingFailed)) } }; match decrypted { Ok(de) => Ok(de), Err(_) => { metrics::DECRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Decryption"); Self::decrypt(encrypted_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt( masked_data: Secret<serde_json::Value, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]); let data = serde_json::to_vec(&masked_data.peek()) .change_context(errors::CryptoError::DecodingFailed)?; let encrypted_data = crypt_algo.encode_message(key, &data)?; Ok(Self::new(masked_data, encrypted_data.into())) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]); let encrypted = encrypted_data.into_inner(); let data = crypt_algo.decode_message(key, encrypted.clone())?; let value: serde_json::Value = serde_json::from_slice(&data) .change_context(errors::CryptoError::DecodingFailed)?; Ok(Self::new(value.into(), encrypted)) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt_via_api( state: &KeyManagerState, masked_data: FxHashMap<String, Secret<serde_json::Value, S>>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::batch_encrypt(masked_data, key, crypt_algo).await } else { let result: Result< BatchEncryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/encrypt", BatchEncryptDataRequest::from((masked_data.clone(), identifier)), ) .await; match result { Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), Err(err) => { metrics::ENCRYPTION_API_FAILURES.add(1, &[]); logger::error!("Encryption error {:?}", err); logger::info!("Fall back to Application Encryption"); Self::batch_encrypt(masked_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt_via_api( state: &KeyManagerState, encrypted_data: FxHashMap<String, Encryption>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::batch_decrypt(encrypted_data, key, crypt_algo).await } else { let result: Result< BatchDecryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/decrypt", TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), ) .await; let decrypted = match result { Ok(decrypted_data) => { ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) } Err(err) => { logger::error!("Decryption error {:?}", err); Err(err.change_context(errors::CryptoError::DecodingFailed)) } }; match decrypted { Ok(de) => Ok(de), Err(_) => { metrics::DECRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Decryption"); Self::batch_decrypt(encrypted_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt( masked_data: FxHashMap<String, Secret<serde_json::Value, S>>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]); masked_data .into_iter() .map(|(k, v)| { let data = serde_json::to_vec(v.peek()) .change_context(errors::CryptoError::DecodingFailed)?; Ok(( k, Self::new(v, crypt_algo.encode_message(key, &data)?.into()), )) }) .collect() } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt( encrypted_data: FxHashMap<String, Encryption>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]); encrypted_data .into_iter() .map(|(k, v)| { let data = crypt_algo.decode_message(key, v.clone().into_inner().clone())?; let value: serde_json::Value = serde_json::from_slice(&data) .change_context(errors::CryptoError::DecodingFailed)?; Ok((k, Self::new(value.into(), v.into_inner()))) }) .collect() } } impl<T> EncryptedJsonType<T> where T: std::fmt::Debug + Clone + serde::Serialize + serde::de::DeserializeOwned, { fn serialize_json_bytes(&self) -> CustomResult<Secret<Vec<u8>>, errors::CryptoError> { common_utils::ext_traits::Encode::encode_to_vec(self.inner()) .change_context(errors::CryptoError::EncodingFailed) .attach_printable("Failed to JSON serialize data before encryption") .map(Secret::new) } fn deserialize_json_bytes<S>( bytes: Secret<Vec<u8>>, ) -> CustomResult<Secret<Self, S>, errors::ParsingError> where S: masking::Strategy<Self>, { bytes .peek() .as_slice() .parse_struct::<T>(std::any::type_name::<T>()) .map(|result| Secret::new(Self::from(result))) .attach_printable("Failed to JSON deserialize data after decryption") } } #[async_trait] impl< T: std::fmt::Debug + Clone + serde::Serialize + serde::de::DeserializeOwned + Send, V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, S: masking::Strategy<EncryptedJsonType<T>> + Send + Sync, > TypeEncryption<EncryptedJsonType<T>, V, S> for crypto::Encryptable<Secret<EncryptedJsonType<T>, S>> { // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt_via_api( state: &KeyManagerState, masked_data: Secret<EncryptedJsonType<T>, S>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { let data_bytes = EncryptedJsonType::serialize_json_bytes(masked_data.peek())?; let result: crypto::Encryptable<Secret<Vec<u8>>> = TypeEncryption::encrypt_via_api(state, data_bytes, identifier, key, crypt_algo) .await?; Ok(Self::new(masked_data, result.into_encrypted())) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt_via_api( state: &KeyManagerState, encrypted_data: Encryption, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { let result: crypto::Encryptable<Secret<Vec<u8>>> = TypeEncryption::decrypt_via_api(state, encrypted_data, identifier, key, crypt_algo) .await?; result .deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes) .change_context(errors::CryptoError::DecodingFailed) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt( masked_data: Secret<EncryptedJsonType<T>, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { let data_bytes = EncryptedJsonType::serialize_json_bytes(masked_data.peek())?; let result: crypto::Encryptable<Secret<Vec<u8>>> = TypeEncryption::encrypt(data_bytes, key, crypt_algo).await?; Ok(Self::new(masked_data, result.into_encrypted())) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { let result: crypto::Encryptable<Secret<Vec<u8>>> = TypeEncryption::decrypt(encrypted_data, key, crypt_algo).await?; result .deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes) .change_context(errors::CryptoError::DecodingFailed) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt_via_api( state: &KeyManagerState, masked_data: FxHashMap<String, Secret<EncryptedJsonType<T>, S>>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { let hashmap_capacity = masked_data.len(); let data_bytes = masked_data.iter().try_fold( FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()), |mut map, (key, value)| { let value_bytes = EncryptedJsonType::serialize_json_bytes(value.peek())?; map.insert(key.to_owned(), value_bytes); Ok::<_, error_stack::Report<errors::CryptoError>>(map) }, )?; let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> = TypeEncryption::batch_encrypt_via_api( state, data_bytes, identifier, key, crypt_algo, ) .await?; let result_hashmap = result.into_iter().try_fold( FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()), |mut map, (key, value)| { let original_value = masked_data .get(&key) .ok_or(errors::CryptoError::EncodingFailed) .attach_printable_lazy(|| { format!("Failed to find {key} in input hashmap") })?; map.insert( key, Self::new(original_value.clone(), value.into_encrypted()), ); Ok::<_, error_stack::Report<errors::CryptoError>>(map) }, )?; Ok(result_hashmap) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt_via_api( state: &KeyManagerState, encrypted_data: FxHashMap<String, Encryption>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> = TypeEncryption::batch_decrypt_via_api( state, encrypted_data, identifier, key, crypt_algo, ) .await?; let hashmap_capacity = result.len(); let result_hashmap = result.into_iter().try_fold( FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()), |mut map, (key, value)| { let deserialized_value = value .deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes) .change_context(errors::CryptoError::DecodingFailed)?; map.insert(key, deserialized_value); Ok::<_, error_stack::Report<errors::CryptoError>>(map) }, )?; Ok(result_hashmap) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt( masked_data: FxHashMap<String, Secret<EncryptedJsonType<T>, S>>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { let hashmap_capacity = masked_data.len(); let data_bytes = masked_data.iter().try_fold( FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()), |mut map, (key, value)| { let value_bytes = EncryptedJsonType::serialize_json_bytes(value.peek())?; map.insert(key.to_owned(), value_bytes); Ok::<_, error_stack::Report<errors::CryptoError>>(map) }, )?; let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> = TypeEncryption::batch_encrypt(data_bytes, key, crypt_algo).await?; let result_hashmap = result.into_iter().try_fold( FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()), |mut map, (key, value)| { let original_value = masked_data .get(&key) .ok_or(errors::CryptoError::EncodingFailed) .attach_printable_lazy(|| { format!("Failed to find {key} in input hashmap") })?; map.insert( key, Self::new(original_value.clone(), value.into_encrypted()), ); Ok::<_, error_stack::Report<errors::CryptoError>>(map) }, )?; Ok(result_hashmap) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt( encrypted_data: FxHashMap<String, Encryption>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> = TypeEncryption::batch_decrypt(encrypted_data, key, crypt_algo).await?; let hashmap_capacity = result.len(); let result_hashmap = result.into_iter().try_fold( FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()), |mut map, (key, value)| { let deserialized_value = value .deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes) .change_context(errors::CryptoError::DecodingFailed)?; map.insert(key, deserialized_value); Ok::<_, error_stack::Report<errors::CryptoError>>(map) }, )?; Ok(result_hashmap) } } #[async_trait] impl< V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, S: masking::Strategy<Vec<u8>> + Send + Sync, > TypeEncryption<Vec<u8>, V, S> for crypto::Encryptable<Secret<Vec<u8>, S>> { // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt_via_api( state: &KeyManagerState, masked_data: Secret<Vec<u8>, S>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::encrypt(masked_data, key, crypt_algo).await } else { let result: Result< EncryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/encrypt", EncryptDataRequest::from((masked_data.clone(), identifier)), ) .await; match result { Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), Err(err) => { logger::error!("Encryption error {:?}", err); metrics::ENCRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Encryption"); Self::encrypt(masked_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt_via_api( state: &KeyManagerState, encrypted_data: Encryption, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::decrypt(encrypted_data, key, crypt_algo).await } else { let result: Result< DecryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/decrypt", TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), ) .await; let decrypted = match result { Ok(decrypted_data) => { ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) } Err(err) => { logger::error!("Decryption error {:?}", err); Err(err.change_context(errors::CryptoError::DecodingFailed)) } }; match decrypted { Ok(de) => Ok(de), Err(_) => { metrics::DECRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Decryption"); Self::decrypt(encrypted_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt( masked_data: Secret<Vec<u8>, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]); let encrypted_data = crypt_algo.encode_message(key, masked_data.peek())?; Ok(Self::new(masked_data, encrypted_data.into())) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]); let encrypted = encrypted_data.into_inner(); let data = crypt_algo.decode_message(key, encrypted.clone())?; Ok(Self::new(data.into(), encrypted)) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt_via_api( state: &KeyManagerState, masked_data: FxHashMap<String, Secret<Vec<u8>, S>>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::batch_encrypt(masked_data, key, crypt_algo).await } else { let result: Result< BatchEncryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/encrypt", BatchEncryptDataRequest::from((masked_data.clone(), identifier)), ) .await; match result { Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), Err(err) => { metrics::ENCRYPTION_API_FAILURES.add(1, &[]); logger::error!("Encryption error {:?}", err); logger::info!("Fall back to Application Encryption"); Self::batch_encrypt(masked_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt_via_api( state: &KeyManagerState, encrypted_data: FxHashMap<String, Encryption>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::batch_decrypt(encrypted_data, key, crypt_algo).await } else { let result: Result< BatchDecryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/decrypt", TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), ) .await; let decrypted = match result { Ok(response) => { ForeignTryFrom::foreign_try_from((encrypted_data.clone(), response)) } Err(err) => { logger::error!("Decryption error {:?}", err); Err(err.change_context(errors::CryptoError::DecodingFailed)) } }; match decrypted { Ok(de) => Ok(de), Err(_) => { metrics::DECRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Decryption"); Self::batch_decrypt(encrypted_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt( masked_data: FxHashMap<String, Secret<Vec<u8>, S>>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]); masked_data .into_iter() .map(|(k, v)| { Ok(( k, Self::new(v.clone(), crypt_algo.encode_message(key, v.peek())?.into()), )) }) .collect() } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt( encrypted_data: FxHashMap<String, Encryption>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]); encrypted_data .into_iter() .map(|(k, v)| { Ok(( k, Self::new( crypt_algo .decode_message(key, v.clone().into_inner().clone())? .into(), v.into_inner(), ), )) }) .collect() } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct EncryptedJsonType<T>(T); impl<T> EncryptedJsonType<T> { pub fn inner(&self) -> &T { &self.0 } pub fn into_inner(self) -> T { self.0 } } impl<T> From<T> for EncryptedJsonType<T> { fn from(value: T) -> Self { Self(value) } } impl<T> std::ops::Deref for EncryptedJsonType<T> { type Target = T; fn deref(&self) -> &Self::Target { self.inner() } } /// Type alias for `Option<Encryptable<Secret<EncryptedJsonType<T>>>>` pub type OptionalEncryptableJsonType<T> = Option<crypto::Encryptable<Secret<EncryptedJsonType<T>>>>; pub trait Lift<U> { type SelfWrapper<T>; type OtherWrapper<T, E>; fn lift<Func, E, V>(self, func: Func) -> Self::OtherWrapper<V, E> where Func: Fn(Self::SelfWrapper<U>) -> Self::OtherWrapper<V, E>; } impl<U> Lift<U> for Option<U> { type SelfWrapper<T> = Option<T>; type OtherWrapper<T, E> = CustomResult<Option<T>, E>; fn lift<Func, E, V>(self, func: Func) -> Self::OtherWrapper<V, E> where Func: Fn(Self::SelfWrapper<U>) -> Self::OtherWrapper<V, E>, { func(self) } } #[async_trait] pub trait AsyncLift<U> { type SelfWrapper<T>; type OtherWrapper<T, E>; async fn async_lift<Func, F, E, V>(self, func: Func) -> Self::OtherWrapper<V, E> where Func: Fn(Self::SelfWrapper<U>) -> F + Send + Sync, F: futures::Future<Output = Self::OtherWrapper<V, E>> + Send; } #[async_trait] impl<U, V: Lift<U> + Lift<U, SelfWrapper<U> = V> + Send> AsyncLift<U> for V { type SelfWrapper<T> = <V as Lift<U>>::SelfWrapper<T>; type OtherWrapper<T, E> = <V as Lift<U>>::OtherWrapper<T, E>; async fn async_lift<Func, F, E, W>(self, func: Func) -> Self::OtherWrapper<W, E> where Func: Fn(Self::SelfWrapper<U>) -> F + Send + Sync, F: futures::Future<Output = Self::OtherWrapper<W, E>> + Send, { func(self).await } } #[inline] async fn encrypt<E: Clone, S>( state: &KeyManagerState, inner: Secret<E, S>, identifier: Identifier, key: &[u8], ) -> CustomResult<crypto::Encryptable<Secret<E, S>>, CryptoError> where S: masking::Strategy<E>, crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { record_operation_time( crypto::Encryptable::encrypt_via_api(state, inner, identifier, key, crypto::GcmAes256), &metrics::ENCRYPTION_TIME, &[], ) .await } #[inline] async fn batch_encrypt<E: Clone, S>( state: &KeyManagerState, inner: FxHashMap<String, Secret<E, S>>, identifier: Identifier, key: &[u8], ) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, CryptoError> where S: masking::Strategy<E>, crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { if !inner.is_empty() { record_operation_time( crypto::Encryptable::batch_encrypt_via_api( state, inner, identifier, key, crypto::GcmAes256, ), &metrics::ENCRYPTION_TIME, &[], ) .await } else { Ok(FxHashMap::default()) } } #[inline] async fn encrypt_optional<E: Clone, S>( state: &KeyManagerState, inner: Option<Secret<E, S>>, identifier: Identifier, key: &[u8], ) -> CustomResult<Option<crypto::Encryptable<Secret<E, S>>>, CryptoError> where Secret<E, S>: Send, S: masking::Strategy<E>, crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { inner .async_map(|f| encrypt(state, f, identifier, key)) .await .transpose() } #[inline] async fn decrypt_optional<T: Clone, S: masking::Strategy<T>>( state: &KeyManagerState, inner: Option<Encryption>, identifier: Identifier, key: &[u8], ) -> CustomResult<Option<crypto::Encryptable<Secret<T, S>>>, CryptoError> where crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>, { inner .async_map(|item| decrypt(state, item, identifier, key)) .await .transpose() } #[inline] async fn decrypt<T: Clone, S: masking::Strategy<T>>( state: &KeyManagerState, inner: Encryption, identifier: Identifier, key: &[u8], ) -> CustomResult<crypto::Encryptable<Secret<T, S>>, CryptoError> where crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>, { record_operation_time( crypto::Encryptable::decrypt_via_api(state, inner, identifier, key, crypto::GcmAes256), &metrics::DECRYPTION_TIME, &[], ) .await } #[inline] async fn batch_decrypt<E: Clone, S>( state: &KeyManagerState, inner: FxHashMap<String, Encryption>, identifier: Identifier, key: &[u8], ) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, CryptoError> where S: masking::Strategy<E>, crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { if !inner.is_empty() { record_operation_time( crypto::Encryptable::batch_decrypt_via_api( state, inner, identifier, key, crypto::GcmAes256, ), &metrics::ENCRYPTION_TIME, &[], ) .await } else { Ok(FxHashMap::default()) } } pub enum CryptoOperation<T: Clone, S: masking::Strategy<T>> { Encrypt(Secret<T, S>), EncryptOptional(Option<Secret<T, S>>), Decrypt(Encryption), DecryptOptional(Option<Encryption>), BatchEncrypt(FxHashMap<String, Secret<T, S>>), BatchDecrypt(FxHashMap<String, Encryption>), } use errors::CryptoError; #[derive(router_derive::TryGetEnumVariant)] #[error(CryptoError::EncodingFailed)] pub enum CryptoOutput<T: Clone, S: masking::Strategy<T>> { Operation(crypto::Encryptable<Secret<T, S>>), OptionalOperation(Option<crypto::Encryptable<Secret<T, S>>>), BatchOperation(FxHashMap<String, crypto::Encryptable<Secret<T, S>>>), } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all, fields(table = table_name))] pub async fn crypto_operation<T: Clone + Send, S: masking::Strategy<T>>( state: &KeyManagerState, table_name: &str, operation: CryptoOperation<T, S>, identifier: Identifier, key: &[u8], ) -> CustomResult<CryptoOutput<T, S>, CryptoError> where Secret<T, S>: Send, crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>, { match operation { CryptoOperation::Encrypt(data) => { let data = encrypt(state, data, identifier, key).await?; Ok(CryptoOutput::Operation(data)) } CryptoOperation::EncryptOptional(data) => { let data = encrypt_optional(state, data, identifier, key).await?; Ok(CryptoOutput::OptionalOperation(data)) } CryptoOperation::Decrypt(data) => { let data = decrypt(state, data, identifier, key).await?; Ok(CryptoOutput::Operation(data)) } CryptoOperation::DecryptOptional(data) => { let data = decrypt_optional(state, data, identifier, key).await?; Ok(CryptoOutput::OptionalOperation(data)) } CryptoOperation::BatchEncrypt(data) => { let data = batch_encrypt(state, data, identifier, key).await?; Ok(CryptoOutput::BatchOperation(data)) } CryptoOperation::BatchDecrypt(data) => { let data = batch_decrypt(state, data, identifier, key).await?; Ok(CryptoOutput::BatchOperation(data)) } } } pub(crate) mod metrics { use router_env::{counter_metric, global_meter, histogram_metric_f64}; global_meter!(GLOBAL_METER, "ROUTER_API"); // Encryption and Decryption metrics histogram_metric_f64!(ENCRYPTION_TIME, GLOBAL_METER); histogram_metric_f64!(DECRYPTION_TIME, GLOBAL_METER); counter_metric!(ENCRYPTION_API_FAILURES, GLOBAL_METER); counter_metric!(DECRYPTION_API_FAILURES, GLOBAL_METER); counter_metric!(APPLICATION_ENCRYPTION_COUNT, GLOBAL_METER); counter_metric!(APPLICATION_DECRYPTION_COUNT, GLOBAL_METER); }
crates/hyperswitch_domain_models/src/type_encryption.rs
hyperswitch_domain_models::src::type_encryption
10,808
true
// File: crates/hyperswitch_domain_models/src/router_data.rs // Module: hyperswitch_domain_models::src::router_data use std::{collections::HashMap, marker::PhantomData}; use common_types::{payments as common_payment_types, primitive_wrappers}; use common_utils::{ errors::IntegrityCheckError, ext_traits::{OptionExt, ValueExt}, id_type::{self}, types::MinorUnit, }; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ address::AddressDetails, network_tokenization::NetworkTokenNumber, payment_address::PaymentAddress, payment_method_data, payments, }; #[cfg(feature = "v2")] use crate::{ payments::{ payment_attempt::{ErrorDetails, PaymentAttemptUpdate}, payment_intent::PaymentIntentUpdate, }, router_flow_types, router_request_types, router_response_types, }; #[derive(Debug, Clone, Serialize)] pub struct RouterData<Flow, Request, Response> { pub flow: PhantomData<Flow>, pub merchant_id: id_type::MerchantId, pub customer_id: Option<id_type::CustomerId>, pub connector_customer: Option<String>, pub connector: String, // TODO: This should be a PaymentId type. // Make this change after all the connector dependency has been removed from connectors pub payment_id: String, pub attempt_id: String, pub tenant_id: id_type::TenantId, pub status: common_enums::enums::AttemptStatus, pub payment_method: common_enums::enums::PaymentMethod, pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, pub connector_auth_type: ConnectorAuthType, pub description: Option<String>, pub address: PaymentAddress, pub auth_type: common_enums::enums::AuthenticationType, pub connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, pub connector_wallets_details: Option<common_utils::pii::SecretSerdeValue>, pub amount_captured: Option<i64>, pub access_token: Option<AccessToken>, pub session_token: Option<String>, pub reference_id: Option<String>, pub payment_method_token: Option<PaymentMethodToken>, pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>, pub preprocessing_id: Option<String>, /// This is the balance amount for gift cards or voucher pub payment_method_balance: Option<PaymentMethodBalance>, ///for switching between two different versions of the same connector pub connector_api_version: Option<String>, /// Contains flow-specific data required to construct a request and send it to the connector. pub request: Request, /// Contains flow-specific data that the connector responds with. pub response: Result<Response, ErrorResponse>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, #[cfg(feature = "payouts")] /// Contains payout method data pub payout_method_data: Option<api_models::payouts::PayoutMethodData>, #[cfg(feature = "payouts")] /// Contains payout's quote ID pub quote_id: Option<String>, pub test_mode: Option<bool>, pub connector_http_status_code: Option<u16>, pub external_latency: Option<u128>, /// Contains apple pay flow type simplified or manual pub apple_pay_flow: Option<payment_method_data::ApplePayFlow>, pub frm_metadata: Option<common_utils::pii::SecretSerdeValue>, pub dispute_id: Option<String>, pub refund_id: Option<String>, /// This field is used to store various data regarding the response from connector pub connector_response: Option<ConnectorResponseData>, pub payment_method_status: Option<common_enums::PaymentMethodStatus>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, pub minor_amount_capturable: Option<MinorUnit>, // stores the authorized amount in case of partial authorization pub authorized_amount: Option<MinorUnit>, pub integrity_check: Result<(), IntegrityCheckError>, pub additional_merchant_data: Option<api_models::admin::AdditionalMerchantData>, pub header_payload: Option<payments::HeaderPayload>, pub connector_mandate_request_reference_id: Option<String>, pub l2_l3_data: Option<Box<L2L3Data>>, pub authentication_id: Option<id_type::AuthenticationId>, /// Contains the type of sca exemption required for the transaction pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, /// Contains stringified connector raw response body pub raw_connector_response: Option<Secret<String>>, /// Indicates whether the payment ID was provided by the merchant (true), /// or generated internally by Hyperswitch (false) pub is_payment_id_from_merchant: Option<bool>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct L2L3Data { pub order_date: Option<time::PrimitiveDateTime>, pub tax_status: Option<common_enums::TaxStatus>, pub customer_tax_registration_id: Option<Secret<String>>, pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>, pub discount_amount: Option<MinorUnit>, pub shipping_cost: Option<MinorUnit>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub merchant_order_reference_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub billing_address_city: Option<String>, pub merchant_tax_registration_id: Option<Secret<String>>, pub customer_email: Option<common_utils::pii::Email>, pub customer_name: Option<Secret<String>>, pub customer_phone_number: Option<Secret<String>>, pub customer_phone_country_code: Option<String>, pub shipping_details: Option<AddressDetails>, } impl L2L3Data { pub fn get_shipping_country(&self) -> Option<common_enums::enums::CountryAlpha2> { self.shipping_details .as_ref() .and_then(|address| address.country) } pub fn get_shipping_city(&self) -> Option<String> { self.shipping_details .as_ref() .and_then(|address| address.city.clone()) } pub fn get_shipping_state(&self) -> Option<Secret<String>> { self.shipping_details .as_ref() .and_then(|address| address.state.clone()) } pub fn get_shipping_origin_zip(&self) -> Option<Secret<String>> { self.shipping_details .as_ref() .and_then(|address| address.origin_zip.clone()) } pub fn get_shipping_zip(&self) -> Option<Secret<String>> { self.shipping_details .as_ref() .and_then(|address| address.zip.clone()) } pub fn get_shipping_address_line1(&self) -> Option<Secret<String>> { self.shipping_details .as_ref() .and_then(|address| address.line1.clone()) } pub fn get_shipping_address_line2(&self) -> Option<Secret<String>> { self.shipping_details .as_ref() .and_then(|address| address.line2.clone()) } } // Different patterns of authentication. #[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(tag = "auth_type")] pub enum ConnectorAuthType { TemporaryAuth, HeaderKey { api_key: Secret<String>, }, BodyKey { api_key: Secret<String>, key1: Secret<String>, }, SignatureKey { api_key: Secret<String>, key1: Secret<String>, api_secret: Secret<String>, }, MultiAuthKey { api_key: Secret<String>, key1: Secret<String>, api_secret: Secret<String>, key2: Secret<String>, }, CurrencyAuthKey { auth_key_map: HashMap<common_enums::enums::Currency, common_utils::pii::SecretSerdeValue>, }, CertificateAuth { certificate: Secret<String>, private_key: Secret<String>, }, #[default] NoKey, } impl ConnectorAuthType { pub fn from_option_secret_value( value: Option<common_utils::pii::SecretSerdeValue>, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorAuthType") .change_context(common_utils::errors::ParsingError::StructParseFailure( "ConnectorAuthType", )) } pub fn from_secret_value( value: common_utils::pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorAuthType") .change_context(common_utils::errors::ParsingError::StructParseFailure( "ConnectorAuthType", )) } // show only first and last two digits of the key and mask others with * // mask the entire key if it's length is less than or equal to 4 fn mask_key(&self, key: String) -> Secret<String> { let key_len = key.len(); let masked_key = if key_len <= 4 { "*".repeat(key_len) } else { // Show the first two and last two characters, mask the rest with '*' let mut masked_key = String::new(); let key_len = key.len(); // Iterate through characters by their index for (index, character) in key.chars().enumerate() { if index < 2 || index >= key_len - 2 { masked_key.push(character); // Keep the first two and last two characters } else { masked_key.push('*'); // Mask the middle characters } } masked_key }; Secret::new(masked_key) } // Mask the keys in the auth_type pub fn get_masked_keys(&self) -> Self { match self { Self::TemporaryAuth => Self::TemporaryAuth, Self::NoKey => Self::NoKey, Self::HeaderKey { api_key } => Self::HeaderKey { api_key: self.mask_key(api_key.clone().expose()), }, Self::BodyKey { api_key, key1 } => Self::BodyKey { api_key: self.mask_key(api_key.clone().expose()), key1: self.mask_key(key1.clone().expose()), }, Self::SignatureKey { api_key, key1, api_secret, } => Self::SignatureKey { api_key: self.mask_key(api_key.clone().expose()), key1: self.mask_key(key1.clone().expose()), api_secret: self.mask_key(api_secret.clone().expose()), }, Self::MultiAuthKey { api_key, key1, api_secret, key2, } => Self::MultiAuthKey { api_key: self.mask_key(api_key.clone().expose()), key1: self.mask_key(key1.clone().expose()), api_secret: self.mask_key(api_secret.clone().expose()), key2: self.mask_key(key2.clone().expose()), }, Self::CurrencyAuthKey { auth_key_map } => Self::CurrencyAuthKey { auth_key_map: auth_key_map.clone(), }, Self::CertificateAuth { certificate, private_key, } => Self::CertificateAuth { certificate: self.mask_key(certificate.clone().expose()), private_key: self.mask_key(private_key.clone().expose()), }, } } } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct AccessTokenAuthenticationResponse { pub code: Secret<String>, pub expires: i64, } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct AccessToken { pub token: Secret<String>, pub expires: i64, } #[derive(Debug, Clone, Deserialize, Serialize)] pub enum PaymentMethodToken { Token(Secret<String>), ApplePayDecrypt(Box<common_payment_types::ApplePayPredecryptData>), GooglePayDecrypt(Box<common_payment_types::GPayPredecryptData>), PazeDecrypt(Box<PazeDecryptedData>), } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayPredecryptDataInternal { pub application_primary_account_number: cards::CardNumber, pub application_expiration_date: String, pub currency_code: String, pub transaction_amount: i64, pub device_manufacturer_identifier: Secret<String>, pub payment_data_type: Secret<String>, pub payment_data: ApplePayCryptogramDataInternal, } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayCryptogramDataInternal { pub online_payment_cryptogram: Secret<String>, pub eci_indicator: Option<String>, } impl TryFrom<ApplePayPredecryptDataInternal> for common_payment_types::ApplePayPredecryptData { type Error = common_utils::errors::ValidationError; fn try_from(data: ApplePayPredecryptDataInternal) -> Result<Self, Self::Error> { let application_expiration_month = data.clone().get_expiry_month()?; let application_expiration_year = data.clone().get_four_digit_expiry_year()?; Ok(Self { application_primary_account_number: data.application_primary_account_number.clone(), application_expiration_month, application_expiration_year, payment_data: data.payment_data.into(), }) } } impl From<GooglePayPredecryptDataInternal> for common_payment_types::GPayPredecryptData { fn from(data: GooglePayPredecryptDataInternal) -> Self { Self { card_exp_month: Secret::new(data.payment_method_details.expiration_month.two_digits()), card_exp_year: Secret::new(data.payment_method_details.expiration_year.four_digits()), application_primary_account_number: data.payment_method_details.pan.clone(), cryptogram: data.payment_method_details.cryptogram.clone(), eci_indicator: data.payment_method_details.eci_indicator.clone(), } } } impl From<ApplePayCryptogramDataInternal> for common_payment_types::ApplePayCryptogramData { fn from(payment_data: ApplePayCryptogramDataInternal) -> Self { Self { online_payment_cryptogram: payment_data.online_payment_cryptogram, eci_indicator: payment_data.eci_indicator, } } } impl ApplePayPredecryptDataInternal { /// This logic being applied as apple pay provides application_expiration_date in the YYMMDD format fn get_four_digit_expiry_year( &self, ) -> Result<Secret<String>, common_utils::errors::ValidationError> { Ok(Secret::new(format!( "20{}", self.application_expiration_date.get(0..2).ok_or( common_utils::errors::ValidationError::InvalidValue { message: "Invalid two-digit year".to_string(), } )? ))) } fn get_expiry_month(&self) -> Result<Secret<String>, common_utils::errors::ValidationError> { Ok(Secret::new( self.application_expiration_date .get(2..4) .ok_or(common_utils::errors::ValidationError::InvalidValue { message: "Invalid two-digit month".to_string(), })? .to_owned(), )) } } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayPredecryptDataInternal { pub message_expiration: String, pub message_id: String, #[serde(rename = "paymentMethod")] pub payment_method_type: String, pub payment_method_details: GooglePayPaymentMethodDetails, } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayPaymentMethodDetails { pub auth_method: common_enums::enums::GooglePayAuthMethod, pub expiration_month: cards::CardExpirationMonth, pub expiration_year: cards::CardExpirationYear, pub pan: cards::CardNumber, pub cryptogram: Option<Secret<String>>, pub eci_indicator: Option<String>, pub card_network: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeDecryptedData { pub client_id: Secret<String>, pub profile_id: String, pub token: PazeToken, pub payment_card_network: common_enums::enums::CardNetwork, pub dynamic_data: Vec<PazeDynamicData>, pub billing_address: PazeAddress, pub consumer: PazeConsumer, pub eci: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeToken { pub payment_token: NetworkTokenNumber, pub token_expiration_month: Secret<String>, pub token_expiration_year: Secret<String>, pub payment_account_reference: Secret<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeDynamicData { pub dynamic_data_value: Option<Secret<String>>, pub dynamic_data_type: Option<String>, pub dynamic_data_expiration: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeAddress { pub name: Option<Secret<String>>, pub line1: Option<Secret<String>>, pub line2: Option<Secret<String>>, pub line3: Option<Secret<String>>, pub city: Option<Secret<String>>, pub state: Option<Secret<String>>, pub zip: Option<Secret<String>>, pub country_code: Option<common_enums::enums::CountryAlpha2>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeConsumer { // This is consumer data not customer data. pub first_name: Option<Secret<String>>, pub last_name: Option<Secret<String>>, pub full_name: Secret<String>, pub email_address: common_utils::pii::Email, pub mobile_number: Option<PazePhoneNumber>, pub country_code: Option<common_enums::enums::CountryAlpha2>, pub language_code: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazePhoneNumber { pub country_code: Secret<String>, pub phone_number: Secret<String>, } #[derive(Debug, Default, Clone, Serialize)] pub struct RecurringMandatePaymentData { pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::enums::Currency>, pub mandate_metadata: Option<common_utils::pii::SecretSerdeValue>, } #[derive(Debug, Clone, Serialize)] pub struct PaymentMethodBalance { pub amount: MinorUnit, pub currency: common_enums::enums::Currency, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ConnectorResponseData { pub additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>, extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>, is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>, } impl ConnectorResponseData { pub fn with_additional_payment_method_data( additional_payment_method_data: AdditionalPaymentMethodConnectorResponse, ) -> Self { Self { additional_payment_method_data: Some(additional_payment_method_data), extended_authorization_response_data: None, is_overcapture_enabled: None, } } pub fn new( additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>, is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>, extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>, ) -> Self { Self { additional_payment_method_data, extended_authorization_response_data, is_overcapture_enabled, } } pub fn get_extended_authorization_response_data( &self, ) -> Option<&ExtendedAuthorizationResponseData> { self.extended_authorization_response_data.as_ref() } pub fn is_overcapture_enabled(&self) -> Option<primitive_wrappers::OvercaptureEnabledBool> { self.is_overcapture_enabled } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum AdditionalPaymentMethodConnectorResponse { Card { /// Details regarding the authentication details of the connector, if this is a 3ds payment. authentication_data: Option<serde_json::Value>, /// Various payment checks that are done for a payment payment_checks: Option<serde_json::Value>, /// Card Network returned by the processor card_network: Option<String>, /// Domestic(Co-Branded) Card network returned by the processor domestic_network: Option<String>, }, PayLater { klarna_sdk: Option<KlarnaSdkResponse>, }, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ExtendedAuthorizationResponseData { pub extended_authentication_applied: Option<primitive_wrappers::ExtendedAuthorizationAppliedBool>, pub capture_before: Option<time::PrimitiveDateTime>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct KlarnaSdkResponse { pub payment_type: Option<String>, } #[derive(Clone, Debug, Serialize)] pub struct ErrorResponse { pub code: String, pub message: String, pub reason: Option<String>, pub status_code: u16, pub attempt_status: Option<common_enums::enums::AttemptStatus>, pub connector_transaction_id: Option<String>, pub network_decline_code: Option<String>, pub network_advice_code: Option<String>, pub network_error_message: Option<String>, pub connector_metadata: Option<Secret<serde_json::Value>>, } impl Default for ErrorResponse { fn default() -> Self { Self { code: "HE_00".to_string(), message: "Something went wrong".to_string(), reason: None, status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, } } } impl ErrorResponse { pub fn get_not_implemented() -> Self { Self { code: "IR_00".to_string(), message: "This API is under development and will be made available soon.".to_string(), reason: None, status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, } } } /// Get updatable trakcer objects of payment intent and payment attempt #[cfg(feature = "v2")] pub trait TrackerPostUpdateObjects<Flow, FlowRequest, D> { fn get_payment_intent_update( &self, payment_data: &D, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate; fn get_payment_attempt_update( &self, payment_data: &D, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate; /// Get the amount that can be captured for the payment fn get_amount_capturable(&self, payment_data: &D) -> Option<MinorUnit>; /// Get the amount that has been captured for the payment fn get_captured_amount(&self, payment_data: &D) -> Option<MinorUnit>; /// Get the attempt status based on parameters like captured amount and amount capturable fn get_attempt_status_for_db_update( &self, payment_data: &D, ) -> common_enums::enums::AttemptStatus; } #[cfg(feature = "v2")] impl TrackerPostUpdateObjects< router_flow_types::Authorize, router_request_types::PaymentsAuthorizeData, payments::PaymentConfirmData<router_flow_types::Authorize>, > for RouterData< router_flow_types::Authorize, router_request_types::PaymentsAuthorizeData, router_response_types::PaymentsResponseData, > { fn get_payment_intent_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); let updated_feature_metadata = payment_data .payment_intent .feature_metadata .clone() .map(|mut feature_metadata| { if let Some(ref mut payment_revenue_recovery_metadata) = feature_metadata.payment_revenue_recovery_metadata { payment_revenue_recovery_metadata.payment_connector_transmission = if self .response .is_ok() { common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded } else { common_enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful }; } Box::new(feature_metadata) }); match self.response { Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate { status: common_enums::IntentStatus::from( self.get_attempt_status_for_db_update(payment_data), ), amount_captured, updated_by: storage_scheme.to_string(), feature_metadata: updated_feature_metadata, }, Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate { status: { let attempt_status = match error.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error.status_code { 500..=511 => common_enums::enums::AttemptStatus::Pending, _ => common_enums::enums::AttemptStatus::Failure, }, }; common_enums::IntentStatus::from(attempt_status) }, amount_captured, updated_by: storage_scheme.to_string(), feature_metadata: updated_feature_metadata, }, } } fn get_payment_attempt_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { let amount_capturable = self.get_amount_capturable(payment_data); match self.response { Ok(ref response_router_data) => match response_router_data { router_response_types::PaymentsResponseData::TransactionResponse { resource_id, redirection_data, connector_metadata, connector_response_reference_id, .. } => { let attempt_status = self.get_attempt_status_for_db_update(payment_data); let connector_payment_id = match resource_id { router_request_types::ResponseId::NoResponseId => None, router_request_types::ResponseId::ConnectorTransactionId(id) | router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()), }; PaymentAttemptUpdate::ConfirmIntentResponse(Box::new( payments::payment_attempt::ConfirmIntentResponseUpdate { status: attempt_status, connector_payment_id, updated_by: storage_scheme.to_string(), redirection_data: *redirection_data.clone(), amount_capturable, connector_metadata: connector_metadata.clone().map(Secret::new), connector_token_details: response_router_data .get_updated_connector_token_details( payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|token_details| { token_details.get_connector_token_request_reference_id() }), ), connector_response_reference_id: connector_response_reference_id .clone(), }, )) } router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(), router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TransactionUnresolvedResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ConnectorCustomerResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => todo!(), }, Err(ref error_response) => { let ErrorResponse { code, message, reason, status_code: _, attempt_status: _, connector_transaction_id, network_decline_code, network_advice_code, network_error_message, connector_metadata, } = error_response.clone(); let attempt_status = match error_response.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error_response.status_code { 500..=511 => common_enums::enums::AttemptStatus::Pending, _ => common_enums::enums::AttemptStatus::Failure, }, }; let error_details = ErrorDetails { code, message, reason, unified_code: None, unified_message: None, network_advice_code, network_decline_code, network_error_message, }; PaymentAttemptUpdate::ErrorUpdate { status: attempt_status, error: error_details, amount_capturable, connector_payment_id: connector_transaction_id, updated_by: storage_scheme.to_string(), } } } } fn get_attempt_status_for_db_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>, ) -> common_enums::AttemptStatus { match self.status { common_enums::AttemptStatus::Charged => { let amount_captured = self .get_captured_amount(payment_data) .unwrap_or(MinorUnit::zero()); let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); if amount_captured == total_amount { common_enums::AttemptStatus::Charged } else { common_enums::AttemptStatus::PartialCharged } } _ => self.status, } } fn get_amount_capturable( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); let amount_capturable_from_intent_status = match intent_status { // If the status is already succeeded / failed we cannot capture any more amount // So set the amount capturable to zero common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the capturable amount when it reaches terminal / capturable state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, // If status is requires capture, get the total amount that can be captured // This is in cases where the capture method will be `manual` or `manual_multiple` // We do not need to handle the case where amount_to_capture is provided here as it cannot be passed in authroize flow common_enums::IntentStatus::RequiresCapture => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // Invalid statues for this flow, after doing authorization this state is invalid common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, }; self.minor_amount_capturable .or(amount_capturable_from_intent_status) .or(Some(payment_data.payment_attempt.get_total_amount())) } fn get_captured_amount( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount that was captured let intent_status = common_enums::IntentStatus::from(self.status); let amount_captured_from_intent_status = match intent_status { // If the status is succeeded then we have captured the whole amount // we need not check for `amount_to_capture` here because passing `amount_to_capture` when authorizing is not supported common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // No amount is captured common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the amount captured when it reaches terminal state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, // No amount has been captured yet common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { Some(MinorUnit::zero()) } // Invalid statues for this flow common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, }; self.minor_amount_captured .or(amount_captured_from_intent_status) .or(Some(payment_data.payment_attempt.get_total_amount())) } } #[cfg(feature = "v2")] impl TrackerPostUpdateObjects< router_flow_types::Capture, router_request_types::PaymentsCaptureData, payments::PaymentCaptureData<router_flow_types::Capture>, > for RouterData< router_flow_types::Capture, router_request_types::PaymentsCaptureData, router_response_types::PaymentsResponseData, > { fn get_payment_intent_update( &self, payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); match self.response { Ok(ref _response) => PaymentIntentUpdate::CaptureUpdate { status: common_enums::IntentStatus::from( self.get_attempt_status_for_db_update(payment_data), ), amount_captured, updated_by: storage_scheme.to_string(), }, Err(ref error) => PaymentIntentUpdate::CaptureUpdate { status: error .attempt_status .map(common_enums::IntentStatus::from) .unwrap_or(common_enums::IntentStatus::Failed), amount_captured, updated_by: storage_scheme.to_string(), }, } } fn get_payment_attempt_update( &self, payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { let amount_capturable = self.get_amount_capturable(payment_data); match self.response { Ok(ref response_router_data) => match response_router_data { router_response_types::PaymentsResponseData::TransactionResponse { .. } => { let attempt_status = self.status; PaymentAttemptUpdate::CaptureUpdate { status: attempt_status, amount_capturable, updated_by: storage_scheme.to_string(), } } router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(), router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TransactionUnresolvedResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ConnectorCustomerResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => todo!(), }, Err(ref error_response) => { let ErrorResponse { code, message, reason, status_code: _, attempt_status, connector_transaction_id, network_advice_code, network_decline_code, network_error_message, connector_metadata: _, } = error_response.clone(); let attempt_status = attempt_status.unwrap_or(self.status); let error_details = ErrorDetails { code, message, reason, unified_code: None, unified_message: None, network_advice_code, network_decline_code, network_error_message, }; PaymentAttemptUpdate::ErrorUpdate { status: attempt_status, error: error_details, amount_capturable, connector_payment_id: connector_transaction_id, updated_by: storage_scheme.to_string(), } } } } fn get_attempt_status_for_db_update( &self, payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>, ) -> common_enums::AttemptStatus { match self.status { common_enums::AttemptStatus::Charged => { let amount_captured = self .get_captured_amount(payment_data) .unwrap_or(MinorUnit::zero()); let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); if amount_captured == total_amount { common_enums::AttemptStatus::Charged } else { common_enums::AttemptStatus::PartialCharged } } _ => self.status, } } fn get_amount_capturable( &self, payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); match intent_status { // If the status is already succeeded / failed we cannot capture any more amount common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the capturable amount when it reaches terminal / capturable state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // Invalid statues for this flow common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } fn get_captured_amount( &self, payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); match intent_status { // If the status is succeeded then we have captured the whole amount common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => { let amount_to_capture = payment_data .payment_attempt .amount_details .get_amount_to_capture(); let amount_captured = amount_to_capture .unwrap_or(payment_data.payment_attempt.amount_details.get_net_amount()); Some(amount_captured) } // No amount is captured common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // For these statuses, update the amount captured when it reaches terminal state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, // Invalid statues for this flow common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => { todo!() } } } } #[cfg(feature = "v2")] impl TrackerPostUpdateObjects< router_flow_types::PSync, router_request_types::PaymentsSyncData, payments::PaymentStatusData<router_flow_types::PSync>, > for RouterData< router_flow_types::PSync, router_request_types::PaymentsSyncData, router_response_types::PaymentsResponseData, > { fn get_payment_intent_update( &self, payment_data: &payments::PaymentStatusData<router_flow_types::PSync>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); match self.response { Ok(ref _response) => PaymentIntentUpdate::SyncUpdate { status: common_enums::IntentStatus::from( self.get_attempt_status_for_db_update(payment_data), ), amount_captured, updated_by: storage_scheme.to_string(), }, Err(ref error) => PaymentIntentUpdate::SyncUpdate { status: { let attempt_status = match error.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error.status_code { 200..=299 => common_enums::enums::AttemptStatus::Failure, _ => self.status, }, }; common_enums::IntentStatus::from(attempt_status) }, amount_captured, updated_by: storage_scheme.to_string(), }, } } fn get_payment_attempt_update( &self, payment_data: &payments::PaymentStatusData<router_flow_types::PSync>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { let amount_capturable = self.get_amount_capturable(payment_data); match self.response { Ok(ref response_router_data) => match response_router_data { router_response_types::PaymentsResponseData::TransactionResponse { .. } => { let attempt_status = self.get_attempt_status_for_db_update(payment_data); PaymentAttemptUpdate::SyncUpdate { status: attempt_status, amount_capturable, updated_by: storage_scheme.to_string(), } } router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(), router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TransactionUnresolvedResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ConnectorCustomerResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => todo!(), }, Err(ref error_response) => { let ErrorResponse { code, message, reason, status_code: _, attempt_status: _, connector_transaction_id, network_advice_code, network_decline_code, network_error_message, connector_metadata: _, } = error_response.clone(); let attempt_status = match error_response.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error_response.status_code { 200..=299 => common_enums::enums::AttemptStatus::Failure, _ => self.status, }, }; let error_details = ErrorDetails { code, message, reason, unified_code: None, unified_message: None, network_advice_code, network_decline_code, network_error_message, }; PaymentAttemptUpdate::ErrorUpdate { status: attempt_status, error: error_details, amount_capturable, connector_payment_id: connector_transaction_id, updated_by: storage_scheme.to_string(), } } } } fn get_attempt_status_for_db_update( &self, payment_data: &payments::PaymentStatusData<router_flow_types::PSync>, ) -> common_enums::AttemptStatus { match self.status { common_enums::AttemptStatus::Charged => { let amount_captured = self .get_captured_amount(payment_data) .unwrap_or(MinorUnit::zero()); let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); if amount_captured == total_amount { common_enums::AttemptStatus::Charged } else { common_enums::AttemptStatus::PartialCharged } } _ => self.status, } } fn get_amount_capturable( &self, payment_data: &payments::PaymentStatusData<router_flow_types::PSync>, ) -> Option<MinorUnit> { let payment_attempt = &payment_data.payment_attempt; // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); let amount_capturable_from_intent_status = match intent_status { // If the status is already succeeded / failed we cannot capture any more amount common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the capturable amount when it reaches terminal / capturable state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCaptured => { let total_amount = payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // Invalid statues for this flow common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, }; self.minor_amount_capturable .or(amount_capturable_from_intent_status) } fn get_captured_amount( &self, payment_data: &payments::PaymentStatusData<router_flow_types::PSync>, ) -> Option<MinorUnit> { let payment_attempt = &payment_data.payment_attempt; // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); let amount_captured_from_intent_status = match intent_status { // If the status is succeeded then we have captured the whole amount or amount_to_capture common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => { let amount_to_capture = payment_attempt.amount_details.get_amount_to_capture(); let amount_captured = amount_to_capture.unwrap_or(payment_attempt.amount_details.get_net_amount()); Some(amount_captured) } // No amount is captured common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the amount captured when it reaches terminal state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { let total_amount = payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // Invalid statues for this flow common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, }; self.minor_amount_captured .or(amount_captured_from_intent_status) .or(Some(payment_data.payment_attempt.get_total_amount())) } } #[cfg(feature = "v2")] impl TrackerPostUpdateObjects< router_flow_types::ExternalVaultProxy, router_request_types::ExternalVaultProxyPaymentsData, payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>, > for RouterData< router_flow_types::ExternalVaultProxy, router_request_types::ExternalVaultProxyPaymentsData, router_response_types::PaymentsResponseData, > { fn get_payment_intent_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); match self.response { Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate { status: common_enums::IntentStatus::from( self.get_attempt_status_for_db_update(payment_data), ), amount_captured, updated_by: storage_scheme.to_string(), feature_metadata: None, }, Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate { status: { let attempt_status = match error.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error.status_code { 500..=511 => common_enums::enums::AttemptStatus::Pending, _ => common_enums::enums::AttemptStatus::Failure, }, }; common_enums::IntentStatus::from(attempt_status) }, amount_captured, updated_by: storage_scheme.to_string(), feature_metadata: None, }, } } fn get_payment_attempt_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { let amount_capturable = self.get_amount_capturable(payment_data); match self.response { Ok(ref response_router_data) => match response_router_data { router_response_types::PaymentsResponseData::TransactionResponse { resource_id, redirection_data, connector_metadata, connector_response_reference_id, .. } => { let attempt_status = self.get_attempt_status_for_db_update(payment_data); let connector_payment_id = match resource_id { router_request_types::ResponseId::NoResponseId => None, router_request_types::ResponseId::ConnectorTransactionId(id) | router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()), }; PaymentAttemptUpdate::ConfirmIntentResponse(Box::new( payments::payment_attempt::ConfirmIntentResponseUpdate { status: attempt_status, connector_payment_id, updated_by: storage_scheme.to_string(), redirection_data: *redirection_data.clone(), amount_capturable, connector_metadata: connector_metadata.clone().map(Secret::new), connector_token_details: response_router_data .get_updated_connector_token_details( payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|token_details| { token_details.get_connector_token_request_reference_id() }), ), connector_response_reference_id: connector_response_reference_id .clone(), }, )) } router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(), router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TransactionUnresolvedResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ConnectorCustomerResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => todo!(), }, Err(ref error_response) => { let ErrorResponse { code, message, reason, status_code: _, attempt_status: _, connector_transaction_id, network_decline_code, network_advice_code, network_error_message, connector_metadata, } = error_response.clone(); let attempt_status = match error_response.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error_response.status_code { 500..=511 => common_enums::enums::AttemptStatus::Pending, _ => common_enums::enums::AttemptStatus::Failure, }, }; let error_details = ErrorDetails { code, message, reason, unified_code: None, unified_message: None, network_advice_code, network_decline_code, network_error_message, }; PaymentAttemptUpdate::ErrorUpdate { status: attempt_status, error: error_details, amount_capturable, connector_payment_id: connector_transaction_id, updated_by: storage_scheme.to_string(), } } } } fn get_attempt_status_for_db_update( &self, _payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>, ) -> common_enums::AttemptStatus { // For this step, consider whatever status was given by the connector module // We do not need to check for amount captured or amount capturable here because we are authorizing the whole amount self.status } fn get_amount_capturable( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } fn get_captured_amount( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount that was captured let intent_status = common_enums::IntentStatus::from(self.status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::Failed | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::CancelledPostCapture => Some(MinorUnit::zero()), common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } } #[cfg(feature = "v2")] impl TrackerPostUpdateObjects< router_flow_types::SetupMandate, router_request_types::SetupMandateRequestData, payments::PaymentConfirmData<router_flow_types::SetupMandate>, > for RouterData< router_flow_types::SetupMandate, router_request_types::SetupMandateRequestData, router_response_types::PaymentsResponseData, > { fn get_payment_intent_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); match self.response { Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate { status: common_enums::IntentStatus::from( self.get_attempt_status_for_db_update(payment_data), ), amount_captured, updated_by: storage_scheme.to_string(), feature_metadata: None, }, Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate { status: error .attempt_status .map(common_enums::IntentStatus::from) .unwrap_or(common_enums::IntentStatus::Failed), amount_captured, updated_by: storage_scheme.to_string(), feature_metadata: None, }, } } fn get_payment_attempt_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { let amount_capturable = self.get_amount_capturable(payment_data); match self.response { Ok(ref response_router_data) => match response_router_data { router_response_types::PaymentsResponseData::TransactionResponse { resource_id, redirection_data, connector_metadata, .. } => { let attempt_status = self.get_attempt_status_for_db_update(payment_data); let connector_payment_id = match resource_id { router_request_types::ResponseId::NoResponseId => None, router_request_types::ResponseId::ConnectorTransactionId(id) | router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()), }; PaymentAttemptUpdate::ConfirmIntentResponse(Box::new( payments::payment_attempt::ConfirmIntentResponseUpdate { status: attempt_status, connector_payment_id, updated_by: storage_scheme.to_string(), redirection_data: *redirection_data.clone(), amount_capturable, connector_metadata: connector_metadata.clone().map(Secret::new), connector_token_details: response_router_data .get_updated_connector_token_details( payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|token_details| { token_details.get_connector_token_request_reference_id() }), ), connector_response_reference_id: None, }, )) } router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(), router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TransactionUnresolvedResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ConnectorCustomerResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => todo!(), }, Err(ref error_response) => { let ErrorResponse { code, message, reason, status_code: _, attempt_status, connector_transaction_id, network_advice_code, network_decline_code, network_error_message, connector_metadata: _, } = error_response.clone(); let attempt_status = attempt_status.unwrap_or(self.status); let error_details = ErrorDetails { code, message, reason, unified_code: None, unified_message: None, network_advice_code, network_decline_code, network_error_message, }; PaymentAttemptUpdate::ErrorUpdate { status: attempt_status, error: error_details, amount_capturable, connector_payment_id: connector_transaction_id, updated_by: storage_scheme.to_string(), } } } } fn get_attempt_status_for_db_update( &self, _payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>, ) -> common_enums::AttemptStatus { // For this step, consider whatever status was given by the connector module // We do not need to check for amount captured or amount capturable here because we are authorizing the whole amount self.status } fn get_amount_capturable( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); match intent_status { // If the status is already succeeded / failed we cannot capture any more amount // So set the amount capturable to zero common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the capturable amount when it reaches terminal / capturable state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, // If status is requires capture, get the total amount that can be captured // This is in cases where the capture method will be `manual` or `manual_multiple` // We do not need to handle the case where amount_to_capture is provided here as it cannot be passed in authroize flow common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // Invalid statues for this flow, after doing authorization this state is invalid common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } fn get_captured_amount( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount that was captured let intent_status = common_enums::IntentStatus::from(self.status); match intent_status { // If the status is succeeded then we have captured the whole amount // we need not check for `amount_to_capture` here because passing `amount_to_capture` when authorizing is not supported common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // No amount is captured common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the amount captured when it reaches terminal state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, // No amount has been captured yet common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { Some(MinorUnit::zero()) } // Invalid statues for this flow common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } } #[cfg(feature = "v2")] impl TrackerPostUpdateObjects< router_flow_types::Void, router_request_types::PaymentsCancelData, payments::PaymentCancelData<router_flow_types::Void>, > for RouterData< router_flow_types::Void, router_request_types::PaymentsCancelData, router_response_types::PaymentsResponseData, > { fn get_payment_intent_update( &self, payment_data: &payments::PaymentCancelData<router_flow_types::Void>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let intent_status = common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data)); PaymentIntentUpdate::VoidUpdate { status: intent_status, updated_by: storage_scheme.to_string(), } } fn get_payment_attempt_update( &self, payment_data: &payments::PaymentCancelData<router_flow_types::Void>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { match &self.response { Err(ref error_response) => { let ErrorResponse { code, message, reason, status_code: _, attempt_status: _, connector_transaction_id, network_decline_code, network_advice_code, network_error_message, connector_metadata: _, } = error_response.clone(); // Handle errors exactly let status = match error_response.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error_response.status_code { 500..=511 => common_enums::AttemptStatus::Pending, _ => common_enums::AttemptStatus::VoidFailed, }, }; let error_details = ErrorDetails { code, message, reason, unified_code: None, unified_message: None, network_advice_code, network_decline_code, network_error_message, }; PaymentAttemptUpdate::ErrorUpdate { status, amount_capturable: Some(MinorUnit::zero()), error: error_details, updated_by: storage_scheme.to_string(), connector_payment_id: connector_transaction_id, } } Ok(ref _response) => PaymentAttemptUpdate::VoidUpdate { status: self.status, cancellation_reason: payment_data.payment_attempt.cancellation_reason.clone(), updated_by: storage_scheme.to_string(), }, } } fn get_amount_capturable( &self, _payment_data: &payments::PaymentCancelData<router_flow_types::Void>, ) -> Option<MinorUnit> { // For void operations, no amount is capturable Some(MinorUnit::zero()) } fn get_captured_amount( &self, _payment_data: &payments::PaymentCancelData<router_flow_types::Void>, ) -> Option<MinorUnit> { // For void operations, no amount is captured Some(MinorUnit::zero()) } fn get_attempt_status_for_db_update( &self, _payment_data: &payments::PaymentCancelData<router_flow_types::Void>, ) -> common_enums::AttemptStatus { // For void operations, determine status based on response match &self.response { Err(ref error_response) => match error_response.attempt_status { Some(status) => status, None => match error_response.status_code { 500..=511 => common_enums::AttemptStatus::Pending, _ => common_enums::AttemptStatus::VoidFailed, }, }, Ok(ref _response) => self.status, } } }
crates/hyperswitch_domain_models/src/router_data.rs
hyperswitch_domain_models::src::router_data
16,106
true
// File: crates/hyperswitch_domain_models/src/business_profile.rs // Module: hyperswitch_domain_models::src::business_profile use std::borrow::Cow; use common_enums::enums as api_enums; use common_types::{domain::AcquirerConfig, primitive_wrappers}; use common_utils::{ crypto::{OptionalEncryptableName, OptionalEncryptableValue}, date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, ext_traits::{OptionExt, ValueExt}, pii, type_name, types::keymanager, }; #[cfg(feature = "v2")] use diesel_models::business_profile::RevenueRecoveryAlgorithmData; use diesel_models::business_profile::{ self as storage_types, AuthenticationConnectorDetails, BusinessPaymentLinkConfig, BusinessPayoutLinkConfig, CardTestingGuardConfig, ExternalVaultConnectorDetails, ProfileUpdateInternal, WebhookDetails, }; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{ behaviour::Conversion, errors::api_error_response, merchant_key_store::MerchantKeyStore, type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, }; #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct Profile { profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_name: String, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub is_recon_enabled: bool, pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: bool, pub is_l2_l3_enabled: bool, pub version: common_enums::ApiVersion, pub dynamic_routing_algorithm: Option<serde_json::Value>, pub is_network_tokenization_enabled: bool, pub is_auto_retries_enabled: bool, pub max_auto_retries_enabled: Option<i16>, pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, pub is_click_to_pay_enabled: bool, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, pub is_clear_pan_retries_enabled: bool, pub force_3ds_challenge: bool, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: bool, pub three_ds_decision_rule_algorithm: Option<serde_json::Value>, pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, pub external_vault_details: ExternalVaultDetails, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub enum ExternalVaultDetails { ExternalVaultEnabled(ExternalVaultConnectorDetails), Skip, } #[cfg(feature = "v1")] impl ExternalVaultDetails { pub fn is_external_vault_enabled(&self) -> bool { match self { Self::ExternalVaultEnabled(_) => true, Self::Skip => false, } } } #[cfg(feature = "v1")] impl TryFrom<( Option<common_enums::ExternalVaultEnabled>, Option<ExternalVaultConnectorDetails>, )> for ExternalVaultDetails { type Error = error_stack::Report<ValidationError>; fn try_from( item: ( Option<common_enums::ExternalVaultEnabled>, Option<ExternalVaultConnectorDetails>, ), ) -> Result<Self, Self::Error> { match item { (is_external_vault_enabled, external_vault_connector_details) if is_external_vault_enabled .unwrap_or(common_enums::ExternalVaultEnabled::Skip) == common_enums::ExternalVaultEnabled::Enable => { Ok(Self::ExternalVaultEnabled( external_vault_connector_details .get_required_value("ExternalVaultConnectorDetails")?, )) } _ => Ok(Self::Skip), } } } #[cfg(feature = "v1")] impl TryFrom<(Option<bool>, Option<ExternalVaultConnectorDetails>)> for ExternalVaultDetails { type Error = error_stack::Report<ValidationError>; fn try_from( item: (Option<bool>, Option<ExternalVaultConnectorDetails>), ) -> Result<Self, Self::Error> { match item { (is_external_vault_enabled, external_vault_connector_details) if is_external_vault_enabled.unwrap_or(false) => { Ok(Self::ExternalVaultEnabled( external_vault_connector_details .get_required_value("ExternalVaultConnectorDetails")?, )) } _ => Ok(Self::Skip), } } } #[cfg(feature = "v1")] impl From<ExternalVaultDetails> for ( Option<common_enums::ExternalVaultEnabled>, Option<ExternalVaultConnectorDetails>, ) { fn from(external_vault_details: ExternalVaultDetails) -> Self { match external_vault_details { ExternalVaultDetails::ExternalVaultEnabled(connector_details) => ( Some(common_enums::ExternalVaultEnabled::Enable), Some(connector_details), ), ExternalVaultDetails::Skip => (Some(common_enums::ExternalVaultEnabled::Skip), None), } } } #[cfg(feature = "v1")] impl From<ExternalVaultDetails> for (Option<bool>, Option<ExternalVaultConnectorDetails>) { fn from(external_vault_details: ExternalVaultDetails) -> Self { match external_vault_details { ExternalVaultDetails::ExternalVaultEnabled(connector_details) => { (Some(true), Some(connector_details)) } ExternalVaultDetails::Skip => (Some(false), None), } } } #[cfg(feature = "v1")] pub struct ProfileSetter { pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_name: String, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub is_recon_enabled: bool, pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: bool, pub is_l2_l3_enabled: bool, pub dynamic_routing_algorithm: Option<serde_json::Value>, pub is_network_tokenization_enabled: bool, pub is_auto_retries_enabled: bool, pub max_auto_retries_enabled: Option<i16>, pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, pub is_click_to_pay_enabled: bool, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, pub is_clear_pan_retries_enabled: bool, pub force_3ds_challenge: bool, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<api_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: bool, pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, pub external_vault_details: ExternalVaultDetails, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v1")] impl From<ProfileSetter> for Profile { fn from(value: ProfileSetter) -> Self { Self { profile_id: value.profile_id, merchant_id: value.merchant_id, profile_name: value.profile_name, created_at: value.created_at, modified_at: value.modified_at, return_url: value.return_url, enable_payment_response_hash: value.enable_payment_response_hash, payment_response_hash_key: value.payment_response_hash_key, redirect_to_merchant_with_http_post: value.redirect_to_merchant_with_http_post, webhook_details: value.webhook_details, metadata: value.metadata, routing_algorithm: value.routing_algorithm, intent_fulfillment_time: value.intent_fulfillment_time, frm_routing_algorithm: value.frm_routing_algorithm, payout_routing_algorithm: value.payout_routing_algorithm, is_recon_enabled: value.is_recon_enabled, applepay_verified_domains: value.applepay_verified_domains, payment_link_config: value.payment_link_config, session_expiry: value.session_expiry, authentication_connector_details: value.authentication_connector_details, payout_link_config: value.payout_link_config, is_extended_card_info_enabled: value.is_extended_card_info_enabled, extended_card_info_config: value.extended_card_info_config, is_connector_agnostic_mit_enabled: value.is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing: value.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: value .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: value .collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers: value.outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector: value .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: value .always_collect_shipping_details_from_wallet_connector, tax_connector_id: value.tax_connector_id, is_tax_connector_enabled: value.is_tax_connector_enabled, is_l2_l3_enabled: value.is_l2_l3_enabled, version: common_types::consts::API_VERSION, dynamic_routing_algorithm: value.dynamic_routing_algorithm, is_network_tokenization_enabled: value.is_network_tokenization_enabled, is_auto_retries_enabled: value.is_auto_retries_enabled, max_auto_retries_enabled: value.max_auto_retries_enabled, always_request_extended_authorization: value.always_request_extended_authorization, is_click_to_pay_enabled: value.is_click_to_pay_enabled, authentication_product_ids: value.authentication_product_ids, card_testing_guard_config: value.card_testing_guard_config, card_testing_secret_key: value.card_testing_secret_key, is_clear_pan_retries_enabled: value.is_clear_pan_retries_enabled, force_3ds_challenge: value.force_3ds_challenge, is_debit_routing_enabled: value.is_debit_routing_enabled, merchant_business_country: value.merchant_business_country, is_iframe_redirection_enabled: value.is_iframe_redirection_enabled, is_pre_network_tokenization_enabled: value.is_pre_network_tokenization_enabled, three_ds_decision_rule_algorithm: None, // three_ds_decision_rule_algorithm is not yet created during profile creation acquirer_config_map: None, merchant_category_code: value.merchant_category_code, merchant_country_code: value.merchant_country_code, dispute_polling_interval: value.dispute_polling_interval, is_manual_retry_enabled: value.is_manual_retry_enabled, always_enable_overcapture: value.always_enable_overcapture, external_vault_details: value.external_vault_details, billing_processor_id: value.billing_processor_id, } } } impl Profile { #[cfg(feature = "v1")] pub fn get_id(&self) -> &common_utils::id_type::ProfileId { &self.profile_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::ProfileId { &self.id } } #[cfg(feature = "v1")] #[derive(Debug)] pub struct ProfileGeneralUpdate { pub profile_name: Option<String>, pub return_url: Option<String>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: Option<bool>, pub is_l2_l3_enabled: Option<bool>, pub dynamic_routing_algorithm: Option<serde_json::Value>, pub is_network_tokenization_enabled: Option<bool>, pub is_auto_retries_enabled: Option<bool>, pub max_auto_retries_enabled: Option<i16>, pub is_click_to_pay_enabled: Option<bool>, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, pub is_clear_pan_retries_enabled: Option<bool>, pub force_3ds_challenge: Option<bool>, pub is_debit_routing_enabled: Option<bool>, pub merchant_business_country: Option<api_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: Option<bool>, pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v1")] #[derive(Debug)] pub enum ProfileUpdate { Update(Box<ProfileGeneralUpdate>), RoutingAlgorithmUpdate { routing_algorithm: Option<serde_json::Value>, payout_routing_algorithm: Option<serde_json::Value>, three_ds_decision_rule_algorithm: Option<serde_json::Value>, }, DynamicRoutingAlgorithmUpdate { dynamic_routing_algorithm: Option<serde_json::Value>, }, ExtendedCardInfoUpdate { is_extended_card_info_enabled: bool, }, ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled: bool, }, NetworkTokenizationUpdate { is_network_tokenization_enabled: bool, }, CardTestingSecretKeyUpdate { card_testing_secret_key: OptionalEncryptableName, }, AcquirerConfigMapUpdate { acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, }, } #[cfg(feature = "v1")] impl From<ProfileUpdate> for ProfileUpdateInternal { fn from(profile_update: ProfileUpdate) -> Self { let now = date_time::now(); match profile_update { ProfileUpdate::Update(update) => { let ProfileGeneralUpdate { profile_name, return_url, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, webhook_details, metadata, routing_algorithm, intent_fulfillment_time, frm_routing_algorithm, payout_routing_algorithm, applepay_verified_domains, payment_link_config, session_expiry, authentication_connector_details, payout_link_config, extended_card_info_config, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector, tax_connector_id, is_tax_connector_enabled, is_l2_l3_enabled, dynamic_routing_algorithm, is_network_tokenization_enabled, is_auto_retries_enabled, max_auto_retries_enabled, is_click_to_pay_enabled, authentication_product_ids, card_testing_guard_config, card_testing_secret_key, is_clear_pan_retries_enabled, force_3ds_challenge, is_debit_routing_enabled, merchant_business_country, is_iframe_redirection_enabled, is_pre_network_tokenization_enabled, merchant_category_code, merchant_country_code, dispute_polling_interval, always_request_extended_authorization, is_manual_retry_enabled, always_enable_overcapture, is_external_vault_enabled, external_vault_connector_details, billing_processor_id, } = *update; let is_external_vault_enabled = match is_external_vault_enabled { Some(external_vault_mode) => match external_vault_mode { common_enums::ExternalVaultEnabled::Enable => Some(true), common_enums::ExternalVaultEnabled::Skip => Some(false), }, None => Some(false), }; Self { profile_name, modified_at: now, return_url, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, webhook_details, metadata, routing_algorithm, intent_fulfillment_time, frm_routing_algorithm, payout_routing_algorithm, is_recon_enabled: None, applepay_verified_domains, payment_link_config, session_expiry, authentication_connector_details, payout_link_config, is_extended_card_info_enabled: None, extended_card_info_config, is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers .map(Encryption::from), always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector, tax_connector_id, is_tax_connector_enabled, is_l2_l3_enabled, dynamic_routing_algorithm, is_network_tokenization_enabled, is_auto_retries_enabled, max_auto_retries_enabled, always_request_extended_authorization, is_click_to_pay_enabled, authentication_product_ids, card_testing_guard_config, card_testing_secret_key: card_testing_secret_key.map(Encryption::from), is_clear_pan_retries_enabled, force_3ds_challenge, is_debit_routing_enabled, merchant_business_country, is_iframe_redirection_enabled, is_pre_network_tokenization_enabled, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, merchant_category_code, merchant_country_code, dispute_polling_interval, is_manual_retry_enabled, always_enable_overcapture, is_external_vault_enabled, external_vault_connector_details, billing_processor_id, } } ProfileUpdate::RoutingAlgorithmUpdate { routing_algorithm, payout_routing_algorithm, three_ds_decision_rule_algorithm, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, routing_algorithm, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, tax_connector_id: None, is_tax_connector_enabled: None, dynamic_routing_algorithm: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, always_request_extended_authorization: None, is_click_to_pay_enabled: None, authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, force_3ds_challenge: None, is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm, acquirer_config_map: None, merchant_category_code: None, merchant_country_code: None, dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, billing_processor_id: None, is_l2_l3_enabled: None, }, ProfileUpdate::DynamicRoutingAlgorithmUpdate { dynamic_routing_algorithm, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, routing_algorithm: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, tax_connector_id: None, is_tax_connector_enabled: None, dynamic_routing_algorithm, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, always_request_extended_authorization: None, is_click_to_pay_enabled: None, authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, force_3ds_challenge: None, is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, merchant_category_code: None, merchant_country_code: None, dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, billing_processor_id: None, is_l2_l3_enabled: None, }, ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, routing_algorithm: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: Some(is_extended_card_info_enabled), extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, tax_connector_id: None, is_tax_connector_enabled: None, dynamic_routing_algorithm: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, always_request_extended_authorization: None, is_click_to_pay_enabled: None, authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, force_3ds_challenge: None, is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, merchant_category_code: None, merchant_country_code: None, dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, billing_processor_id: None, is_l2_l3_enabled: None, }, ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, routing_algorithm: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: Some(is_connector_agnostic_mit_enabled), use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, tax_connector_id: None, is_tax_connector_enabled: None, dynamic_routing_algorithm: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, always_request_extended_authorization: None, is_click_to_pay_enabled: None, authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, force_3ds_challenge: None, is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, merchant_category_code: None, merchant_country_code: None, dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, billing_processor_id: None, is_l2_l3_enabled: None, }, ProfileUpdate::NetworkTokenizationUpdate { is_network_tokenization_enabled, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, routing_algorithm: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, tax_connector_id: None, is_tax_connector_enabled: None, dynamic_routing_algorithm: None, is_network_tokenization_enabled: Some(is_network_tokenization_enabled), is_auto_retries_enabled: None, max_auto_retries_enabled: None, always_request_extended_authorization: None, is_click_to_pay_enabled: None, authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, force_3ds_challenge: None, is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, merchant_category_code: None, merchant_country_code: None, dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, billing_processor_id: None, is_l2_l3_enabled: None, }, ProfileUpdate::CardTestingSecretKeyUpdate { card_testing_secret_key, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, routing_algorithm: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, tax_connector_id: None, is_tax_connector_enabled: None, dynamic_routing_algorithm: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, always_request_extended_authorization: None, is_click_to_pay_enabled: None, authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: card_testing_secret_key.map(Encryption::from), is_clear_pan_retries_enabled: None, force_3ds_challenge: None, is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, merchant_category_code: None, merchant_country_code: None, dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, billing_processor_id: None, is_l2_l3_enabled: None, }, ProfileUpdate::AcquirerConfigMapUpdate { acquirer_config_map, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, routing_algorithm: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, tax_connector_id: None, is_tax_connector_enabled: None, dynamic_routing_algorithm: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, always_request_extended_authorization: None, is_click_to_pay_enabled: None, authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, force_3ds_challenge: None, is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm: None, acquirer_config_map, merchant_category_code: None, merchant_country_code: None, dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, is_external_vault_enabled: None, external_vault_connector_details: None, billing_processor_id: None, is_l2_l3_enabled: None, }, } } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl Conversion for Profile { type DstType = diesel_models::business_profile::Profile; type NewDstType = diesel_models::business_profile::ProfileNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let (is_external_vault_enabled, external_vault_connector_details) = self.external_vault_details.into(); Ok(diesel_models::business_profile::Profile { profile_id: self.profile_id.clone(), id: Some(self.profile_id), merchant_id: self.merchant_id, profile_name: self.profile_name, created_at: self.created_at, modified_at: self.modified_at, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, webhook_details: self.webhook_details, metadata: self.metadata, routing_algorithm: self.routing_algorithm, intent_fulfillment_time: self.intent_fulfillment_time, frm_routing_algorithm: self.frm_routing_algorithm, payout_routing_algorithm: self.payout_routing_algorithm, is_recon_enabled: self.is_recon_enabled, applepay_verified_domains: self.applepay_verified_domains, payment_link_config: self.payment_link_config, session_expiry: self.session_expiry, authentication_connector_details: self.authentication_connector_details, payout_link_config: self.payout_link_config, is_extended_card_info_enabled: self.is_extended_card_info_enabled, extended_card_info_config: self.extended_card_info_config, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers: self .outgoing_webhook_custom_http_headers .map(Encryption::from), always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: Some(self.is_tax_connector_enabled), is_l2_l3_enabled: Some(self.is_l2_l3_enabled), version: self.version, dynamic_routing_algorithm: self.dynamic_routing_algorithm, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_auto_retries_enabled: Some(self.is_auto_retries_enabled), max_auto_retries_enabled: self.max_auto_retries_enabled, always_request_extended_authorization: self.always_request_extended_authorization, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, card_testing_guard_config: self.card_testing_guard_config, card_testing_secret_key: self.card_testing_secret_key.map(|name| name.into()), is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled, force_3ds_challenge: Some(self.force_3ds_challenge), is_debit_routing_enabled: self.is_debit_routing_enabled, merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, is_pre_network_tokenization_enabled: Some(self.is_pre_network_tokenization_enabled), three_ds_decision_rule_algorithm: self.three_ds_decision_rule_algorithm, acquirer_config_map: self.acquirer_config_map, merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, dispute_polling_interval: self.dispute_polling_interval, is_manual_retry_enabled: self.is_manual_retry_enabled, always_enable_overcapture: self.always_enable_overcapture, is_external_vault_enabled, external_vault_connector_details, billing_processor_id: self.billing_processor_id, }) } async fn convert_back( state: &keymanager::KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { // Decrypt encrypted fields first let (outgoing_webhook_custom_http_headers, card_testing_secret_key) = async { let outgoing_webhook_custom_http_headers = item .outgoing_webhook_custom_http_headers .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?; let card_testing_secret_key = item .card_testing_secret_key .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?; Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>(( outgoing_webhook_custom_http_headers, card_testing_secret_key, )) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting business profile data".to_string(), })?; let external_vault_details = ExternalVaultDetails::try_from(( item.is_external_vault_enabled, item.external_vault_connector_details, ))?; // Construct the domain type Ok(Self { profile_id: item.profile_id, merchant_id: item.merchant_id, profile_name: item.profile_name, created_at: item.created_at, modified_at: item.modified_at, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, webhook_details: item.webhook_details, metadata: item.metadata, routing_algorithm: item.routing_algorithm, intent_fulfillment_time: item.intent_fulfillment_time, frm_routing_algorithm: item.frm_routing_algorithm, payout_routing_algorithm: item.payout_routing_algorithm, is_recon_enabled: item.is_recon_enabled, applepay_verified_domains: item.applepay_verified_domains, payment_link_config: item.payment_link_config, session_expiry: item.session_expiry, authentication_connector_details: item.authentication_connector_details, payout_link_config: item.payout_link_config, is_extended_card_info_enabled: item.is_extended_card_info_enabled, extended_card_info_config: item.extended_card_info_config, is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: item .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: item .collect_billing_details_from_wallet_connector, always_collect_billing_details_from_wallet_connector: item .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: item .always_collect_shipping_details_from_wallet_connector, outgoing_webhook_custom_http_headers, tax_connector_id: item.tax_connector_id, is_tax_connector_enabled: item.is_tax_connector_enabled.unwrap_or(false), is_l2_l3_enabled: item.is_l2_l3_enabled.unwrap_or(false), version: item.version, dynamic_routing_algorithm: item.dynamic_routing_algorithm, is_network_tokenization_enabled: item.is_network_tokenization_enabled, is_auto_retries_enabled: item.is_auto_retries_enabled.unwrap_or(false), max_auto_retries_enabled: item.max_auto_retries_enabled, always_request_extended_authorization: item.always_request_extended_authorization, is_click_to_pay_enabled: item.is_click_to_pay_enabled, authentication_product_ids: item.authentication_product_ids, card_testing_guard_config: item.card_testing_guard_config, card_testing_secret_key, is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, force_3ds_challenge: item.force_3ds_challenge.unwrap_or_default(), is_debit_routing_enabled: item.is_debit_routing_enabled, merchant_business_country: item.merchant_business_country, is_iframe_redirection_enabled: item.is_iframe_redirection_enabled, is_pre_network_tokenization_enabled: item .is_pre_network_tokenization_enabled .unwrap_or(false), three_ds_decision_rule_algorithm: item.three_ds_decision_rule_algorithm, acquirer_config_map: item.acquirer_config_map, merchant_category_code: item.merchant_category_code, merchant_country_code: item.merchant_country_code, dispute_polling_interval: item.dispute_polling_interval, is_manual_retry_enabled: item.is_manual_retry_enabled, always_enable_overcapture: item.always_enable_overcapture, external_vault_details, billing_processor_id: item.billing_processor_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let (is_external_vault_enabled, external_vault_connector_details) = self.external_vault_details.into(); Ok(diesel_models::business_profile::ProfileNew { profile_id: self.profile_id.clone(), id: Some(self.profile_id), merchant_id: self.merchant_id, profile_name: self.profile_name, created_at: self.created_at, modified_at: self.modified_at, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, webhook_details: self.webhook_details, metadata: self.metadata, routing_algorithm: self.routing_algorithm, intent_fulfillment_time: self.intent_fulfillment_time, frm_routing_algorithm: self.frm_routing_algorithm, payout_routing_algorithm: self.payout_routing_algorithm, is_recon_enabled: self.is_recon_enabled, applepay_verified_domains: self.applepay_verified_domains, payment_link_config: self.payment_link_config, session_expiry: self.session_expiry, authentication_connector_details: self.authentication_connector_details, payout_link_config: self.payout_link_config, is_extended_card_info_enabled: self.is_extended_card_info_enabled, extended_card_info_config: self.extended_card_info_config, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers: self .outgoing_webhook_custom_http_headers .map(Encryption::from), always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: Some(self.is_tax_connector_enabled), is_l2_l3_enabled: Some(self.is_l2_l3_enabled), version: self.version, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_auto_retries_enabled: Some(self.is_auto_retries_enabled), max_auto_retries_enabled: self.max_auto_retries_enabled, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, card_testing_guard_config: self.card_testing_guard_config, card_testing_secret_key: self.card_testing_secret_key.map(Encryption::from), is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled, force_3ds_challenge: Some(self.force_3ds_challenge), is_debit_routing_enabled: self.is_debit_routing_enabled, merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, is_pre_network_tokenization_enabled: Some(self.is_pre_network_tokenization_enabled), merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, dispute_polling_interval: self.dispute_polling_interval, is_manual_retry_enabled: self.is_manual_retry_enabled, is_external_vault_enabled, external_vault_connector_details, billing_processor_id: self.billing_processor_id, }) } } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct Profile { id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_name: String, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<common_utils::types::Url>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub is_recon_enabled: bool, pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, pub should_collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: bool, pub version: common_enums::ApiVersion, pub is_network_tokenization_enabled: bool, pub is_click_to_pay_enabled: bool, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, pub is_clear_pan_retries_enabled: bool, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<api_enums::CountryAlpha2>, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>, pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub split_txns_enabled: common_enums::SplitTxnsEnabled, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] pub struct ProfileSetter { pub id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_name: String, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<common_utils::types::Url>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub is_recon_enabled: bool, pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, pub should_collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: bool, pub is_network_tokenization_enabled: bool, pub is_click_to_pay_enabled: bool, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, pub is_clear_pan_retries_enabled: bool, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<api_enums::CountryAlpha2>, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>, pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub split_txns_enabled: common_enums::SplitTxnsEnabled, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] impl From<ProfileSetter> for Profile { fn from(value: ProfileSetter) -> Self { Self { id: value.id, merchant_id: value.merchant_id, profile_name: value.profile_name, created_at: value.created_at, modified_at: value.modified_at, return_url: value.return_url, enable_payment_response_hash: value.enable_payment_response_hash, payment_response_hash_key: value.payment_response_hash_key, redirect_to_merchant_with_http_post: value.redirect_to_merchant_with_http_post, webhook_details: value.webhook_details, metadata: value.metadata, is_recon_enabled: value.is_recon_enabled, applepay_verified_domains: value.applepay_verified_domains, payment_link_config: value.payment_link_config, session_expiry: value.session_expiry, authentication_connector_details: value.authentication_connector_details, payout_link_config: value.payout_link_config, is_extended_card_info_enabled: value.is_extended_card_info_enabled, extended_card_info_config: value.extended_card_info_config, is_connector_agnostic_mit_enabled: value.is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing: value.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: value .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: value .collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers: value.outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector: value .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: value .always_collect_shipping_details_from_wallet_connector, routing_algorithm_id: value.routing_algorithm_id, order_fulfillment_time: value.order_fulfillment_time, order_fulfillment_time_origin: value.order_fulfillment_time_origin, frm_routing_algorithm_id: value.frm_routing_algorithm_id, payout_routing_algorithm_id: value.payout_routing_algorithm_id, default_fallback_routing: value.default_fallback_routing, should_collect_cvv_during_payment: value.should_collect_cvv_during_payment, tax_connector_id: value.tax_connector_id, is_tax_connector_enabled: value.is_tax_connector_enabled, version: common_types::consts::API_VERSION, is_network_tokenization_enabled: value.is_network_tokenization_enabled, is_click_to_pay_enabled: value.is_click_to_pay_enabled, authentication_product_ids: value.authentication_product_ids, three_ds_decision_manager_config: value.three_ds_decision_manager_config, card_testing_guard_config: value.card_testing_guard_config, card_testing_secret_key: value.card_testing_secret_key, is_clear_pan_retries_enabled: value.is_clear_pan_retries_enabled, is_debit_routing_enabled: value.is_debit_routing_enabled, merchant_business_country: value.merchant_business_country, revenue_recovery_retry_algorithm_type: value.revenue_recovery_retry_algorithm_type, revenue_recovery_retry_algorithm_data: value.revenue_recovery_retry_algorithm_data, is_iframe_redirection_enabled: value.is_iframe_redirection_enabled, is_external_vault_enabled: value.is_external_vault_enabled, external_vault_connector_details: value.external_vault_connector_details, merchant_category_code: value.merchant_category_code, merchant_country_code: value.merchant_country_code, split_txns_enabled: value.split_txns_enabled, billing_processor_id: value.billing_processor_id, } } } impl Profile { pub fn get_is_tax_connector_enabled(&self) -> bool { let is_tax_connector_enabled = self.is_tax_connector_enabled; match &self.tax_connector_id { Some(_id) => is_tax_connector_enabled, _ => false, } } #[cfg(feature = "v1")] pub fn get_order_fulfillment_time(&self) -> Option<i64> { self.intent_fulfillment_time } #[cfg(feature = "v2")] pub fn get_order_fulfillment_time(&self) -> Option<i64> { self.order_fulfillment_time } pub fn get_webhook_url_from_profile(&self) -> CustomResult<String, ValidationError> { self.webhook_details .clone() .and_then(|details| details.webhook_url) .get_required_value("webhook_details.webhook_url") .map(ExposeInterface::expose) } #[cfg(feature = "v2")] pub fn is_external_vault_enabled(&self) -> bool { self.is_external_vault_enabled.unwrap_or(false) } #[cfg(feature = "v2")] pub fn is_vault_sdk_enabled(&self) -> bool { self.external_vault_connector_details.is_some() } #[cfg(feature = "v1")] pub fn get_acquirer_details_from_network( &self, network: common_enums::CardNetwork, ) -> Option<AcquirerConfig> { // iterate over acquirer_config_map and find the acquirer config for the given network self.acquirer_config_map .as_ref() .and_then(|acquirer_config_map| { acquirer_config_map .0 .iter() .find(|&(_, acquirer_config)| acquirer_config.network == network) }) .map(|(_, acquirer_config)| acquirer_config.clone()) } #[cfg(feature = "v1")] pub fn get_payment_routing_algorithm( &self, ) -> CustomResult< Option<api_models::routing::RoutingAlgorithmRef>, api_error_response::ApiErrorResponse, > { self.routing_algorithm .clone() .map(|val| { val.parse_value::<api_models::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef") }) .transpose() .change_context(api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize routing algorithm ref from merchant account") } #[cfg(feature = "v1")] pub fn get_payout_routing_algorithm( &self, ) -> CustomResult< Option<api_models::routing::RoutingAlgorithmRef>, api_error_response::ApiErrorResponse, > { self.payout_routing_algorithm .clone() .map(|val| { val.parse_value::<api_models::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef") }) .transpose() .change_context(api_error_response::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize payout routing algorithm ref from merchant account", ) } #[cfg(feature = "v1")] pub fn get_frm_routing_algorithm( &self, ) -> CustomResult< Option<api_models::routing::RoutingAlgorithmRef>, api_error_response::ApiErrorResponse, > { self.frm_routing_algorithm .clone() .map(|val| { val.parse_value::<api_models::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef") }) .transpose() .change_context(api_error_response::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize frm routing algorithm ref from merchant account", ) } pub fn get_payment_webhook_statuses(&self) -> Cow<'_, [common_enums::IntentStatus]> { self.webhook_details .as_ref() .and_then(|details| details.payment_statuses_enabled.as_ref()) .filter(|statuses_vec| !statuses_vec.is_empty()) .map(|statuses_vec| Cow::Borrowed(statuses_vec.as_slice())) .unwrap_or_else(|| { Cow::Borrowed(common_types::consts::DEFAULT_PAYMENT_WEBHOOK_TRIGGER_STATUSES) }) } pub fn get_refund_webhook_statuses(&self) -> Cow<'_, [common_enums::RefundStatus]> { self.webhook_details .as_ref() .and_then(|details| details.refund_statuses_enabled.as_ref()) .filter(|statuses_vec| !statuses_vec.is_empty()) .map(|statuses_vec| Cow::Borrowed(statuses_vec.as_slice())) .unwrap_or_else(|| { Cow::Borrowed(common_types::consts::DEFAULT_REFUND_WEBHOOK_TRIGGER_STATUSES) }) } pub fn get_payout_webhook_statuses(&self) -> Cow<'_, [common_enums::PayoutStatus]> { self.webhook_details .as_ref() .and_then(|details| details.payout_statuses_enabled.as_ref()) .filter(|statuses_vec| !statuses_vec.is_empty()) .map(|statuses_vec| Cow::Borrowed(statuses_vec.as_slice())) .unwrap_or_else(|| { Cow::Borrowed(common_types::consts::DEFAULT_PAYOUT_WEBHOOK_TRIGGER_STATUSES) }) } pub fn get_billing_processor_id( &self, ) -> CustomResult< common_utils::id_type::MerchantConnectorAccountId, api_error_response::ApiErrorResponse, > { self.billing_processor_id .to_owned() .ok_or(error_stack::report!( api_error_response::ApiErrorResponse::MissingRequiredField { field_name: "billing_processor_id" } )) } } #[cfg(feature = "v2")] #[derive(Debug)] pub struct ProfileGeneralUpdate { pub profile_name: Option<String>, pub return_url: Option<common_utils::types::Url>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub is_network_tokenization_enabled: Option<bool>, pub is_click_to_pay_enabled: Option<bool>, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, pub is_debit_routing_enabled: Option<bool>, pub merchant_business_country: Option<api_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] #[derive(Debug)] pub enum ProfileUpdate { Update(Box<ProfileGeneralUpdate>), RoutingAlgorithmUpdate { routing_algorithm_id: Option<common_utils::id_type::RoutingId>, payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>, }, DefaultRoutingFallbackUpdate { default_fallback_routing: Option<pii::SecretSerdeValue>, }, ExtendedCardInfoUpdate { is_extended_card_info_enabled: bool, }, ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled: bool, }, NetworkTokenizationUpdate { is_network_tokenization_enabled: bool, }, CollectCvvDuringPaymentUpdate { should_collect_cvv_during_payment: primitive_wrappers::ShouldCollectCvvDuringPayment, }, DecisionManagerRecordUpdate { three_ds_decision_manager_config: common_types::payments::DecisionManagerRecord, }, CardTestingSecretKeyUpdate { card_testing_secret_key: OptionalEncryptableName, }, RevenueRecoveryAlgorithmUpdate { revenue_recovery_retry_algorithm_type: common_enums::RevenueRecoveryAlgorithmType, revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>, }, } #[cfg(feature = "v2")] impl From<ProfileUpdate> for ProfileUpdateInternal { fn from(profile_update: ProfileUpdate) -> Self { let now = date_time::now(); match profile_update { ProfileUpdate::Update(update) => { let ProfileGeneralUpdate { profile_name, return_url, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, webhook_details, metadata, applepay_verified_domains, payment_link_config, session_expiry, authentication_connector_details, payout_link_config, extended_card_info_config, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector, order_fulfillment_time, order_fulfillment_time_origin, is_network_tokenization_enabled, is_click_to_pay_enabled, authentication_product_ids, three_ds_decision_manager_config, card_testing_guard_config, card_testing_secret_key, is_debit_routing_enabled, merchant_business_country, is_iframe_redirection_enabled, is_external_vault_enabled, external_vault_connector_details, merchant_category_code, merchant_country_code, revenue_recovery_retry_algorithm_type, split_txns_enabled, billing_processor_id, } = *update; Self { profile_name, modified_at: now, return_url, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, webhook_details, metadata, is_recon_enabled: None, applepay_verified_domains, payment_link_config, session_expiry, authentication_connector_details, payout_link_config, is_extended_card_info_enabled: None, extended_card_info_config, is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers .map(Encryption::from), routing_algorithm_id: None, always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector, order_fulfillment_time, order_fulfillment_time_origin, frm_routing_algorithm_id: None, payout_routing_algorithm_id: None, default_fallback_routing: None, should_collect_cvv_during_payment: None, tax_connector_id: None, is_tax_connector_enabled: None, is_l2_l3_enabled: None, is_network_tokenization_enabled, is_auto_retries_enabled: None, max_auto_retries_enabled: None, is_click_to_pay_enabled, authentication_product_ids, three_ds_decision_manager_config, card_testing_guard_config, card_testing_secret_key: card_testing_secret_key.map(Encryption::from), is_clear_pan_retries_enabled: None, is_debit_routing_enabled, merchant_business_country, revenue_recovery_retry_algorithm_type, revenue_recovery_retry_algorithm_data: None, is_iframe_redirection_enabled, is_external_vault_enabled, external_vault_connector_details, merchant_category_code, merchant_country_code, split_txns_enabled, billing_processor_id, } } ProfileUpdate::RoutingAlgorithmUpdate { routing_algorithm_id, payout_routing_algorithm_id, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, routing_algorithm_id, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, order_fulfillment_time: None, order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, payout_routing_algorithm_id, default_fallback_routing: None, should_collect_cvv_during_payment: None, tax_connector_id: None, is_tax_connector_enabled: None, is_l2_l3_enabled: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, is_click_to_pay_enabled: None, authentication_product_ids: None, three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, billing_processor_id: None, }, ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: Some(is_extended_card_info_enabled), extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, routing_algorithm_id: None, payout_routing_algorithm_id: None, order_fulfillment_time: None, order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, default_fallback_routing: None, should_collect_cvv_during_payment: None, tax_connector_id: None, is_tax_connector_enabled: None, is_l2_l3_enabled: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, is_click_to_pay_enabled: None, authentication_product_ids: None, three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, billing_processor_id: None, }, ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, is_l2_l3_enabled: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: Some(is_connector_agnostic_mit_enabled), use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, routing_algorithm_id: None, payout_routing_algorithm_id: None, order_fulfillment_time: None, order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, default_fallback_routing: None, should_collect_cvv_during_payment: None, tax_connector_id: None, is_tax_connector_enabled: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, is_click_to_pay_enabled: None, authentication_product_ids: None, three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, billing_processor_id: None, }, ProfileUpdate::DefaultRoutingFallbackUpdate { default_fallback_routing, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, is_recon_enabled: None, applepay_verified_domains: None, is_l2_l3_enabled: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, routing_algorithm_id: None, payout_routing_algorithm_id: None, order_fulfillment_time: None, order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, default_fallback_routing, should_collect_cvv_during_payment: None, tax_connector_id: None, is_tax_connector_enabled: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, is_click_to_pay_enabled: None, authentication_product_ids: None, three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, billing_processor_id: None, }, ProfileUpdate::NetworkTokenizationUpdate { is_network_tokenization_enabled, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, is_l2_l3_enabled: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, routing_algorithm_id: None, payout_routing_algorithm_id: None, order_fulfillment_time: None, order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, default_fallback_routing: None, should_collect_cvv_during_payment: None, tax_connector_id: None, is_tax_connector_enabled: None, is_network_tokenization_enabled: Some(is_network_tokenization_enabled), is_auto_retries_enabled: None, max_auto_retries_enabled: None, is_click_to_pay_enabled: None, authentication_product_ids: None, three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, billing_processor_id: None, }, ProfileUpdate::CollectCvvDuringPaymentUpdate { should_collect_cvv_during_payment, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, routing_algorithm_id: None, payout_routing_algorithm_id: None, order_fulfillment_time: None, order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, default_fallback_routing: None, should_collect_cvv_during_payment: Some(should_collect_cvv_during_payment), tax_connector_id: None, is_tax_connector_enabled: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, is_click_to_pay_enabled: None, authentication_product_ids: None, is_l2_l3_enabled: None, three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, billing_processor_id: None, }, ProfileUpdate::DecisionManagerRecordUpdate { three_ds_decision_manager_config, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, routing_algorithm_id: None, payout_routing_algorithm_id: None, order_fulfillment_time: None, order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, default_fallback_routing: None, should_collect_cvv_during_payment: None, tax_connector_id: None, is_tax_connector_enabled: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, is_click_to_pay_enabled: None, authentication_product_ids: None, three_ds_decision_manager_config: Some(three_ds_decision_manager_config), card_testing_guard_config: None, card_testing_secret_key: None, is_l2_l3_enabled: None, is_clear_pan_retries_enabled: None, is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, billing_processor_id: None, }, ProfileUpdate::CardTestingSecretKeyUpdate { card_testing_secret_key, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, routing_algorithm_id: None, payout_routing_algorithm_id: None, order_fulfillment_time: None, order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, default_fallback_routing: None, should_collect_cvv_during_payment: None, tax_connector_id: None, is_tax_connector_enabled: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, is_click_to_pay_enabled: None, authentication_product_ids: None, three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: card_testing_secret_key.map(Encryption::from), is_clear_pan_retries_enabled: None, is_debit_routing_enabled: None, is_l2_l3_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, billing_processor_id: None, }, ProfileUpdate::RevenueRecoveryAlgorithmUpdate { revenue_recovery_retry_algorithm_type, revenue_recovery_retry_algorithm_data, } => Self { profile_name: None, modified_at: now, return_url: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, webhook_details: None, metadata: None, is_recon_enabled: None, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, routing_algorithm_id: None, is_l2_l3_enabled: None, payout_routing_algorithm_id: None, order_fulfillment_time: None, order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, default_fallback_routing: None, should_collect_cvv_during_payment: None, tax_connector_id: None, is_tax_connector_enabled: None, is_network_tokenization_enabled: None, is_auto_retries_enabled: None, max_auto_retries_enabled: None, is_click_to_pay_enabled: None, authentication_product_ids: None, three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: Some(revenue_recovery_retry_algorithm_type), revenue_recovery_retry_algorithm_data, is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, split_txns_enabled: None, billing_processor_id: None, }, } } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl Conversion for Profile { type DstType = diesel_models::business_profile::Profile; type NewDstType = diesel_models::business_profile::ProfileNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::business_profile::Profile { id: self.id, merchant_id: self.merchant_id, profile_name: self.profile_name, created_at: self.created_at, modified_at: self.modified_at, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, webhook_details: self.webhook_details, metadata: self.metadata, is_recon_enabled: self.is_recon_enabled, applepay_verified_domains: self.applepay_verified_domains, payment_link_config: self.payment_link_config, session_expiry: self.session_expiry, authentication_connector_details: self.authentication_connector_details, payout_link_config: self.payout_link_config, is_extended_card_info_enabled: self.is_extended_card_info_enabled, extended_card_info_config: self.extended_card_info_config, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers: self .outgoing_webhook_custom_http_headers .map(Encryption::from), routing_algorithm_id: self.routing_algorithm_id, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, payout_routing_algorithm_id: self.payout_routing_algorithm_id, order_fulfillment_time: self.order_fulfillment_time, order_fulfillment_time_origin: self.order_fulfillment_time_origin, frm_routing_algorithm_id: self.frm_routing_algorithm_id, default_fallback_routing: self.default_fallback_routing, should_collect_cvv_during_payment: self.should_collect_cvv_during_payment, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: Some(self.is_tax_connector_enabled), version: self.version, dynamic_routing_algorithm: None, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_auto_retries_enabled: None, max_auto_retries_enabled: None, always_request_extended_authorization: None, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, three_ds_decision_manager_config: self.three_ds_decision_manager_config, card_testing_guard_config: self.card_testing_guard_config, card_testing_secret_key: self.card_testing_secret_key.map(|name| name.into()), is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled, force_3ds_challenge: None, is_debit_routing_enabled: self.is_debit_routing_enabled, merchant_business_country: self.merchant_business_country, revenue_recovery_retry_algorithm_type: self.revenue_recovery_retry_algorithm_type, revenue_recovery_retry_algorithm_data: self.revenue_recovery_retry_algorithm_data, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, is_external_vault_enabled: self.is_external_vault_enabled, external_vault_connector_details: self.external_vault_connector_details, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, dispute_polling_interval: None, split_txns_enabled: Some(self.split_txns_enabled), is_manual_retry_enabled: None, is_l2_l3_enabled: None, always_enable_overcapture: None, billing_processor_id: self.billing_processor_id, }) } async fn convert_back( state: &keymanager::KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { async { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { id: item.id, merchant_id: item.merchant_id, profile_name: item.profile_name, created_at: item.created_at, modified_at: item.modified_at, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, webhook_details: item.webhook_details, metadata: item.metadata, is_recon_enabled: item.is_recon_enabled, applepay_verified_domains: item.applepay_verified_domains, payment_link_config: item.payment_link_config, session_expiry: item.session_expiry, authentication_connector_details: item.authentication_connector_details, payout_link_config: item.payout_link_config, is_extended_card_info_enabled: item.is_extended_card_info_enabled, extended_card_info_config: item.extended_card_info_config, is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: item .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: item .collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers: item .outgoing_webhook_custom_http_headers .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, routing_algorithm_id: item.routing_algorithm_id, always_collect_billing_details_from_wallet_connector: item .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: item .always_collect_shipping_details_from_wallet_connector, order_fulfillment_time: item.order_fulfillment_time, order_fulfillment_time_origin: item.order_fulfillment_time_origin, frm_routing_algorithm_id: item.frm_routing_algorithm_id, payout_routing_algorithm_id: item.payout_routing_algorithm_id, default_fallback_routing: item.default_fallback_routing, should_collect_cvv_during_payment: item.should_collect_cvv_during_payment, tax_connector_id: item.tax_connector_id, is_tax_connector_enabled: item.is_tax_connector_enabled.unwrap_or(false), version: item.version, is_network_tokenization_enabled: item.is_network_tokenization_enabled, is_click_to_pay_enabled: item.is_click_to_pay_enabled, authentication_product_ids: item.authentication_product_ids, three_ds_decision_manager_config: item.three_ds_decision_manager_config, card_testing_guard_config: item.card_testing_guard_config, card_testing_secret_key: match item.card_testing_secret_key { Some(encrypted_value) => crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(Some(encrypted_value)), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) .unwrap_or_default(), None => None, }, is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, is_debit_routing_enabled: item.is_debit_routing_enabled, merchant_business_country: item.merchant_business_country, revenue_recovery_retry_algorithm_type: item.revenue_recovery_retry_algorithm_type, revenue_recovery_retry_algorithm_data: item.revenue_recovery_retry_algorithm_data, is_iframe_redirection_enabled: item.is_iframe_redirection_enabled, is_external_vault_enabled: item.is_external_vault_enabled, external_vault_connector_details: item.external_vault_connector_details, merchant_category_code: item.merchant_category_code, merchant_country_code: item.merchant_country_code, split_txns_enabled: item.split_txns_enabled.unwrap_or_default(), billing_processor_id: item.billing_processor_id, }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting business profile data".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::business_profile::ProfileNew { id: self.id, merchant_id: self.merchant_id, profile_name: self.profile_name, created_at: self.created_at, modified_at: self.modified_at, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, webhook_details: self.webhook_details, metadata: self.metadata, is_recon_enabled: self.is_recon_enabled, applepay_verified_domains: self.applepay_verified_domains, payment_link_config: self.payment_link_config, session_expiry: self.session_expiry, authentication_connector_details: self.authentication_connector_details, payout_link_config: self.payout_link_config, is_extended_card_info_enabled: self.is_extended_card_info_enabled, extended_card_info_config: self.extended_card_info_config, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers: self .outgoing_webhook_custom_http_headers .map(Encryption::from), routing_algorithm_id: self.routing_algorithm_id, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, order_fulfillment_time: self.order_fulfillment_time, order_fulfillment_time_origin: self.order_fulfillment_time_origin, frm_routing_algorithm_id: self.frm_routing_algorithm_id, payout_routing_algorithm_id: self.payout_routing_algorithm_id, default_fallback_routing: self.default_fallback_routing, should_collect_cvv_during_payment: self.should_collect_cvv_during_payment, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: Some(self.is_tax_connector_enabled), version: self.version, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_auto_retries_enabled: None, max_auto_retries_enabled: None, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, three_ds_decision_manager_config: self.three_ds_decision_manager_config, card_testing_guard_config: self.card_testing_guard_config, card_testing_secret_key: self.card_testing_secret_key.map(Encryption::from), is_clear_pan_retries_enabled: Some(self.is_clear_pan_retries_enabled), is_debit_routing_enabled: self.is_debit_routing_enabled, merchant_business_country: self.merchant_business_country, revenue_recovery_retry_algorithm_type: self.revenue_recovery_retry_algorithm_type, revenue_recovery_retry_algorithm_data: self.revenue_recovery_retry_algorithm_data, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, is_external_vault_enabled: self.is_external_vault_enabled, external_vault_connector_details: self.external_vault_connector_details, merchant_category_code: self.merchant_category_code, is_l2_l3_enabled: None, merchant_country_code: self.merchant_country_code, split_txns_enabled: Some(self.split_txns_enabled), billing_processor_id: self.billing_processor_id, }) } } #[async_trait::async_trait] pub trait ProfileInterface where Profile: Conversion<DstType = storage_types::Profile, NewDstType = storage_types::ProfileNew>, { type Error; async fn insert_business_profile( &self, key_manager_state: &keymanager::KeyManagerState, merchant_key_store: &MerchantKeyStore, business_profile: Profile, ) -> CustomResult<Profile, Self::Error>; async fn find_business_profile_by_profile_id( &self, key_manager_state: &keymanager::KeyManagerState, merchant_key_store: &MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<Profile, Self::Error>; async fn find_business_profile_by_merchant_id_profile_id( &self, key_manager_state: &keymanager::KeyManagerState, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<Profile, Self::Error>; async fn find_business_profile_by_profile_name_merchant_id( &self, key_manager_state: &keymanager::KeyManagerState, merchant_key_store: &MerchantKeyStore, profile_name: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Profile, Self::Error>; async fn update_profile_by_profile_id( &self, key_manager_state: &keymanager::KeyManagerState, merchant_key_store: &MerchantKeyStore, current_state: Profile, profile_update: ProfileUpdate, ) -> CustomResult<Profile, Self::Error>; async fn delete_profile_by_profile_id_merchant_id( &self, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, Self::Error>; async fn list_profile_by_merchant_id( &self, key_manager_state: &keymanager::KeyManagerState, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Profile>, Self::Error>; }
crates/hyperswitch_domain_models/src/business_profile.rs
hyperswitch_domain_models::src::business_profile
23,277
true
// File: crates/hyperswitch_domain_models/src/invoice.rs // Module: hyperswitch_domain_models::src::invoice use common_utils::{ errors::{CustomResult, ValidationError}, id_type::GenerateId, pii::SecretSerdeValue, types::{ keymanager::{Identifier, KeyManagerState}, MinorUnit, }, }; use masking::{PeekInterface, Secret}; use utoipa::ToSchema; use crate::merchant_key_store::MerchantKeyStore; #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct Invoice { pub id: common_utils::id_type::InvoiceId, pub subscription_id: common_utils::id_type::SubscriptionId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_id: common_utils::id_type::ProfileId, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, pub payment_intent_id: Option<common_utils::id_type::PaymentId>, pub payment_method_id: Option<String>, pub customer_id: common_utils::id_type::CustomerId, pub amount: MinorUnit, pub currency: String, pub status: common_enums::connector_enums::InvoiceStatus, pub provider_name: common_enums::connector_enums::Connector, pub metadata: Option<SecretSerdeValue>, pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, } #[async_trait::async_trait] impl super::behaviour::Conversion for Invoice { type DstType = diesel_models::invoice::Invoice; type NewDstType = diesel_models::invoice::InvoiceNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let now = common_utils::date_time::now(); Ok(diesel_models::invoice::Invoice { id: self.id, subscription_id: self.subscription_id, merchant_id: self.merchant_id, profile_id: self.profile_id, merchant_connector_id: self.merchant_connector_id, payment_intent_id: self.payment_intent_id, payment_method_id: self.payment_method_id, customer_id: self.customer_id, amount: self.amount, currency: self.currency.to_string(), status: self.status, provider_name: self.provider_name, metadata: None, created_at: now, modified_at: now, connector_invoice_id: self.connector_invoice_id, }) } async fn convert_back( _state: &KeyManagerState, item: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { Ok(Self { id: item.id, subscription_id: item.subscription_id, merchant_id: item.merchant_id, profile_id: item.profile_id, merchant_connector_id: item.merchant_connector_id, payment_intent_id: item.payment_intent_id, payment_method_id: item.payment_method_id, customer_id: item.customer_id, amount: item.amount, currency: item.currency, status: item.status, provider_name: item.provider_name, metadata: item.metadata, connector_invoice_id: item.connector_invoice_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::invoice::InvoiceNew::new( self.subscription_id, self.merchant_id, self.profile_id, self.merchant_connector_id, self.payment_intent_id, self.payment_method_id, self.customer_id, self.amount, self.currency.to_string(), self.status, self.provider_name, None, self.connector_invoice_id, )) } } impl Invoice { #[allow(clippy::too_many_arguments)] pub fn to_invoice( subscription_id: common_utils::id_type::SubscriptionId, merchant_id: common_utils::id_type::MerchantId, profile_id: common_utils::id_type::ProfileId, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, payment_intent_id: Option<common_utils::id_type::PaymentId>, payment_method_id: Option<String>, customer_id: common_utils::id_type::CustomerId, amount: MinorUnit, currency: String, status: common_enums::connector_enums::InvoiceStatus, provider_name: common_enums::connector_enums::Connector, metadata: Option<SecretSerdeValue>, connector_invoice_id: Option<common_utils::id_type::InvoiceId>, ) -> Self { Self { id: common_utils::id_type::InvoiceId::generate(), subscription_id, merchant_id, profile_id, merchant_connector_id, payment_intent_id, payment_method_id, customer_id, amount, currency: currency.to_string(), status, provider_name, metadata, connector_invoice_id, } } } #[async_trait::async_trait] pub trait InvoiceInterface { type Error; async fn insert_invoice_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, invoice_new: Invoice, ) -> CustomResult<Invoice, Self::Error>; async fn find_invoice_by_invoice_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, invoice_id: String, ) -> CustomResult<Invoice, Self::Error>; async fn update_invoice_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, invoice_id: String, data: InvoiceUpdate, ) -> CustomResult<Invoice, Self::Error>; async fn get_latest_invoice_for_subscription( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_id: String, ) -> CustomResult<Invoice, Self::Error>; async fn find_invoice_by_subscription_id_connector_invoice_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_id: String, connector_invoice_id: common_utils::id_type::InvoiceId, ) -> CustomResult<Option<Invoice>, Self::Error>; } pub struct InvoiceUpdate { pub status: Option<common_enums::connector_enums::InvoiceStatus>, pub payment_method_id: Option<String>, pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, pub modified_at: time::PrimitiveDateTime, pub payment_intent_id: Option<common_utils::id_type::PaymentId>, pub amount: Option<MinorUnit>, pub currency: Option<String>, } #[derive(Debug, Clone)] pub struct AmountAndCurrencyUpdate { pub amount: MinorUnit, pub currency: String, } #[derive(Debug, Clone)] pub struct ConnectorAndStatusUpdate { pub connector_invoice_id: common_utils::id_type::InvoiceId, pub status: common_enums::connector_enums::InvoiceStatus, } #[derive(Debug, Clone)] pub struct PaymentAndStatusUpdate { pub payment_method_id: Option<Secret<String>>, pub payment_intent_id: Option<common_utils::id_type::PaymentId>, pub status: common_enums::connector_enums::InvoiceStatus, pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, } /// Enum-based invoice update request for different scenarios #[derive(Debug, Clone)] pub enum InvoiceUpdateRequest { /// Update amount and currency Amount(AmountAndCurrencyUpdate), /// Update connector invoice ID and status Connector(ConnectorAndStatusUpdate), /// Update payment details along with status PaymentStatus(PaymentAndStatusUpdate), } impl InvoiceUpdateRequest { /// Create an amount and currency update request pub fn update_amount_and_currency(amount: MinorUnit, currency: String) -> Self { Self::Amount(AmountAndCurrencyUpdate { amount, currency }) } /// Create a connector invoice ID and status update request pub fn update_connector_and_status( connector_invoice_id: common_utils::id_type::InvoiceId, status: common_enums::connector_enums::InvoiceStatus, ) -> Self { Self::Connector(ConnectorAndStatusUpdate { connector_invoice_id, status, }) } /// Create a combined payment and status update request pub fn update_payment_and_status( payment_method_id: Option<Secret<String>>, payment_intent_id: Option<common_utils::id_type::PaymentId>, status: common_enums::connector_enums::InvoiceStatus, connector_invoice_id: Option<common_utils::id_type::InvoiceId>, ) -> Self { Self::PaymentStatus(PaymentAndStatusUpdate { payment_method_id, payment_intent_id, status, connector_invoice_id, }) } } impl From<InvoiceUpdateRequest> for InvoiceUpdate { fn from(request: InvoiceUpdateRequest) -> Self { let now = common_utils::date_time::now(); match request { InvoiceUpdateRequest::Amount(update) => Self { status: None, payment_method_id: None, connector_invoice_id: None, modified_at: now, payment_intent_id: None, amount: Some(update.amount), currency: Some(update.currency), }, InvoiceUpdateRequest::Connector(update) => Self { status: Some(update.status), payment_method_id: None, connector_invoice_id: Some(update.connector_invoice_id), modified_at: now, payment_intent_id: None, amount: None, currency: None, }, InvoiceUpdateRequest::PaymentStatus(update) => Self { status: Some(update.status), payment_method_id: update .payment_method_id .as_ref() .map(|id| id.peek()) .cloned(), connector_invoice_id: update.connector_invoice_id, modified_at: now, payment_intent_id: update.payment_intent_id, amount: None, currency: None, }, } } } #[async_trait::async_trait] impl super::behaviour::Conversion for InvoiceUpdate { type DstType = diesel_models::invoice::InvoiceUpdate; type NewDstType = diesel_models::invoice::InvoiceUpdate; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::invoice::InvoiceUpdate { status: self.status, payment_method_id: self.payment_method_id, connector_invoice_id: self.connector_invoice_id, modified_at: self.modified_at, payment_intent_id: self.payment_intent_id, amount: self.amount, currency: self.currency, }) } async fn convert_back( _state: &KeyManagerState, item: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { Ok(Self { status: item.status, payment_method_id: item.payment_method_id, connector_invoice_id: item.connector_invoice_id, modified_at: item.modified_at, payment_intent_id: item.payment_intent_id, amount: item.amount, currency: item.currency, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::invoice::InvoiceUpdate { status: self.status, payment_method_id: self.payment_method_id, connector_invoice_id: self.connector_invoice_id, modified_at: self.modified_at, payment_intent_id: self.payment_intent_id, amount: self.amount, currency: self.currency, }) } } impl InvoiceUpdate { pub fn new( payment_method_id: Option<String>, status: Option<common_enums::connector_enums::InvoiceStatus>, connector_invoice_id: Option<common_utils::id_type::InvoiceId>, payment_intent_id: Option<common_utils::id_type::PaymentId>, amount: Option<MinorUnit>, currency: Option<String>, ) -> Self { Self { status, payment_method_id, connector_invoice_id, modified_at: common_utils::date_time::now(), payment_intent_id, amount, currency, } } }
crates/hyperswitch_domain_models/src/invoice.rs
hyperswitch_domain_models::src::invoice
2,611
true
// File: crates/hyperswitch_domain_models/src/errors.rs // Module: hyperswitch_domain_models::src::errors pub mod api_error_response;
crates/hyperswitch_domain_models/src/errors.rs
hyperswitch_domain_models::src::errors
32
true
// File: crates/hyperswitch_domain_models/src/card_testing_guard_data.rs // Module: hyperswitch_domain_models::src::card_testing_guard_data use serde::{self, Deserialize, Serialize}; #[derive(Clone, Serialize, Deserialize, Debug)] pub struct CardTestingGuardData { pub is_card_ip_blocking_enabled: bool, pub card_ip_blocking_cache_key: String, pub is_guest_user_card_blocking_enabled: bool, pub guest_user_card_blocking_cache_key: String, pub is_customer_id_blocking_enabled: bool, pub customer_id_blocking_cache_key: String, pub card_testing_guard_expiry: i32, }
crates/hyperswitch_domain_models/src/card_testing_guard_data.rs
hyperswitch_domain_models::src::card_testing_guard_data
132
true
// File: crates/hyperswitch_domain_models/src/customer.rs // Module: hyperswitch_domain_models::src::customer use common_enums::enums::MerchantStorageScheme; #[cfg(feature = "v2")] use common_enums::DeleteStatus; use common_utils::{ crypto::{self, Encryptable}, date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, ext_traits::ValueExt, id_type, pii, types::{ keymanager::{self, KeyManagerState, ToEncryptable}, Description, }, }; use diesel_models::{ customers as storage_types, customers::CustomerUpdateInternal, query::customers as query, }; use error_stack::ResultExt; use masking::{ExposeOptionInterface, PeekInterface, Secret, SwitchStrategy}; use router_env::{instrument, tracing}; use rustc_hash::FxHashMap; use time::PrimitiveDateTime; #[cfg(feature = "v2")] use crate::merchant_connector_account::MerchantConnectorAccountTypeDetails; use crate::{behaviour, merchant_key_store::MerchantKeyStore, type_encryption as types}; #[cfg(feature = "v1")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct Customer { pub customer_id: id_type::CustomerId, pub merchant_id: id_type::MerchantId, #[encrypt] pub name: Option<Encryptable<Secret<String>>>, #[encrypt] pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>, #[encrypt] pub phone: Option<Encryptable<Secret<String>>>, pub phone_country_code: Option<String>, pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, pub connector_customer: Option<pii::SecretSerdeValue>, pub address_id: Option<String>, pub default_payment_method_id: Option<String>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, #[encrypt] pub tax_registration_id: Option<Encryptable<Secret<String>>>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct Customer { pub merchant_id: id_type::MerchantId, #[encrypt] pub name: Option<Encryptable<Secret<String>>>, #[encrypt] pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>, #[encrypt] pub phone: Option<Encryptable<Secret<String>>>, pub phone_country_code: Option<String>, pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>, pub modified_at: PrimitiveDateTime, pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, pub updated_by: Option<String>, pub merchant_reference_id: Option<id_type::CustomerId>, pub default_billing_address: Option<Encryption>, pub default_shipping_address: Option<Encryption>, pub id: id_type::GlobalCustomerId, pub version: common_enums::ApiVersion, pub status: DeleteStatus, #[encrypt] pub tax_registration_id: Option<Encryptable<Secret<String>>>, } impl Customer { /// Get the unique identifier of Customer #[cfg(feature = "v1")] pub fn get_id(&self) -> &id_type::CustomerId { &self.customer_id } /// Get the global identifier of Customer #[cfg(feature = "v2")] pub fn get_id(&self) -> &id_type::GlobalCustomerId { &self.id } /// Get the connector customer ID for the specified connector label, if present #[cfg(feature = "v1")] pub fn get_connector_customer_map( &self, ) -> FxHashMap<id_type::MerchantConnectorAccountId, String> { use masking::PeekInterface; if let Some(connector_customer_value) = &self.connector_customer { connector_customer_value .peek() .clone() .parse_value("ConnectorCustomerMap") .unwrap_or_default() } else { FxHashMap::default() } } /// Get the connector customer ID for the specified connector label, if present #[cfg(feature = "v1")] pub fn get_connector_customer_id(&self, connector_label: &str) -> Option<&str> { use masking::PeekInterface; self.connector_customer .as_ref() .and_then(|connector_customer_value| { connector_customer_value.peek().get(connector_label) }) .and_then(|connector_customer| connector_customer.as_str()) } /// Get the connector customer ID for the specified merchant connector account ID, if present #[cfg(feature = "v2")] pub fn get_connector_customer_id( &self, merchant_connector_account: &MerchantConnectorAccountTypeDetails, ) -> Option<&str> { match merchant_connector_account { MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(account) => { let connector_account_id = account.get_id(); self.connector_customer .as_ref()? .get(&connector_account_id) .map(|connector_customer_id| connector_customer_id.as_str()) } MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None, } } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl behaviour::Conversion for Customer { type DstType = diesel_models::customers::Customer; type NewDstType = diesel_models::customers::CustomerNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::customers::Customer { customer_id: self.customer_id, merchant_id: self.merchant_id, name: self.name.map(Encryption::from), email: self.email.map(Encryption::from), phone: self.phone.map(Encryption::from), phone_country_code: self.phone_country_code, description: self.description, created_at: self.created_at, metadata: self.metadata, modified_at: self.modified_at, connector_customer: self.connector_customer, address_id: self.address_id, default_payment_method_id: self.default_payment_method_id, updated_by: self.updated_by, version: self.version, tax_registration_id: self.tax_registration_id.map(Encryption::from), }) } async fn convert_back( state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, _key_store_ref_id: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let decrypted = types::crypto_operation( state, common_utils::type_name!(Self::DstType), types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable( EncryptedCustomer { name: item.name.clone(), phone: item.phone.clone(), email: item.email.clone(), tax_registration_id: item.tax_registration_id.clone(), }, )), keymanager::Identifier::Merchant(item.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), })?; let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context( ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), }, )?; Ok(Self { customer_id: item.customer_id, merchant_id: item.merchant_id, name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, phone_country_code: item.phone_country_code, description: item.description, created_at: item.created_at, metadata: item.metadata, modified_at: item.modified_at, connector_customer: item.connector_customer, address_id: item.address_id, default_payment_method_id: item.default_payment_method_id, updated_by: item.updated_by, version: item.version, tax_registration_id: encryptable_customer.tax_registration_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(diesel_models::customers::CustomerNew { customer_id: self.customer_id, merchant_id: self.merchant_id, name: self.name.map(Encryption::from), email: self.email.map(Encryption::from), phone: self.phone.map(Encryption::from), description: self.description, phone_country_code: self.phone_country_code, metadata: self.metadata, created_at: now, modified_at: now, connector_customer: self.connector_customer, address_id: self.address_id, updated_by: self.updated_by, version: self.version, tax_registration_id: self.tax_registration_id.map(Encryption::from), }) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl behaviour::Conversion for Customer { type DstType = diesel_models::customers::Customer; type NewDstType = diesel_models::customers::CustomerNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::customers::Customer { id: self.id, merchant_reference_id: self.merchant_reference_id, merchant_id: self.merchant_id, name: self.name.map(Encryption::from), email: self.email.map(Encryption::from), phone: self.phone.map(Encryption::from), phone_country_code: self.phone_country_code, description: self.description, created_at: self.created_at, metadata: self.metadata, modified_at: self.modified_at, connector_customer: self.connector_customer, default_payment_method_id: self.default_payment_method_id, updated_by: self.updated_by, default_billing_address: self.default_billing_address, default_shipping_address: self.default_shipping_address, version: self.version, status: self.status, tax_registration_id: self.tax_registration_id.map(Encryption::from), }) } async fn convert_back( state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, _key_store_ref_id: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let decrypted = types::crypto_operation( state, common_utils::type_name!(Self::DstType), types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable( EncryptedCustomer { name: item.name.clone(), phone: item.phone.clone(), email: item.email.clone(), tax_registration_id: item.tax_registration_id.clone(), }, )), keymanager::Identifier::Merchant(item.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), })?; let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context( ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), }, )?; Ok(Self { id: item.id, merchant_reference_id: item.merchant_reference_id, merchant_id: item.merchant_id, name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, phone_country_code: item.phone_country_code, description: item.description, created_at: item.created_at, metadata: item.metadata, modified_at: item.modified_at, connector_customer: item.connector_customer, default_payment_method_id: item.default_payment_method_id, updated_by: item.updated_by, default_billing_address: item.default_billing_address, default_shipping_address: item.default_shipping_address, version: item.version, status: item.status, tax_registration_id: encryptable_customer.tax_registration_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(diesel_models::customers::CustomerNew { id: self.id, merchant_reference_id: self.merchant_reference_id, merchant_id: self.merchant_id, name: self.name.map(Encryption::from), email: self.email.map(Encryption::from), phone: self.phone.map(Encryption::from), description: self.description, phone_country_code: self.phone_country_code, metadata: self.metadata, default_payment_method_id: None, created_at: now, modified_at: now, connector_customer: self.connector_customer, updated_by: self.updated_by, default_billing_address: self.default_billing_address, default_shipping_address: self.default_shipping_address, version: common_types::consts::API_VERSION, status: self.status, tax_registration_id: self.tax_registration_id.map(Encryption::from), }) } } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct CustomerGeneralUpdate { pub name: crypto::OptionalEncryptableName, pub email: Box<crypto::OptionalEncryptableEmail>, pub phone: Box<crypto::OptionalEncryptablePhone>, pub description: Option<Description>, pub phone_country_code: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Box<Option<common_types::customers::ConnectorCustomerMap>>, pub default_billing_address: Option<Encryption>, pub default_shipping_address: Option<Encryption>, pub default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>, pub status: Option<DeleteStatus>, pub tax_registration_id: crypto::OptionalEncryptableSecretString, } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub enum CustomerUpdate { Update(Box<CustomerGeneralUpdate>), ConnectorCustomer { connector_customer: Option<common_types::customers::ConnectorCustomerMap>, }, UpdateDefaultPaymentMethod { default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>, }, } #[cfg(feature = "v2")] impl From<CustomerUpdate> for CustomerUpdateInternal { fn from(customer_update: CustomerUpdate) -> Self { match customer_update { CustomerUpdate::Update(update) => { let CustomerGeneralUpdate { name, email, phone, description, phone_country_code, metadata, connector_customer, default_billing_address, default_shipping_address, default_payment_method_id, status, tax_registration_id, } = *update; Self { name: name.map(Encryption::from), email: email.map(Encryption::from), phone: phone.map(Encryption::from), description, phone_country_code, metadata, connector_customer: *connector_customer, modified_at: date_time::now(), default_billing_address, default_shipping_address, default_payment_method_id, updated_by: None, status, tax_registration_id: tax_registration_id.map(Encryption::from), } } CustomerUpdate::ConnectorCustomer { connector_customer } => Self { connector_customer, name: None, email: None, phone: None, description: None, phone_country_code: None, metadata: None, modified_at: date_time::now(), default_payment_method_id: None, updated_by: None, default_billing_address: None, default_shipping_address: None, status: None, tax_registration_id: None, }, CustomerUpdate::UpdateDefaultPaymentMethod { default_payment_method_id, } => Self { default_payment_method_id, modified_at: date_time::now(), name: None, email: None, phone: None, description: None, phone_country_code: None, metadata: None, connector_customer: None, updated_by: None, default_billing_address: None, default_shipping_address: None, status: None, tax_registration_id: None, }, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub enum CustomerUpdate { Update { name: crypto::OptionalEncryptableName, email: crypto::OptionalEncryptableEmail, phone: Box<crypto::OptionalEncryptablePhone>, description: Option<Description>, phone_country_code: Option<String>, metadata: Box<Option<pii::SecretSerdeValue>>, connector_customer: Box<Option<pii::SecretSerdeValue>>, address_id: Option<String>, tax_registration_id: crypto::OptionalEncryptableSecretString, }, ConnectorCustomer { connector_customer: Option<pii::SecretSerdeValue>, }, UpdateDefaultPaymentMethod { default_payment_method_id: Option<Option<String>>, }, } #[cfg(feature = "v1")] impl From<CustomerUpdate> for CustomerUpdateInternal { fn from(customer_update: CustomerUpdate) -> Self { match customer_update { CustomerUpdate::Update { name, email, phone, description, phone_country_code, metadata, connector_customer, address_id, tax_registration_id, } => Self { name: name.map(Encryption::from), email: email.map(Encryption::from), phone: phone.map(Encryption::from), description, phone_country_code, metadata: *metadata, connector_customer: *connector_customer, modified_at: date_time::now(), address_id, default_payment_method_id: None, updated_by: None, tax_registration_id: tax_registration_id.map(Encryption::from), }, CustomerUpdate::ConnectorCustomer { connector_customer } => Self { connector_customer, modified_at: date_time::now(), name: None, email: None, phone: None, description: None, phone_country_code: None, metadata: None, default_payment_method_id: None, updated_by: None, address_id: None, tax_registration_id: None, }, CustomerUpdate::UpdateDefaultPaymentMethod { default_payment_method_id, } => Self { default_payment_method_id, modified_at: date_time::now(), name: None, email: None, phone: None, description: None, phone_country_code: None, metadata: None, connector_customer: None, updated_by: None, address_id: None, tax_registration_id: None, }, } } } pub struct CustomerListConstraints { pub limit: u16, pub offset: Option<u32>, pub customer_id: Option<id_type::CustomerId>, pub time_range: Option<common_utils::types::TimeRange>, } impl From<CustomerListConstraints> for query::CustomerListConstraints { fn from(value: CustomerListConstraints) -> Self { Self { limit: i64::from(value.limit), offset: value.offset.map(i64::from), customer_id: value.customer_id, time_range: value.time_range, } } } #[async_trait::async_trait] pub trait CustomerInterface where Customer: behaviour::Conversion< DstType = storage_types::Customer, NewDstType = storage_types::CustomerNew, >, { type Error; #[cfg(feature = "v1")] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, Self::Error>; #[cfg(feature = "v1")] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<Customer>, Self::Error>; #[cfg(feature = "v1")] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<Customer>, Self::Error>; #[cfg(feature = "v2")] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<Customer>, Self::Error>; #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn update_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, customer: Customer, customer_update: CustomerUpdate, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; #[cfg(feature = "v1")] async fn find_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; #[cfg(feature = "v2")] async fn find_customer_by_merchant_reference_id_merchant_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: CustomerListConstraints, ) -> CustomResult<Vec<Customer>, Self::Error>; async fn list_customers_by_merchant_id_with_count( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: CustomerListConstraints, ) -> CustomResult<(Vec<Customer>, usize), Self::Error>; async fn insert_customer( &self, customer_data: Customer, state: &KeyManagerState, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn update_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: Customer, customer_update: CustomerUpdate, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; #[cfg(feature = "v2")] async fn find_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; } #[cfg(feature = "v1")] #[instrument] pub async fn update_connector_customer_in_customers( connector_label: &str, customer: Option<&Customer>, connector_customer_id: Option<String>, ) -> Option<CustomerUpdate> { let mut connector_customer_map = customer .and_then(|customer| customer.connector_customer.clone().expose_option()) .and_then(|connector_customer| connector_customer.as_object().cloned()) .unwrap_or_default(); let updated_connector_customer_map = connector_customer_id.map(|connector_customer_id| { let connector_customer_value = serde_json::Value::String(connector_customer_id); connector_customer_map.insert(connector_label.to_string(), connector_customer_value); connector_customer_map }); updated_connector_customer_map .map(serde_json::Value::Object) .map( |connector_customer_value| CustomerUpdate::ConnectorCustomer { connector_customer: Some(pii::SecretSerdeValue::new(connector_customer_value)), }, ) } #[cfg(feature = "v2")] #[instrument] pub async fn update_connector_customer_in_customers( merchant_connector_account: &MerchantConnectorAccountTypeDetails, customer: Option<&Customer>, connector_customer_id: Option<String>, ) -> Option<CustomerUpdate> { match merchant_connector_account { MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(account) => { connector_customer_id.map(|new_conn_cust_id| { let connector_account_id = account.get_id().clone(); let mut connector_customer_map = customer .and_then(|customer| customer.connector_customer.clone()) .unwrap_or_default(); connector_customer_map.insert(connector_account_id, new_conn_cust_id); CustomerUpdate::ConnectorCustomer { connector_customer: Some(connector_customer_map), } }) } // TODO: Construct connector_customer for MerchantConnectorDetails if required by connector. MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { todo!("Handle connector_customer construction for MerchantConnectorDetails"); } } }
crates/hyperswitch_domain_models/src/customer.rs
hyperswitch_domain_models::src::customer
5,623
true
// File: crates/hyperswitch_domain_models/src/router_response_types.rs // Module: hyperswitch_domain_models::src::router_response_types pub mod disputes; pub mod fraud_check; pub mod revenue_recovery; pub mod subscriptions; use std::collections::HashMap; use api_models::payments::AddressDetails; use common_utils::{pii, request::Method, types::MinorUnit}; pub use disputes::{ AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, SubmitEvidenceResponse, }; use serde::Serialize; use crate::{ errors::api_error_response::ApiErrorResponse, router_request_types::{authentication::AuthNFlowType, ResponseId}, vault::PaymentMethodVaultingData, }; #[derive(Debug, Clone)] pub struct RefundsResponseData { pub connector_refund_id: String, pub refund_status: common_enums::RefundStatus, // pub amount_received: Option<i32>, // Calculation for amount received not in place yet } #[derive(Debug, Clone, Serialize)] pub struct ConnectorCustomerResponseData { pub connector_customer_id: String, pub name: Option<String>, pub email: Option<String>, pub billing_address: Option<AddressDetails>, } impl ConnectorCustomerResponseData { pub fn new_with_customer_id(connector_customer_id: String) -> Self { Self::new(connector_customer_id, None, None, None) } pub fn new( connector_customer_id: String, name: Option<String>, email: Option<String>, billing_address: Option<AddressDetails>, ) -> Self { Self { connector_customer_id, name, email, billing_address, } } } #[derive(Debug, Clone, Serialize)] pub enum PaymentsResponseData { TransactionResponse { resource_id: ResponseId, redirection_data: Box<Option<RedirectForm>>, mandate_reference: Box<Option<MandateReference>>, connector_metadata: Option<serde_json::Value>, network_txn_id: Option<String>, connector_response_reference_id: Option<String>, incremental_authorization_allowed: Option<bool>, charges: Option<common_types::payments::ConnectorChargeResponseData>, }, MultipleCaptureResponse { // pending_capture_id_list: Vec<String>, capture_sync_response_list: HashMap<String, CaptureSyncResponse>, }, SessionResponse { session_token: api_models::payments::SessionToken, }, SessionTokenResponse { session_token: String, }, TransactionUnresolvedResponse { resource_id: ResponseId, //to add more info on cypto response, like `unresolved` reason(overpaid, underpaid, delayed) reason: Option<api_models::enums::UnresolvedResponseReason>, connector_response_reference_id: Option<String>, }, TokenizationResponse { token: String, }, ConnectorCustomerResponse(ConnectorCustomerResponseData), ThreeDSEnrollmentResponse { enrolled_v2: bool, related_transaction_id: Option<String>, }, PreProcessingResponse { pre_processing_id: PreprocessingResponseId, connector_metadata: Option<serde_json::Value>, session_token: Option<api_models::payments::SessionToken>, connector_response_reference_id: Option<String>, }, IncrementalAuthorizationResponse { status: common_enums::AuthorizationStatus, connector_authorization_id: Option<String>, error_code: Option<String>, error_message: Option<String>, }, PostProcessingResponse { session_token: Option<api_models::payments::OpenBankingSessionToken>, }, PaymentResourceUpdateResponse { status: common_enums::PaymentResourceUpdateStatus, }, PaymentsCreateOrderResponse { order_id: String, }, } #[derive(Debug, Clone)] pub struct GiftCardBalanceCheckResponseData { pub balance: MinorUnit, pub currency: common_enums::Currency, } #[derive(Debug, Clone)] pub struct TaxCalculationResponseData { pub order_tax_amount: MinorUnit, } #[derive(Serialize, Debug, Clone)] pub struct MandateReference { pub connector_mandate_id: Option<String>, pub payment_method_id: Option<String>, pub mandate_metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_request_reference_id: Option<String>, } #[derive(Debug, Clone, Serialize)] pub enum CaptureSyncResponse { Success { resource_id: ResponseId, status: common_enums::AttemptStatus, connector_response_reference_id: Option<String>, amount: Option<MinorUnit>, }, Error { code: String, message: String, reason: Option<String>, status_code: u16, amount: Option<MinorUnit>, }, } impl CaptureSyncResponse { pub fn get_amount_captured(&self) -> Option<MinorUnit> { match self { Self::Success { amount, .. } | Self::Error { amount, .. } => *amount, } } pub fn get_connector_response_reference_id(&self) -> Option<String> { match self { Self::Success { connector_response_reference_id, .. } => connector_response_reference_id.clone(), Self::Error { .. } => None, } } } impl PaymentsResponseData { pub fn get_connector_metadata(&self) -> Option<masking::Secret<serde_json::Value>> { match self { Self::TransactionResponse { connector_metadata, .. } | Self::PreProcessingResponse { connector_metadata, .. } => connector_metadata.clone().map(masking::Secret::new), _ => None, } } pub fn get_network_transaction_id(&self) -> Option<String> { match self { Self::TransactionResponse { network_txn_id, .. } => network_txn_id.clone(), _ => None, } } pub fn get_connector_transaction_id( &self, ) -> Result<String, error_stack::Report<ApiErrorResponse>> { match self { Self::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(txn_id), .. } => Ok(txn_id.to_string()), _ => Err(ApiErrorResponse::MissingRequiredField { field_name: "ConnectorTransactionId", } .into()), } } pub fn merge_transaction_responses( auth_response: &Self, capture_response: &Self, ) -> Result<Self, error_stack::Report<ApiErrorResponse>> { match (auth_response, capture_response) { ( Self::TransactionResponse { resource_id: _, redirection_data: auth_redirection_data, mandate_reference: auth_mandate_reference, connector_metadata: auth_connector_metadata, network_txn_id: auth_network_txn_id, connector_response_reference_id: auth_connector_response_reference_id, incremental_authorization_allowed: auth_incremental_auth_allowed, charges: auth_charges, }, Self::TransactionResponse { resource_id: capture_resource_id, redirection_data: capture_redirection_data, mandate_reference: capture_mandate_reference, connector_metadata: capture_connector_metadata, network_txn_id: capture_network_txn_id, connector_response_reference_id: capture_connector_response_reference_id, incremental_authorization_allowed: capture_incremental_auth_allowed, charges: capture_charges, }, ) => Ok(Self::TransactionResponse { resource_id: capture_resource_id.clone(), redirection_data: Box::new( capture_redirection_data .clone() .or_else(|| *auth_redirection_data.clone()), ), mandate_reference: Box::new( auth_mandate_reference .clone() .or_else(|| *capture_mandate_reference.clone()), ), connector_metadata: capture_connector_metadata .clone() .or(auth_connector_metadata.clone()), network_txn_id: capture_network_txn_id .clone() .or(auth_network_txn_id.clone()), connector_response_reference_id: capture_connector_response_reference_id .clone() .or(auth_connector_response_reference_id.clone()), incremental_authorization_allowed: (*capture_incremental_auth_allowed) .or(*auth_incremental_auth_allowed), charges: auth_charges.clone().or(capture_charges.clone()), }), _ => Err(ApiErrorResponse::NotSupported { message: "Invalid Flow ".to_owned(), } .into()), } } #[cfg(feature = "v2")] pub fn get_updated_connector_token_details( &self, original_connector_mandate_request_reference_id: Option<String>, ) -> Option<diesel_models::ConnectorTokenDetails> { if let Self::TransactionResponse { mandate_reference, .. } = self { mandate_reference.clone().map(|mandate_ref| { let connector_mandate_id = mandate_ref.connector_mandate_id; let connector_mandate_request_reference_id = mandate_ref .connector_mandate_request_reference_id .or(original_connector_mandate_request_reference_id); diesel_models::ConnectorTokenDetails { connector_mandate_id, connector_token_request_reference_id: connector_mandate_request_reference_id, } }) } else { None } } } #[derive(Debug, Clone, Serialize)] pub enum PreprocessingResponseId { PreProcessingId(String), ConnectorTransactionId(String), } #[derive(Debug, Eq, PartialEq, Clone, Serialize, serde::Deserialize)] pub enum RedirectForm { Form { endpoint: String, method: Method, form_fields: HashMap<String, String>, }, Html { html_data: String, }, BarclaycardAuthSetup { access_token: String, ddc_url: String, reference_id: String, }, BarclaycardConsumerAuth { access_token: String, step_up_url: String, }, BlueSnap { payment_fields_token: String, // payment-field-token }, CybersourceAuthSetup { access_token: String, ddc_url: String, reference_id: String, }, CybersourceConsumerAuth { access_token: String, step_up_url: String, }, DeutschebankThreeDSChallengeFlow { acs_url: String, creq: String, }, Payme, Braintree { client_token: String, card_token: String, bin: String, acs_url: String, }, Nmi { amount: String, currency: common_enums::Currency, public_key: masking::Secret<String>, customer_vault_id: String, order_id: String, }, Mifinity { initialization_token: String, }, WorldpayDDCForm { endpoint: url::Url, method: Method, form_fields: HashMap<String, String>, collection_id: Option<String>, }, } impl From<(url::Url, Method)> for RedirectForm { fn from((mut redirect_url, method): (url::Url, Method)) -> Self { let form_fields = HashMap::from_iter( redirect_url .query_pairs() .map(|(key, value)| (key.to_string(), value.to_string())), ); // Do not include query params in the endpoint redirect_url.set_query(None); Self::Form { endpoint: redirect_url.to_string(), method, form_fields, } } } impl From<RedirectForm> for diesel_models::payment_attempt::RedirectForm { fn from(redirect_form: RedirectForm) -> Self { match redirect_form { RedirectForm::Form { endpoint, method, form_fields, } => Self::Form { endpoint, method, form_fields, }, RedirectForm::Html { html_data } => Self::Html { html_data }, RedirectForm::BarclaycardAuthSetup { access_token, ddc_url, reference_id, } => Self::BarclaycardAuthSetup { access_token, ddc_url, reference_id, }, RedirectForm::BarclaycardConsumerAuth { access_token, step_up_url, } => Self::BarclaycardConsumerAuth { access_token, step_up_url, }, RedirectForm::BlueSnap { payment_fields_token, } => Self::BlueSnap { payment_fields_token, }, RedirectForm::CybersourceAuthSetup { access_token, ddc_url, reference_id, } => Self::CybersourceAuthSetup { access_token, ddc_url, reference_id, }, RedirectForm::CybersourceConsumerAuth { access_token, step_up_url, } => Self::CybersourceConsumerAuth { access_token, step_up_url, }, RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => { Self::DeutschebankThreeDSChallengeFlow { acs_url, creq } } RedirectForm::Payme => Self::Payme, RedirectForm::Braintree { client_token, card_token, bin, acs_url, } => Self::Braintree { client_token, card_token, bin, acs_url, }, RedirectForm::Nmi { amount, currency, public_key, customer_vault_id, order_id, } => Self::Nmi { amount, currency, public_key, customer_vault_id, order_id, }, RedirectForm::Mifinity { initialization_token, } => Self::Mifinity { initialization_token, }, RedirectForm::WorldpayDDCForm { endpoint, method, form_fields, collection_id, } => Self::WorldpayDDCForm { endpoint: common_utils::types::Url::wrap(endpoint), method, form_fields, collection_id, }, } } } impl From<diesel_models::payment_attempt::RedirectForm> for RedirectForm { fn from(redirect_form: diesel_models::payment_attempt::RedirectForm) -> Self { match redirect_form { diesel_models::payment_attempt::RedirectForm::Form { endpoint, method, form_fields, } => Self::Form { endpoint, method, form_fields, }, diesel_models::payment_attempt::RedirectForm::Html { html_data } => { Self::Html { html_data } } diesel_models::payment_attempt::RedirectForm::BarclaycardAuthSetup { access_token, ddc_url, reference_id, } => Self::BarclaycardAuthSetup { access_token, ddc_url, reference_id, }, diesel_models::payment_attempt::RedirectForm::BarclaycardConsumerAuth { access_token, step_up_url, } => Self::BarclaycardConsumerAuth { access_token, step_up_url, }, diesel_models::payment_attempt::RedirectForm::BlueSnap { payment_fields_token, } => Self::BlueSnap { payment_fields_token, }, diesel_models::payment_attempt::RedirectForm::CybersourceAuthSetup { access_token, ddc_url, reference_id, } => Self::CybersourceAuthSetup { access_token, ddc_url, reference_id, }, diesel_models::payment_attempt::RedirectForm::CybersourceConsumerAuth { access_token, step_up_url, } => Self::CybersourceConsumerAuth { access_token, step_up_url, }, diesel_models::RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => { Self::DeutschebankThreeDSChallengeFlow { acs_url, creq } } diesel_models::payment_attempt::RedirectForm::Payme => Self::Payme, diesel_models::payment_attempt::RedirectForm::Braintree { client_token, card_token, bin, acs_url, } => Self::Braintree { client_token, card_token, bin, acs_url, }, diesel_models::payment_attempt::RedirectForm::Nmi { amount, currency, public_key, customer_vault_id, order_id, } => Self::Nmi { amount, currency, public_key, customer_vault_id, order_id, }, diesel_models::payment_attempt::RedirectForm::Mifinity { initialization_token, } => Self::Mifinity { initialization_token, }, diesel_models::payment_attempt::RedirectForm::WorldpayDDCForm { endpoint, method, form_fields, collection_id, } => Self::WorldpayDDCForm { endpoint: endpoint.into_inner(), method, form_fields, collection_id, }, } } } #[derive(Default, Clone, Debug)] pub struct UploadFileResponse { pub provider_file_id: String, } #[derive(Clone, Debug)] pub struct RetrieveFileResponse { pub file_data: Vec<u8>, } #[cfg(feature = "payouts")] #[derive(Clone, Debug, Default)] pub struct PayoutsResponseData { pub status: Option<common_enums::PayoutStatus>, pub connector_payout_id: Option<String>, pub payout_eligible: Option<bool>, pub should_add_next_step_to_process_tracker: bool, pub error_code: Option<String>, pub error_message: Option<String>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct VerifyWebhookSourceResponseData { pub verify_webhook_status: VerifyWebhookStatus, } #[derive(Debug, Clone)] pub enum VerifyWebhookStatus { SourceVerified, SourceNotVerified, } #[derive(Debug, Clone)] pub struct MandateRevokeResponseData { pub mandate_status: common_enums::MandateStatus, } #[derive(Debug, Clone)] pub enum AuthenticationResponseData { PreAuthVersionCallResponse { maximum_supported_3ds_version: common_utils::types::SemanticVersion, }, PreAuthThreeDsMethodCallResponse { threeds_server_transaction_id: String, three_ds_method_data: Option<String>, three_ds_method_url: Option<String>, connector_metadata: Option<serde_json::Value>, }, PreAuthNResponse { threeds_server_transaction_id: String, maximum_supported_3ds_version: common_utils::types::SemanticVersion, connector_authentication_id: String, three_ds_method_data: Option<String>, three_ds_method_url: Option<String>, message_version: common_utils::types::SemanticVersion, connector_metadata: Option<serde_json::Value>, directory_server_id: Option<String>, }, AuthNResponse { authn_flow_type: AuthNFlowType, authentication_value: Option<masking::Secret<String>>, trans_status: common_enums::TransactionStatus, connector_metadata: Option<serde_json::Value>, ds_trans_id: Option<String>, eci: Option<String>, challenge_code: Option<String>, challenge_cancel: Option<String>, challenge_code_reason: Option<String>, message_extension: Option<pii::SecretSerdeValue>, }, PostAuthNResponse { trans_status: common_enums::TransactionStatus, authentication_value: Option<masking::Secret<String>>, eci: Option<String>, challenge_cancel: Option<String>, challenge_code_reason: Option<String>, }, } #[derive(Debug, Clone)] pub struct CompleteAuthorizeRedirectResponse { pub params: Option<masking::Secret<String>>, pub payload: Option<pii::SecretSerdeValue>, } /// Represents details of a payment method. #[derive(Debug, Clone)] pub struct PaymentMethodDetails { /// Indicates whether mandates are supported by this payment method. pub mandates: common_enums::FeatureStatus, /// Indicates whether refund is supported by this payment method. pub refunds: common_enums::FeatureStatus, /// List of supported capture methods pub supported_capture_methods: Vec<common_enums::CaptureMethod>, /// Payment method specific features pub specific_features: Option<api_models::feature_matrix::PaymentMethodSpecificFeatures>, } /// list of payment method types and metadata related to them pub type PaymentMethodTypeMetadata = HashMap<common_enums::PaymentMethodType, PaymentMethodDetails>; /// list of payment methods, payment method types and metadata related to them pub type SupportedPaymentMethods = HashMap<common_enums::PaymentMethod, PaymentMethodTypeMetadata>; #[derive(Debug, Clone)] pub struct ConnectorInfo { /// Display name of the Connector pub display_name: &'static str, /// Description of the connector. pub description: &'static str, /// Connector Type pub connector_type: common_enums::HyperswitchConnectorCategory, /// Integration status of the connector pub integration_status: common_enums::ConnectorIntegrationStatus, } pub trait SupportedPaymentMethodsExt { fn add( &mut self, payment_method: common_enums::PaymentMethod, payment_method_type: common_enums::PaymentMethodType, payment_method_details: PaymentMethodDetails, ); } impl SupportedPaymentMethodsExt for SupportedPaymentMethods { fn add( &mut self, payment_method: common_enums::PaymentMethod, payment_method_type: common_enums::PaymentMethodType, payment_method_details: PaymentMethodDetails, ) { if let Some(payment_method_data) = self.get_mut(&payment_method) { payment_method_data.insert(payment_method_type, payment_method_details); } else { let mut payment_method_type_metadata = PaymentMethodTypeMetadata::new(); payment_method_type_metadata.insert(payment_method_type, payment_method_details); self.insert(payment_method, payment_method_type_metadata); } } } #[derive(Debug, Clone)] pub enum VaultResponseData { ExternalVaultCreateResponse { session_id: masking::Secret<String>, client_secret: masking::Secret<String>, }, ExternalVaultInsertResponse { connector_vault_id: String, fingerprint_id: String, }, ExternalVaultRetrieveResponse { vault_data: PaymentMethodVaultingData, }, ExternalVaultDeleteResponse { connector_vault_id: String, }, } impl Default for VaultResponseData { fn default() -> Self { Self::ExternalVaultInsertResponse { connector_vault_id: String::new(), fingerprint_id: String::new(), } } }
crates/hyperswitch_domain_models/src/router_response_types.rs
hyperswitch_domain_models::src::router_response_types
4,783
true
// File: crates/hyperswitch_domain_models/src/gsm.rs // Module: hyperswitch_domain_models::src::gsm use common_utils::{errors::ValidationError, ext_traits::StringExt}; use serde::{self, Deserialize, Serialize}; #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] pub struct GatewayStatusMap { pub connector: String, pub flow: String, pub sub_flow: String, pub code: String, pub message: String, pub status: String, pub router_error: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<common_enums::ErrorCategory>, pub feature_data: common_types::domain::GsmFeatureData, pub feature: common_enums::GsmFeature, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct GatewayStatusMappingUpdate { pub status: Option<String>, pub router_error: Option<Option<String>>, pub decision: Option<common_enums::GsmDecision>, pub step_up_possible: Option<bool>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<common_enums::ErrorCategory>, pub clear_pan_possible: Option<bool>, pub feature_data: Option<common_types::domain::GsmFeatureData>, pub feature: Option<common_enums::GsmFeature>, } impl TryFrom<GatewayStatusMap> for diesel_models::gsm::GatewayStatusMappingNew { type Error = error_stack::Report<ValidationError>; fn try_from(value: GatewayStatusMap) -> Result<Self, Self::Error> { Ok(Self { connector: value.connector.to_string(), flow: value.flow, sub_flow: value.sub_flow, code: value.code, message: value.message, status: value.status.clone(), router_error: value.router_error, decision: value.feature_data.get_decision().to_string(), step_up_possible: value .feature_data .get_retry_feature_data() .map(|retry_feature_data| retry_feature_data.is_step_up_possible()) .unwrap_or(false), unified_code: value.unified_code, unified_message: value.unified_message, error_category: value.error_category, clear_pan_possible: value .feature_data .get_retry_feature_data() .map(|retry_feature_data| retry_feature_data.is_clear_pan_possible()) .unwrap_or(false), feature_data: Some(value.feature_data), feature: Some(value.feature), }) } } impl TryFrom<GatewayStatusMappingUpdate> for diesel_models::gsm::GatewayStatusMappingUpdate { type Error = error_stack::Report<ValidationError>; fn try_from(value: GatewayStatusMappingUpdate) -> Result<Self, Self::Error> { Ok(Self { status: value.status, router_error: value.router_error, decision: value.decision.map(|gsm_decision| gsm_decision.to_string()), step_up_possible: value.step_up_possible, unified_code: value.unified_code, unified_message: value.unified_message, error_category: value.error_category, clear_pan_possible: value.clear_pan_possible, feature_data: value.feature_data, feature: value.feature, }) } } impl TryFrom<diesel_models::gsm::GatewayStatusMap> for GatewayStatusMap { type Error = ValidationError; fn try_from(item: diesel_models::gsm::GatewayStatusMap) -> Result<Self, Self::Error> { let decision = StringExt::<common_enums::GsmDecision>::parse_enum(item.decision, "GsmDecision") .map_err(|_| ValidationError::InvalidValue { message: "Failed to parse GsmDecision".to_string(), })?; let db_feature_data = item.feature_data; // The only case where `FeatureData` can be null is for legacy records // (i.e., records created before `FeatureData` and related features were introduced). // At that time, the only supported feature was `Retry`, so it's safe to default to it. let feature_data = match db_feature_data { Some(common_types::domain::GsmFeatureData::Retry(data)) => { common_types::domain::GsmFeatureData::Retry(data) } None => common_types::domain::GsmFeatureData::Retry( common_types::domain::RetryFeatureData { step_up_possible: item.step_up_possible, clear_pan_possible: item.clear_pan_possible, alternate_network_possible: false, decision, }, ), }; let feature = item.feature.unwrap_or(common_enums::GsmFeature::Retry); Ok(Self { connector: item.connector, flow: item.flow, sub_flow: item.sub_flow, code: item.code, message: item.message, status: item.status, router_error: item.router_error, unified_code: item.unified_code, unified_message: item.unified_message, error_category: item.error_category, feature_data, feature, }) } }
crates/hyperswitch_domain_models/src/gsm.rs
hyperswitch_domain_models::src::gsm
1,083
true
// File: crates/hyperswitch_domain_models/src/revenue_recovery.rs // Module: hyperswitch_domain_models::src::revenue_recovery use api_models::{payments as api_payments, webhooks}; use common_enums::enums as common_enums; use common_types::primitive_wrappers; use common_utils::{id_type, pii, types as util_types}; use time::PrimitiveDateTime; use crate::{ payments, router_response_types::revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, }, ApiModelToDieselModelConvertor, }; /// Recovery payload is unified struct constructed from billing connectors #[derive(Debug)] pub struct RevenueRecoveryAttemptData { /// transaction amount against invoice, accepted in minor unit. pub amount: util_types::MinorUnit, /// currency of the transaction pub currency: common_enums::Currency, /// merchant reference id at billing connector. ex: invoice_id pub merchant_reference_id: id_type::PaymentReferenceId, /// transaction id reference at payment connector pub connector_transaction_id: Option<util_types::ConnectorTransactionId>, /// error code sent by billing connector. pub error_code: Option<String>, /// error message sent by billing connector. pub error_message: Option<String>, /// mandate token at payment processor end. pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. pub connector_customer_id: String, /// Payment gateway identifier id at billing processor. pub connector_account_reference_id: String, /// timestamp at which transaction has been created at billing connector pub transaction_created_at: Option<PrimitiveDateTime>, /// transaction status at billing connector equivalent to payment attempt status. pub status: common_enums::AttemptStatus, /// payment method of payment attempt. pub payment_method_type: common_enums::PaymentMethod, /// payment method sub type of the payment attempt. pub payment_method_sub_type: common_enums::PaymentMethodType, /// 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>, /// Number of attempts made for an invoice pub retry_count: Option<u16>, /// Time when next invoice will be generated which will be equal to the end time of the current invoice pub invoice_next_billing_time: Option<PrimitiveDateTime>, /// Time at which the invoice created pub invoice_billing_started_at_time: Option<PrimitiveDateTime>, /// stripe specific id used to validate duplicate attempts in revenue recovery flow pub charge_id: Option<String>, /// Additional card details pub card_info: api_payments::AdditionalCardInfo, } /// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors #[derive(Debug, Clone)] pub struct RevenueRecoveryInvoiceData { /// invoice amount at billing connector pub amount: util_types::MinorUnit, /// currency of the amount. pub currency: common_enums::Currency, /// merchant reference id at billing connector. ex: invoice_id pub merchant_reference_id: id_type::PaymentReferenceId, /// billing address id of the invoice pub billing_address: Option<api_payments::Address>, /// Retry count of the invoice pub retry_count: Option<u16>, /// Ending date of the invoice or the Next billing time of the Subscription pub next_billing_at: Option<PrimitiveDateTime>, /// Invoice Starting Time pub billing_started_at: Option<PrimitiveDateTime>, /// metadata of the merchant pub metadata: Option<pii::SecretSerdeValue>, /// Allow partial authorization for this payment pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, } #[derive(Clone, Debug)] pub struct RecoveryPaymentIntent { pub payment_id: id_type::GlobalPaymentId, pub status: common_enums::IntentStatus, pub feature_metadata: Option<api_payments::FeatureMetadata>, pub merchant_id: id_type::MerchantId, pub merchant_reference_id: Option<id_type::PaymentReferenceId>, pub invoice_amount: util_types::MinorUnit, pub invoice_currency: common_enums::Currency, pub created_at: Option<PrimitiveDateTime>, pub billing_address: Option<api_payments::Address>, } #[derive(Clone, Debug)] pub struct RecoveryPaymentAttempt { pub attempt_id: id_type::GlobalAttemptId, pub attempt_status: common_enums::AttemptStatus, pub feature_metadata: Option<api_payments::PaymentAttemptFeatureMetadata>, pub amount: util_types::MinorUnit, pub network_advice_code: Option<String>, pub network_decline_code: Option<String>, pub error_code: Option<String>, pub created_at: PrimitiveDateTime, } impl RecoveryPaymentAttempt { pub fn get_attempt_triggered_by(&self) -> Option<common_enums::TriggeredBy> { self.feature_metadata.as_ref().and_then(|metadata| { metadata .revenue_recovery .as_ref() .map(|recovery| recovery.attempt_triggered_by) }) } } impl From<&RevenueRecoveryInvoiceData> for api_payments::AmountDetails { fn from(data: &RevenueRecoveryInvoiceData) -> Self { let amount = api_payments::AmountDetailsSetter { order_amount: data.amount.into(), currency: data.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, }; Self::new(amount) } } impl From<&RevenueRecoveryInvoiceData> for api_payments::PaymentsCreateIntentRequest { fn from(data: &RevenueRecoveryInvoiceData) -> Self { let amount_details = api_payments::AmountDetails::from(data); Self { amount_details, merchant_reference_id: Some(data.merchant_reference_id.clone()), routing_algorithm_id: None, // Payments in the revenue recovery flow are always recurring transactions, // so capture method will be always automatic. capture_method: Some(common_enums::CaptureMethod::Automatic), authentication_type: Some(common_enums::AuthenticationType::NoThreeDs), billing: data.billing_address.clone(), shipping: None, customer_id: None, customer_present: Some(common_enums::PresenceOfCustomerDuringPayment::Absent), 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: data.metadata.clone(), connector_metadata: None, feature_metadata: None, payment_link_enabled: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, force_3ds_challenge: None, merchant_connector_details: None, enable_partial_authorization: data.enable_partial_authorization, } } } impl From<&BillingConnectorInvoiceSyncResponse> for RevenueRecoveryInvoiceData { fn from(data: &BillingConnectorInvoiceSyncResponse) -> Self { Self { amount: data.amount, currency: data.currency, merchant_reference_id: data.merchant_reference_id.clone(), billing_address: data.billing_address.clone(), retry_count: data.retry_count, next_billing_at: data.ends_at, billing_started_at: data.created_at, metadata: None, enable_partial_authorization: None, } } } impl From<( &BillingConnectorPaymentsSyncResponse, &RevenueRecoveryInvoiceData, )> for RevenueRecoveryAttemptData { fn from( data: ( &BillingConnectorPaymentsSyncResponse, &RevenueRecoveryInvoiceData, ), ) -> Self { let billing_connector_payment_details = data.0; let invoice_details = data.1; Self { amount: billing_connector_payment_details.amount, currency: billing_connector_payment_details.currency, merchant_reference_id: billing_connector_payment_details .merchant_reference_id .clone(), connector_transaction_id: billing_connector_payment_details .connector_transaction_id .clone(), error_code: billing_connector_payment_details.error_code.clone(), error_message: billing_connector_payment_details.error_message.clone(), processor_payment_method_token: billing_connector_payment_details .processor_payment_method_token .clone(), connector_customer_id: billing_connector_payment_details .connector_customer_id .clone(), connector_account_reference_id: billing_connector_payment_details .connector_account_reference_id .clone(), transaction_created_at: billing_connector_payment_details.transaction_created_at, status: billing_connector_payment_details.status, payment_method_type: billing_connector_payment_details.payment_method_type, payment_method_sub_type: billing_connector_payment_details.payment_method_sub_type, network_advice_code: None, network_decline_code: None, network_error_message: None, retry_count: invoice_details.retry_count, invoice_next_billing_time: invoice_details.next_billing_at, charge_id: billing_connector_payment_details.charge_id.clone(), invoice_billing_started_at_time: invoice_details.billing_started_at, card_info: billing_connector_payment_details.card_info.clone(), } } } impl From<&RevenueRecoveryAttemptData> for api_payments::PaymentAttemptAmountDetails { fn from(data: &RevenueRecoveryAttemptData) -> Self { Self { net_amount: data.amount, amount_to_capture: None, surcharge_amount: None, tax_on_surcharge: None, amount_capturable: data.amount, shipping_cost: None, order_tax_amount: None, } } } impl From<&RevenueRecoveryAttemptData> for Option<api_payments::RecordAttemptErrorDetails> { fn from(data: &RevenueRecoveryAttemptData) -> Self { data.error_code .as_ref() .zip(data.error_message.clone()) .map(|(code, message)| api_payments::RecordAttemptErrorDetails { code: code.to_string(), message: message.to_string(), network_advice_code: data.network_advice_code.clone(), network_decline_code: data.network_decline_code.clone(), network_error_message: data.network_error_message.clone(), }) } } impl From<&payments::PaymentIntent> for RecoveryPaymentIntent { fn from(payment_intent: &payments::PaymentIntent) -> Self { Self { payment_id: payment_intent.id.clone(), status: payment_intent.status, feature_metadata: payment_intent .feature_metadata .clone() .map(|feature_metadata| feature_metadata.convert_back()), merchant_reference_id: payment_intent.merchant_reference_id.clone(), invoice_amount: payment_intent.amount_details.order_amount, invoice_currency: payment_intent.amount_details.currency, billing_address: payment_intent .billing_address .clone() .map(|address| api_payments::Address::from(address.into_inner())), merchant_id: payment_intent.merchant_id.clone(), created_at: Some(payment_intent.created_at), } } } impl From<&payments::payment_attempt::PaymentAttempt> for RecoveryPaymentAttempt { fn from(payment_attempt: &payments::payment_attempt::PaymentAttempt) -> Self { Self { attempt_id: payment_attempt.id.clone(), attempt_status: payment_attempt.status, feature_metadata: payment_attempt .feature_metadata .clone() .map( |feature_metadata| api_payments::PaymentAttemptFeatureMetadata { revenue_recovery: feature_metadata.revenue_recovery.map(|recovery| { api_payments::PaymentAttemptRevenueRecoveryData { attempt_triggered_by: recovery.attempt_triggered_by, charge_id: recovery.charge_id, } }), }, ), amount: payment_attempt.amount_details.get_net_amount(), network_advice_code: payment_attempt .error .clone() .and_then(|error| error.network_advice_code), network_decline_code: payment_attempt .error .clone() .and_then(|error| error.network_decline_code), error_code: payment_attempt .error .as_ref() .map(|error| error.code.clone()), created_at: payment_attempt.created_at, } } }
crates/hyperswitch_domain_models/src/revenue_recovery.rs
hyperswitch_domain_models::src::revenue_recovery
2,764
true
// File: crates/hyperswitch_domain_models/src/authentication.rs // Module: hyperswitch_domain_models::src::authentication use common_utils::{ crypto::Encryptable, encryption::Encryption, errors::CustomResult, pii, types::keymanager::ToEncryptable, }; use masking::Secret; use rustc_hash::FxHashMap; use serde_json::Value; #[cfg(feature = "v1")] #[derive(Clone, Debug, router_derive::ToEncryption, serde::Serialize)] pub struct Authentication { pub authentication_id: common_utils::id_type::AuthenticationId, pub merchant_id: common_utils::id_type::MerchantId, pub authentication_connector: Option<String>, pub connector_authentication_id: Option<String>, pub authentication_data: Option<Value>, pub payment_method_id: String, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, pub authentication_status: common_enums::AuthenticationStatus, pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: time::PrimitiveDateTime, pub error_message: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<String>, pub cavv: Option<String>, pub authentication_flow_type: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<String>, pub trans_status: Option<common_enums::TransactionStatus>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, pub three_ds_method_data: Option<String>, pub three_ds_method_url: Option<String>, pub acs_url: Option<String>, pub challenge_request: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub acs_signed_content: Option<String>, pub profile_id: common_utils::id_type::ProfileId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, pub acquirer_country_code: Option<String>, pub service_details: Option<Value>, pub organization_id: common_utils::id_type::OrganizationId, pub authentication_client_secret: Option<String>, pub force_3ds_challenge: Option<bool>, pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, pub return_url: Option<String>, pub amount: Option<common_utils::types::MinorUnit>, pub currency: Option<common_enums::Currency>, #[encrypt(ty = Value)] pub billing_address: Option<Encryptable<crate::address::Address>>, #[encrypt(ty = Value)] pub shipping_address: Option<Encryptable<crate::address::Address>>, pub browser_info: Option<Value>, pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>, } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponseForAuthentication { pub authentication_id: common_utils::id_type::AuthenticationId, pub status: common_enums::TransactionStatus, pub gateway_id: String, pub customer_id: Option<common_utils::id_type::CustomerId>, pub amount: Option<common_utils::types::MinorUnit>, }
crates/hyperswitch_domain_models/src/authentication.rs
hyperswitch_domain_models::src::authentication
792
true
// File: crates/hyperswitch_domain_models/src/payment_method_data.rs // Module: hyperswitch_domain_models::src::payment_method_data #[cfg(feature = "v2")] use std::str::FromStr; use api_models::{ mandates, payment_methods::{self}, payments::{additional_info as payment_additional_types, ExtendedCardInfo}, }; use common_enums::{enums as api_enums, GooglePayCardFundingSource}; use common_utils::{ ext_traits::{OptionExt, StringExt}, id_type, new_type::{ MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId, }, payout_method_utils, pii::{self, Email}, }; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use time::Date; // We need to derive Serialize and Deserialize because some parts of payment method data are being // stored in the database as serde_json::Value #[derive(PartialEq, Clone, Debug, Serialize, Deserialize)] pub enum PaymentMethodData { Card(Card), CardDetailsForNetworkTransactionId(CardDetailsForNetworkTransactionId), CardRedirect(CardRedirectData), Wallet(WalletData), PayLater(PayLaterData), BankRedirect(BankRedirectData), BankDebit(BankDebitData), BankTransfer(Box<BankTransferData>), Crypto(CryptoData), MandatePayment, Reward, RealTimePayment(Box<RealTimePaymentData>), Upi(UpiData), Voucher(VoucherData), GiftCard(Box<GiftCardData>), CardToken(CardToken), OpenBanking(OpenBankingData), NetworkToken(NetworkTokenData), MobilePayment(MobilePaymentData), } #[derive(PartialEq, Clone, Debug, Serialize, Deserialize)] pub enum ExternalVaultPaymentMethodData { Card(Box<ExternalVaultCard>), VaultToken(VaultToken), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub enum ApplePayFlow { Simplified(api_models::payments::PaymentProcessingDetails), Manual, } impl PaymentMethodData { pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> { match self { Self::Card(_) | Self::NetworkToken(_) | Self::CardDetailsForNetworkTransactionId(_) => { Some(common_enums::PaymentMethod::Card) } Self::CardRedirect(_) => Some(common_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(common_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(common_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(common_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(common_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(common_enums::PaymentMethod::BankTransfer), Self::Crypto(_) => Some(common_enums::PaymentMethod::Crypto), Self::Reward => Some(common_enums::PaymentMethod::Reward), Self::RealTimePayment(_) => Some(common_enums::PaymentMethod::RealTimePayment), Self::Upi(_) => Some(common_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(common_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(common_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(common_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(common_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } pub fn get_wallet_data(&self) -> Option<&WalletData> { if let Self::Wallet(wallet_data) = self { Some(wallet_data) } else { None } } pub fn is_network_token_payment_method_data(&self) -> bool { matches!(self, Self::NetworkToken(_)) } pub fn get_co_badged_card_data(&self) -> Option<&payment_methods::CoBadgedCardData> { if let Self::Card(card) = self { card.co_badged_card_data.as_ref() } else { None } } pub fn get_card_data(&self) -> Option<&Card> { if let Self::Card(card) = self { Some(card) } else { None } } pub fn extract_debit_routing_saving_percentage( &self, network: &common_enums::CardNetwork, ) -> Option<f64> { self.get_co_badged_card_data()? .co_badged_card_networks_info .0 .iter() .find(|info| &info.network == network) .map(|info| info.saving_percentage) } } #[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)] pub struct Card { pub card_number: cards::CardNumber, pub card_exp_month: Secret<String>, pub card_exp_year: Secret<String>, pub card_cvc: Secret<String>, pub card_issuer: Option<String>, pub card_network: Option<common_enums::CardNetwork>, pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } #[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)] pub struct ExternalVaultCard { pub card_number: Secret<String>, pub card_exp_month: Secret<String>, pub card_exp_year: Secret<String>, pub card_cvc: Secret<String>, pub bin_number: Option<String>, pub last_four: Option<String>, pub card_issuer: Option<String>, pub card_network: Option<common_enums::CardNetwork>, pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } #[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)] pub struct VaultToken { pub card_cvc: Secret<String>, pub card_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] pub struct CardDetailsForNetworkTransactionId { pub card_number: cards::CardNumber, pub card_exp_month: Secret<String>, pub card_exp_year: Secret<String>, pub card_issuer: Option<String>, pub card_network: Option<common_enums::CardNetwork>, pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, } #[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)] pub struct CardDetail { pub card_number: cards::CardNumber, pub card_exp_month: Secret<String>, pub card_exp_year: Secret<String>, pub card_issuer: Option<String>, pub card_network: Option<api_enums::CardNetwork>, pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } impl CardDetailsForNetworkTransactionId { pub fn get_nti_and_card_details_for_mit_flow( recurring_details: mandates::RecurringDetails, ) -> Option<(api_models::payments::MandateReferenceId, Self)> { let network_transaction_id_and_card_details = match recurring_details { mandates::RecurringDetails::NetworkTransactionIdAndCardDetails( network_transaction_id_and_card_details, ) => Some(network_transaction_id_and_card_details), mandates::RecurringDetails::MandateId(_) | mandates::RecurringDetails::PaymentMethodId(_) | mandates::RecurringDetails::ProcessorPaymentToken(_) => None, }?; let mandate_reference_id = api_models::payments::MandateReferenceId::NetworkMandateId( network_transaction_id_and_card_details .network_transaction_id .peek() .to_string(), ); Some(( mandate_reference_id, network_transaction_id_and_card_details.clone().into(), )) } } impl From<&Card> for CardDetail { fn from(item: &Card) -> Self { Self { card_number: item.card_number.to_owned(), card_exp_month: item.card_exp_month.to_owned(), card_exp_year: item.card_exp_year.to_owned(), card_issuer: item.card_issuer.to_owned(), card_network: item.card_network.to_owned(), card_type: item.card_type.to_owned(), card_issuing_country: item.card_issuing_country.to_owned(), bank_code: item.bank_code.to_owned(), nick_name: item.nick_name.to_owned(), card_holder_name: item.card_holder_name.to_owned(), co_badged_card_data: item.co_badged_card_data.to_owned(), } } } impl From<mandates::NetworkTransactionIdAndCardDetails> for CardDetailsForNetworkTransactionId { fn from(card_details_for_nti: mandates::NetworkTransactionIdAndCardDetails) -> Self { Self { card_number: card_details_for_nti.card_number, card_exp_month: card_details_for_nti.card_exp_month, card_exp_year: card_details_for_nti.card_exp_year, card_issuer: card_details_for_nti.card_issuer, card_network: card_details_for_nti.card_network, card_type: card_details_for_nti.card_type, card_issuing_country: card_details_for_nti.card_issuing_country, bank_code: card_details_for_nti.bank_code, nick_name: card_details_for_nti.nick_name, card_holder_name: card_details_for_nti.card_holder_name, } } } #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub enum PayLaterData { KlarnaRedirect {}, KlarnaSdk { token: String }, AffirmRedirect {}, AfterpayClearpayRedirect {}, PayBrightRedirect {}, WalleyRedirect {}, FlexitiRedirect {}, AlmaRedirect {}, AtomeRedirect {}, BreadpayRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub enum WalletData { AliPayQr(Box<AliPayQr>), AliPayRedirect(AliPayRedirection), AliPayHkRedirect(AliPayHkRedirection), AmazonPay(AmazonPayWalletData), AmazonPayRedirect(Box<AmazonPayRedirect>), BluecodeRedirect {}, Paysera(Box<PayseraData>), Skrill(Box<SkrillData>), MomoRedirect(MomoRedirection), KakaoPayRedirect(KakaoPayRedirection), GoPayRedirect(GoPayRedirection), GcashRedirect(GcashRedirection), ApplePay(ApplePayWalletData), ApplePayRedirect(Box<ApplePayRedirectData>), ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), DanaRedirect {}, GooglePay(GooglePayWalletData), GooglePayRedirect(Box<GooglePayRedirectData>), GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), MobilePayRedirect(Box<MobilePayRedirection>), PaypalRedirect(PaypalRedirection), PaypalSdk(PayPalWalletData), Paze(PazeWalletData), SamsungPay(Box<SamsungPayWalletData>), TwintRedirect {}, VippsRedirect {}, TouchNGoRedirect(Box<TouchNGoRedirection>), WeChatPayRedirect(Box<WeChatPayRedirection>), WeChatPayQr(Box<WeChatPayQr>), CashappQr(Box<CashappQr>), SwishQr(SwishQrData), Mifinity(MifinityData), RevolutPay(RevolutPayData), } impl WalletData { pub fn get_paze_wallet_data(&self) -> Option<&PazeWalletData> { if let Self::Paze(paze_wallet_data) = self { Some(paze_wallet_data) } else { None } } pub fn get_apple_pay_wallet_data(&self) -> Option<&ApplePayWalletData> { if let Self::ApplePay(apple_pay_wallet_data) = self { Some(apple_pay_wallet_data) } else { None } } pub fn get_google_pay_wallet_data(&self) -> Option<&GooglePayWalletData> { if let Self::GooglePay(google_pay_wallet_data) = self { Some(google_pay_wallet_data) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct MifinityData { pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletCredentials { pub method: Option<String>, pub recurring_payment: Option<bool>, pub card_brand: common_enums::SamsungPayCardBrand, pub dpan_last_four_digits: Option<String>, #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { #[serde(rename = "type")] pub three_ds_type: Option<String>, pub version: String, pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct GooglePayWalletData { /// The type of payment method 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: common_types::payments::GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RevolutPayData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct GooglePayThirdPartySdkData { pub token: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ApplePayThirdPartySdkData { pub token: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaypalRedirection { /// paypal's email address pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct AmazonPayRedirect {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct BluecodeQrRedirect {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PayseraData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct SkrillData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct MbWayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] 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>, /// Card funding source for the selected payment method pub card_funding_source: Option<GooglePayCardFundingSource>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] #[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)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: common_types::payments::ApplePayPaymentData, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } impl ApplePayWalletData { pub fn get_payment_method_type(&self) -> Option<api_enums::PaymentMethodType> { self.payment_method .pm_type .clone() .parse_enum("ApplePayPaymentMethodType") .ok() .and_then(|payment_type| match payment_type { common_enums::ApplePayPaymentMethodType::Debit => { Some(api_enums::PaymentMethodType::Debit) } common_enums::ApplePayPaymentMethodType::Credit => { Some(api_enums::PaymentMethodType::Credit) } common_enums::ApplePayPaymentMethodType::Prepaid | common_enums::ApplePayPaymentMethodType::Store => None, }) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ApplepayPaymentMethod { pub display_name: String, pub network: String, pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Default, Debug, serde::Deserialize, serde::Serialize)] pub struct AmazonPayWalletData { pub checkout_session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub enum RealTimePaymentData { DuitNow {}, Fps {}, PromptPay {}, VietQr {}, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub enum BankRedirectData { BancontactCard { card_number: Option<cards::CardNumber>, card_exp_month: Option<Secret<String>>, card_exp_year: Option<Secret<String>>, card_holder_name: Option<Secret<String>>, }, Bizum {}, Blik { blik_code: Option<String>, }, Eps { bank_name: Option<common_enums::BankNames>, country: Option<api_enums::CountryAlpha2>, }, Giropay { bank_account_bic: Option<Secret<String>>, bank_account_iban: Option<Secret<String>>, country: Option<api_enums::CountryAlpha2>, }, Ideal { bank_name: Option<common_enums::BankNames>, }, Interac { country: Option<api_enums::CountryAlpha2>, email: Option<Email>, }, OnlineBankingCzechRepublic { issuer: common_enums::BankNames, }, OnlineBankingFinland { email: Option<Email>, }, OnlineBankingPoland { issuer: common_enums::BankNames, }, OnlineBankingSlovakia { issuer: common_enums::BankNames, }, OpenBankingUk { issuer: Option<common_enums::BankNames>, country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { bank_name: Option<common_enums::BankNames>, }, Sofort { country: Option<api_enums::CountryAlpha2>, preferred_language: Option<String>, }, Trustly { country: Option<api_enums::CountryAlpha2>, }, OnlineBankingFpx { issuer: common_enums::BankNames, }, OnlineBankingThailand { issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { provider: String, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { OpenBankingPIS {}, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[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)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), UpiQr(UpiQrData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct UpiQrData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] #[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>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct BoletoVoucherData { /// The shopper's social security number pub social_security_number: Option<Secret<String>>, /// The bank number associated with the boleto pub bank_number: Option<Secret<String>>, /// The type of document (e.g., CPF, CNPJ) pub document_type: Option<common_enums::DocumentKind>, /// The percentage of fine applied for late payment pub fine_percentage: Option<String>, /// The number of days after due date when fine is applied pub fine_quantity_days: Option<String>, /// The percentage of interest applied for late payment pub interest_percentage: Option<String>, /// Number of days after which the boleto can be written off pub write_off_quantity_days: Option<String>, /// Additional messages to display to the shopper pub messages: Option<Vec<String>>, /// The date upon which the boleto is due and is of format: "YYYY-MM-DD" pub due_date: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct AlfamartVoucherData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct IndomaretVoucherData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct JCSVoucherData {} #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, BhnCardNetwork(BHNGiftCardDetails), } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number pub number: Secret<String>, /// The card verification code. pub cvc: Secret<String>, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct BHNGiftCardDetails { /// The gift card or account number pub account_number: Secret<String>, /// The security PIN for gift cards requiring it pub pin: Option<Secret<String>>, /// The CVV2 code for Open Loop/VPLN products pub cvv2: Option<Secret<String>>, /// The expiration date in MMYYYY format for Open Loop/VPLN products pub expiration_date: Option<String>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card pub card_cvc: Option<Secret<String>>, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { AchBankDebit { account_number: Secret<String>, routing_number: Secret<String>, card_holder_name: Option<Secret<String>>, bank_account_holder_name: Option<Secret<String>>, bank_name: Option<common_enums::BankNames>, bank_type: Option<common_enums::BankType>, bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { iban: Secret<String>, bank_account_holder_name: Option<Secret<String>>, }, SepaGuarenteedBankDebit { iban: Secret<String>, bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { account_number: Secret<String>, bsb_number: Secret<String>, bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { account_number: Secret<String>, sort_code: Secret<String>, bank_account_holder_name: Option<Secret<String>>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer {}, SepaBankTransfer {}, BacsBankTransfer {}, MultibancoBankTransfer {}, PermataBankTransfer {}, BcaBankTransfer {}, BniVaBankTransfer {}, BriVaBankTransfer {}, CimbVaBankTransfer {}, DanamonVaBankTransfer {}, MandiriVaBankTransfer {}, Pix { /// Unique key for pix transfer pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number cnpj: Option<Secret<String>>, /// Source bank account UUID source_bank_account_id: Option<MaskedBankAccount>, /// Destination bank account UUID. destination_bank_account_id: Option<MaskedBankAccount>, /// The expiration date and time for the Pix QR code expiry_date: Option<time::PrimitiveDateTime>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, InstantBankTransferFinland {}, InstantBankTransferPoland {}, IndonesianBankTransfer { bank_name: Option<common_enums::BankNames>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing pub email: Email, /// The billing name for SEPA and BACS billing pub name: Secret<String>, } #[cfg(feature = "v1")] #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] pub struct NetworkTokenData { pub token_number: cards::CardNumber, pub token_exp_month: Secret<String>, pub token_exp_year: Secret<String>, pub token_cryptogram: Option<Secret<String>>, pub card_issuer: Option<String>, pub card_network: Option<common_enums::CardNetwork>, pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, pub nick_name: Option<Secret<String>>, pub eci: Option<String>, } #[cfg(feature = "v2")] #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] pub struct NetworkTokenData { pub network_token: cards::NetworkToken, pub network_token_exp_month: Secret<String>, pub network_token_exp_year: Secret<String>, pub cryptogram: Option<Secret<String>>, pub card_issuer: Option<String>, //since network token is tied to card, so its issuer will be same as card issuer pub card_network: Option<common_enums::CardNetwork>, pub card_type: Option<payment_methods::CardType>, pub card_issuing_country: Option<common_enums::CountryAlpha2>, pub bank_code: Option<String>, pub card_holder_name: Option<Secret<String>>, pub nick_name: Option<Secret<String>>, pub eci: Option<String>, } #[cfg(feature = "v2")] #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] pub struct NetworkTokenDetails { pub network_token: cards::NetworkToken, pub network_token_exp_month: Secret<String>, pub network_token_exp_year: Secret<String>, pub card_issuer: Option<String>, //since network token is tied to card, so its issuer will be same as card issuer pub card_network: Option<common_enums::CardNetwork>, pub card_type: Option<payment_methods::CardType>, pub card_issuing_country: Option<api_enums::CountryAlpha2>, pub card_holder_name: Option<Secret<String>>, pub nick_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user msisdn: String, /// Unique user identifier client_uid: Option<String>, }, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodData { type Error = error_stack::Report<common_utils::errors::ValidationError>; fn try_from(value: payment_methods::PaymentMethodCreateData) -> Result<Self, Self::Error> { match value { payment_methods::PaymentMethodCreateData::Card(payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_cvc, card_issuer, card_network, card_type, card_issuing_country, nick_name, card_holder_name, }) => Ok(Self::Card(Card { card_number, card_exp_month, card_exp_year, card_cvc: card_cvc.get_required_value("card_cvc")?, card_issuer, card_network, card_type: card_type.map(|card_type| card_type.to_string()), card_issuing_country: card_issuing_country.map(|country| country.to_string()), bank_code: None, nick_name, card_holder_name, co_badged_card_data: None, })), payment_methods::PaymentMethodCreateData::ProxyCard(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "Payment method data", } .into(), ), } } } impl From<api_models::payments::PaymentMethodData> for PaymentMethodData { fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self { match api_model_payment_method_data { api_models::payments::PaymentMethodData::Card(card_data) => { Self::Card(Card::from((card_data, None))) } api_models::payments::PaymentMethodData::CardRedirect(card_redirect) => { Self::CardRedirect(From::from(card_redirect)) } api_models::payments::PaymentMethodData::Wallet(wallet_data) => { Self::Wallet(From::from(wallet_data)) } api_models::payments::PaymentMethodData::PayLater(pay_later_data) => { Self::PayLater(From::from(pay_later_data)) } api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => { Self::BankRedirect(From::from(bank_redirect_data)) } api_models::payments::PaymentMethodData::BankDebit(bank_debit_data) => { Self::BankDebit(From::from(bank_debit_data)) } api_models::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => { Self::BankTransfer(Box::new(From::from(*bank_transfer_data))) } api_models::payments::PaymentMethodData::Crypto(crypto_data) => { Self::Crypto(From::from(crypto_data)) } api_models::payments::PaymentMethodData::MandatePayment => Self::MandatePayment, api_models::payments::PaymentMethodData::Reward => Self::Reward, api_models::payments::PaymentMethodData::RealTimePayment(real_time_payment_data) => { Self::RealTimePayment(Box::new(From::from(*real_time_payment_data))) } api_models::payments::PaymentMethodData::Upi(upi_data) => { Self::Upi(From::from(upi_data)) } api_models::payments::PaymentMethodData::Voucher(voucher_data) => { Self::Voucher(From::from(voucher_data)) } api_models::payments::PaymentMethodData::GiftCard(gift_card) => { Self::GiftCard(Box::new(From::from(*gift_card))) } api_models::payments::PaymentMethodData::CardToken(card_token) => { Self::CardToken(From::from(card_token)) } api_models::payments::PaymentMethodData::OpenBanking(ob_data) => { Self::OpenBanking(From::from(ob_data)) } api_models::payments::PaymentMethodData::MobilePayment(mobile_payment_data) => { Self::MobilePayment(From::from(mobile_payment_data)) } } } } impl From<api_models::payments::ProxyPaymentMethodData> for ExternalVaultPaymentMethodData { fn from(api_model_payment_method_data: api_models::payments::ProxyPaymentMethodData) -> Self { match api_model_payment_method_data { api_models::payments::ProxyPaymentMethodData::VaultDataCard(card_data) => { Self::Card(Box::new(ExternalVaultCard::from(*card_data))) } api_models::payments::ProxyPaymentMethodData::VaultToken(vault_data) => { Self::VaultToken(VaultToken::from(vault_data)) } } } } impl From<api_models::payments::ProxyCardData> for ExternalVaultCard { fn from(value: api_models::payments::ProxyCardData) -> Self { let api_models::payments::ProxyCardData { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, bin_number, last_four, card_issuer, card_network, card_type, card_issuing_country, bank_code, nick_name, } = value; Self { card_number, card_exp_month, card_exp_year, card_cvc, bin_number, last_four, card_issuer, card_network, card_type, card_issuing_country, bank_code, nick_name, card_holder_name, co_badged_card_data: None, } } } impl From<api_models::payments::VaultToken> for VaultToken { fn from(value: api_models::payments::VaultToken) -> Self { let api_models::payments::VaultToken { card_cvc, card_holder_name, } = value; Self { card_cvc, card_holder_name, } } } impl From<( api_models::payments::Card, Option<payment_methods::CoBadgedCardData>, )> for Card { fn from( (value, co_badged_card_data_optional): ( api_models::payments::Card, Option<payment_methods::CoBadgedCardData>, ), ) -> Self { let api_models::payments::Card { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type, card_issuing_country, bank_code, nick_name, } = value; Self { card_number, card_exp_month, card_exp_year, card_cvc, card_issuer, card_network, card_type, card_issuing_country, bank_code, nick_name, card_holder_name, co_badged_card_data: co_badged_card_data_optional, } } } #[cfg(feature = "v2")] impl From<( payment_methods::CardDetail, Secret<String>, Option<Secret<String>>, )> for Card { fn from( (card_detail, card_cvc, card_holder_name): ( payment_methods::CardDetail, Secret<String>, Option<Secret<String>>, ), ) -> Self { Self { card_number: card_detail.card_number, card_exp_month: card_detail.card_exp_month, card_exp_year: card_detail.card_exp_year, card_cvc, card_issuer: card_detail.card_issuer, card_network: card_detail.card_network, card_type: card_detail.card_type.map(|val| val.to_string()), card_issuing_country: card_detail.card_issuing_country.map(|val| val.to_string()), bank_code: None, nick_name: card_detail.nick_name, card_holder_name: card_holder_name.or(card_detail.card_holder_name), co_badged_card_data: None, } } } #[cfg(feature = "v2")] impl From<Card> for payment_methods::CardDetail { fn from(card: Card) -> Self { Self { card_number: card.card_number, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, nick_name: card.nick_name, card_issuing_country: None, card_network: card.card_network, card_issuer: card.card_issuer, card_type: None, card_cvc: Some(card.card_cvc), } } } #[cfg(feature = "v2")] impl From<ExternalVaultCard> for payment_methods::ProxyCardDetails { fn from(card: ExternalVaultCard) -> Self { Self { card_number: card.card_number, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, nick_name: card.nick_name, card_issuing_country: card.card_issuing_country, card_network: card.card_network, card_issuer: card.card_issuer, card_type: card.card_type, card_cvc: Some(card.card_cvc), bin_number: card.bin_number, last_four: card.last_four, } } } impl From<api_models::payments::CardRedirectData> for CardRedirectData { fn from(value: api_models::payments::CardRedirectData) -> Self { match value { api_models::payments::CardRedirectData::Knet {} => Self::Knet {}, api_models::payments::CardRedirectData::Benefit {} => Self::Benefit {}, api_models::payments::CardRedirectData::MomoAtm {} => Self::MomoAtm {}, api_models::payments::CardRedirectData::CardRedirect {} => Self::CardRedirect {}, } } } impl From<CardRedirectData> for api_models::payments::CardRedirectData { fn from(value: CardRedirectData) -> Self { match value { CardRedirectData::Knet {} => Self::Knet {}, CardRedirectData::Benefit {} => Self::Benefit {}, CardRedirectData::MomoAtm {} => Self::MomoAtm {}, CardRedirectData::CardRedirect {} => Self::CardRedirect {}, } } } impl From<api_models::payments::WalletData> for WalletData { fn from(value: api_models::payments::WalletData) -> Self { match value { api_models::payments::WalletData::AliPayQr(_) => Self::AliPayQr(Box::new(AliPayQr {})), api_models::payments::WalletData::AliPayRedirect(_) => { Self::AliPayRedirect(AliPayRedirection {}) } api_models::payments::WalletData::AliPayHkRedirect(_) => { Self::AliPayHkRedirect(AliPayHkRedirection {}) } api_models::payments::WalletData::AmazonPay(amazon_pay_data) => { Self::AmazonPay(AmazonPayWalletData::from(amazon_pay_data)) } api_models::payments::WalletData::AmazonPayRedirect(_) => { Self::AmazonPayRedirect(Box::new(AmazonPayRedirect {})) } api_models::payments::WalletData::Skrill(_) => Self::Skrill(Box::new(SkrillData {})), api_models::payments::WalletData::Paysera(_) => Self::Paysera(Box::new(PayseraData {})), api_models::payments::WalletData::MomoRedirect(_) => { Self::MomoRedirect(MomoRedirection {}) } api_models::payments::WalletData::KakaoPayRedirect(_) => { Self::KakaoPayRedirect(KakaoPayRedirection {}) } api_models::payments::WalletData::GoPayRedirect(_) => { Self::GoPayRedirect(GoPayRedirection {}) } api_models::payments::WalletData::GcashRedirect(_) => { Self::GcashRedirect(GcashRedirection {}) } api_models::payments::WalletData::ApplePay(apple_pay_data) => { Self::ApplePay(ApplePayWalletData::from(apple_pay_data)) } api_models::payments::WalletData::ApplePayRedirect(_) => { Self::ApplePayRedirect(Box::new(ApplePayRedirectData {})) } api_models::payments::WalletData::ApplePayThirdPartySdk(apple_pay_sdk_data) => { Self::ApplePayThirdPartySdk(Box::new(ApplePayThirdPartySdkData { token: apple_pay_sdk_data.token, })) } api_models::payments::WalletData::DanaRedirect {} => Self::DanaRedirect {}, api_models::payments::WalletData::GooglePay(google_pay_data) => { Self::GooglePay(GooglePayWalletData::from(google_pay_data)) } api_models::payments::WalletData::GooglePayRedirect(_) => { Self::GooglePayRedirect(Box::new(GooglePayRedirectData {})) } api_models::payments::WalletData::GooglePayThirdPartySdk(google_pay_sdk_data) => { Self::GooglePayThirdPartySdk(Box::new(GooglePayThirdPartySdkData { token: google_pay_sdk_data.token, })) } api_models::payments::WalletData::MbWayRedirect(..) => { Self::MbWayRedirect(Box::new(MbWayRedirection {})) } api_models::payments::WalletData::MobilePayRedirect(_) => { Self::MobilePayRedirect(Box::new(MobilePayRedirection {})) } api_models::payments::WalletData::PaypalRedirect(paypal_redirect_data) => { Self::PaypalRedirect(PaypalRedirection { email: paypal_redirect_data.email, }) } api_models::payments::WalletData::PaypalSdk(paypal_sdk_data) => { Self::PaypalSdk(PayPalWalletData { token: paypal_sdk_data.token, }) } api_models::payments::WalletData::Paze(paze_data) => { Self::Paze(PazeWalletData::from(paze_data)) } api_models::payments::WalletData::SamsungPay(samsung_pay_data) => { Self::SamsungPay(Box::new(SamsungPayWalletData::from(samsung_pay_data))) } api_models::payments::WalletData::TwintRedirect {} => Self::TwintRedirect {}, api_models::payments::WalletData::VippsRedirect {} => Self::VippsRedirect {}, api_models::payments::WalletData::TouchNGoRedirect(_) => { Self::TouchNGoRedirect(Box::new(TouchNGoRedirection {})) } api_models::payments::WalletData::WeChatPayRedirect(_) => { Self::WeChatPayRedirect(Box::new(WeChatPayRedirection {})) } api_models::payments::WalletData::WeChatPayQr(_) => { Self::WeChatPayQr(Box::new(WeChatPayQr {})) } api_models::payments::WalletData::CashappQr(_) => { Self::CashappQr(Box::new(CashappQr {})) } api_models::payments::WalletData::SwishQr(_) => Self::SwishQr(SwishQrData {}), api_models::payments::WalletData::Mifinity(mifinity_data) => { Self::Mifinity(MifinityData { date_of_birth: mifinity_data.date_of_birth, language_preference: mifinity_data.language_preference, }) } api_models::payments::WalletData::BluecodeRedirect {} => Self::BluecodeRedirect {}, api_models::payments::WalletData::RevolutPay(_) => Self::RevolutPay(RevolutPayData {}), } } } impl From<api_models::payments::GooglePayWalletData> for GooglePayWalletData { fn from(value: api_models::payments::GooglePayWalletData) -> Self { Self { pm_type: value.pm_type, description: value.description, info: GooglePayPaymentMethodInfo { card_network: value.info.card_network, card_details: value.info.card_details, assurance_details: value.info.assurance_details.map(|info| { GooglePayAssuranceDetails { card_holder_authenticated: info.card_holder_authenticated, account_verified: info.account_verified, } }), card_funding_source: value.info.card_funding_source, }, tokenization_data: value.tokenization_data, } } } impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData { fn from(value: api_models::payments::ApplePayWalletData) -> Self { Self { payment_data: value.payment_data, payment_method: ApplepayPaymentMethod { display_name: value.payment_method.display_name, network: value.payment_method.network, pm_type: value.payment_method.pm_type, }, transaction_identifier: value.transaction_identifier, } } } impl From<api_models::payments::AmazonPayWalletData> for AmazonPayWalletData { fn from(value: api_models::payments::AmazonPayWalletData) -> Self { Self { checkout_session_id: value.checkout_session_id, } } } impl From<api_models::payments::SamsungPayTokenData> for SamsungPayTokenData { fn from(samsung_pay_token_data: api_models::payments::SamsungPayTokenData) -> Self { Self { three_ds_type: samsung_pay_token_data.three_ds_type, version: samsung_pay_token_data.version, data: samsung_pay_token_data.data, } } } impl From<api_models::payments::PazeWalletData> for PazeWalletData { fn from(value: api_models::payments::PazeWalletData) -> Self { Self { complete_response: value.complete_response, } } } impl From<Box<api_models::payments::SamsungPayWalletData>> for SamsungPayWalletData { fn from(value: Box<api_models::payments::SamsungPayWalletData>) -> Self { match value.payment_credential { api_models::payments::SamsungPayWalletCredentials::SamsungPayWalletDataForApp( samsung_pay_app_wallet_data, ) => Self { payment_credential: SamsungPayWalletCredentials { method: samsung_pay_app_wallet_data.method, recurring_payment: samsung_pay_app_wallet_data.recurring_payment, card_brand: samsung_pay_app_wallet_data.payment_card_brand.into(), dpan_last_four_digits: samsung_pay_app_wallet_data.payment_last4_dpan, card_last_four_digits: samsung_pay_app_wallet_data.payment_last4_fpan, token_data: samsung_pay_app_wallet_data.token_data.into(), }, }, api_models::payments::SamsungPayWalletCredentials::SamsungPayWalletDataForWeb( samsung_pay_web_wallet_data, ) => Self { payment_credential: SamsungPayWalletCredentials { method: samsung_pay_web_wallet_data.method, recurring_payment: samsung_pay_web_wallet_data.recurring_payment, card_brand: samsung_pay_web_wallet_data.card_brand.into(), dpan_last_four_digits: None, card_last_four_digits: samsung_pay_web_wallet_data.card_last_four_digits, token_data: samsung_pay_web_wallet_data.token_data.into(), }, }, } } } impl From<api_models::payments::PayLaterData> for PayLaterData { fn from(value: api_models::payments::PayLaterData) -> Self { match value { api_models::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect {}, api_models::payments::PayLaterData::KlarnaSdk { token } => Self::KlarnaSdk { token }, api_models::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect {}, api_models::payments::PayLaterData::FlexitiRedirect {} => Self::FlexitiRedirect {}, api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { Self::AfterpayClearpayRedirect {} } api_models::payments::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect {}, api_models::payments::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect {}, api_models::payments::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect {}, api_models::payments::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect {}, api_models::payments::PayLaterData::BreadpayRedirect {} => Self::BreadpayRedirect {}, } } } impl From<api_models::payments::BankRedirectData> for BankRedirectData { fn from(value: api_models::payments::BankRedirectData) -> Self { match value { api_models::payments::BankRedirectData::BancontactCard { card_number, card_exp_month, card_exp_year, card_holder_name, .. } => Self::BancontactCard { card_number, card_exp_month, card_exp_year, card_holder_name, }, api_models::payments::BankRedirectData::Bizum {} => Self::Bizum {}, api_models::payments::BankRedirectData::Blik { blik_code } => Self::Blik { blik_code }, api_models::payments::BankRedirectData::Eps { bank_name, country, .. } => Self::Eps { bank_name, country }, api_models::payments::BankRedirectData::Giropay { bank_account_bic, bank_account_iban, country, .. } => Self::Giropay { bank_account_bic, bank_account_iban, country, }, api_models::payments::BankRedirectData::Ideal { bank_name, .. } => { Self::Ideal { bank_name } } api_models::payments::BankRedirectData::Interac { country, email } => { Self::Interac { country, email } } api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => { Self::OnlineBankingCzechRepublic { issuer } } api_models::payments::BankRedirectData::OnlineBankingFinland { email } => { Self::OnlineBankingFinland { email } } api_models::payments::BankRedirectData::OnlineBankingPoland { issuer } => { Self::OnlineBankingPoland { issuer } } api_models::payments::BankRedirectData::OnlineBankingSlovakia { issuer } => { Self::OnlineBankingSlovakia { issuer } } api_models::payments::BankRedirectData::OpenBankingUk { country, issuer, .. } => Self::OpenBankingUk { country, issuer }, api_models::payments::BankRedirectData::Przelewy24 { bank_name, .. } => { Self::Przelewy24 { bank_name } } api_models::payments::BankRedirectData::Sofort { preferred_language, country, .. } => Self::Sofort { country, preferred_language, }, api_models::payments::BankRedirectData::Trustly { country } => Self::Trustly { country: Some(country), }, api_models::payments::BankRedirectData::OnlineBankingFpx { issuer } => { Self::OnlineBankingFpx { issuer } } api_models::payments::BankRedirectData::OnlineBankingThailand { issuer } => { Self::OnlineBankingThailand { issuer } } api_models::payments::BankRedirectData::LocalBankRedirect { .. } => { Self::LocalBankRedirect {} } api_models::payments::BankRedirectData::Eft { provider } => Self::Eft { provider }, } } } impl From<api_models::payments::CryptoData> for CryptoData { fn from(value: api_models::payments::CryptoData) -> Self { let api_models::payments::CryptoData { pay_currency, network, } = value; Self { pay_currency, network, } } } impl From<CryptoData> for api_models::payments::CryptoData { fn from(value: CryptoData) -> Self { let CryptoData { pay_currency, network, } = value; Self { pay_currency, network, } } } impl From<api_models::payments::UpiData> for UpiData { fn from(value: api_models::payments::UpiData) -> Self { match value { api_models::payments::UpiData::UpiCollect(upi) => { Self::UpiCollect(UpiCollectData { vpa_id: upi.vpa_id }) } api_models::payments::UpiData::UpiIntent(_) => Self::UpiIntent(UpiIntentData {}), api_models::payments::UpiData::UpiQr(_) => Self::UpiQr(UpiQrData {}), } } } impl From<UpiData> for api_models::payments::additional_info::UpiAdditionalData { fn from(value: UpiData) -> Self { match value { UpiData::UpiCollect(upi) => Self::UpiCollect(Box::new( payment_additional_types::UpiCollectAdditionalData { vpa_id: upi.vpa_id.map(MaskedUpiVpaId::from), }, )), UpiData::UpiIntent(_) => { Self::UpiIntent(Box::new(api_models::payments::UpiIntentData {})) } UpiData::UpiQr(_) => Self::UpiQr(Box::new(api_models::payments::UpiQrData {})), } } } impl From<api_models::payments::VoucherData> for VoucherData { fn from(value: api_models::payments::VoucherData) -> Self { match value { api_models::payments::VoucherData::Boleto(boleto_data) => { Self::Boleto(Box::new(BoletoVoucherData { social_security_number: boleto_data.social_security_number, bank_number: boleto_data.bank_number, document_type: boleto_data.document_type, fine_percentage: boleto_data.fine_percentage, fine_quantity_days: boleto_data.fine_quantity_days, interest_percentage: boleto_data.interest_percentage, write_off_quantity_days: boleto_data.write_off_quantity_days, messages: boleto_data.messages, due_date: boleto_data.due_date, })) } api_models::payments::VoucherData::Alfamart(_) => { Self::Alfamart(Box::new(AlfamartVoucherData {})) } api_models::payments::VoucherData::Indomaret(_) => { Self::Indomaret(Box::new(IndomaretVoucherData {})) } api_models::payments::VoucherData::SevenEleven(_) | api_models::payments::VoucherData::Lawson(_) | api_models::payments::VoucherData::MiniStop(_) | api_models::payments::VoucherData::FamilyMart(_) | api_models::payments::VoucherData::Seicomart(_) | api_models::payments::VoucherData::PayEasy(_) => { Self::SevenEleven(Box::new(JCSVoucherData {})) } api_models::payments::VoucherData::Efecty => Self::Efecty, api_models::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo, api_models::payments::VoucherData::RedCompra => Self::RedCompra, api_models::payments::VoucherData::RedPagos => Self::RedPagos, api_models::payments::VoucherData::Oxxo => Self::Oxxo, } } } impl From<Box<BoletoVoucherData>> for Box<api_models::payments::BoletoVoucherData> { fn from(value: Box<BoletoVoucherData>) -> Self { Self::new(api_models::payments::BoletoVoucherData { social_security_number: value.social_security_number, bank_number: value.bank_number, document_type: value.document_type, fine_percentage: value.fine_percentage, fine_quantity_days: value.fine_quantity_days, interest_percentage: value.interest_percentage, write_off_quantity_days: value.write_off_quantity_days, messages: value.messages, due_date: value.due_date, }) } } impl From<Box<AlfamartVoucherData>> for Box<api_models::payments::AlfamartVoucherData> { fn from(_value: Box<AlfamartVoucherData>) -> Self { Self::new(api_models::payments::AlfamartVoucherData { first_name: None, last_name: None, email: None, }) } } impl From<Box<IndomaretVoucherData>> for Box<api_models::payments::IndomaretVoucherData> { fn from(_value: Box<IndomaretVoucherData>) -> Self { Self::new(api_models::payments::IndomaretVoucherData { first_name: None, last_name: None, email: None, }) } } impl From<Box<JCSVoucherData>> for Box<api_models::payments::JCSVoucherData> { fn from(_value: Box<JCSVoucherData>) -> Self { Self::new(api_models::payments::JCSVoucherData { first_name: None, last_name: None, email: None, phone_number: None, }) } } impl From<VoucherData> for api_models::payments::VoucherData { fn from(value: VoucherData) -> Self { match value { VoucherData::Boleto(boleto_data) => Self::Boleto(boleto_data.into()), VoucherData::Alfamart(alfa_mart) => Self::Alfamart(alfa_mart.into()), VoucherData::Indomaret(info_maret) => Self::Indomaret(info_maret.into()), VoucherData::SevenEleven(jcs_data) | VoucherData::Lawson(jcs_data) | VoucherData::MiniStop(jcs_data) | VoucherData::FamilyMart(jcs_data) | VoucherData::Seicomart(jcs_data) | VoucherData::PayEasy(jcs_data) => Self::SevenEleven(jcs_data.into()), VoucherData::Efecty => Self::Efecty, VoucherData::PagoEfectivo => Self::PagoEfectivo, VoucherData::RedCompra => Self::RedCompra, VoucherData::RedPagos => Self::RedPagos, VoucherData::Oxxo => Self::Oxxo, } } } impl From<api_models::payments::GiftCardData> for GiftCardData { fn from(value: api_models::payments::GiftCardData) -> Self { match value { api_models::payments::GiftCardData::Givex(details) => Self::Givex(GiftCardDetails { number: details.number, cvc: details.cvc, }), api_models::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCard {}, api_models::payments::GiftCardData::BhnCardNetwork(details) => { Self::BhnCardNetwork(BHNGiftCardDetails { account_number: details.account_number, pin: details.pin, cvv2: details.cvv2, expiration_date: details.expiration_date, }) } } } } impl From<GiftCardData> for payment_additional_types::GiftCardAdditionalData { fn from(value: GiftCardData) -> Self { match value { GiftCardData::Givex(details) => Self::Givex(Box::new( payment_additional_types::GivexGiftCardAdditionalData { last4: details .number .peek() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>() .into(), }, )), GiftCardData::PaySafeCard {} => Self::PaySafeCard {}, GiftCardData::BhnCardNetwork(_) => Self::BhnCardNetwork {}, } } } impl From<api_models::payments::CardToken> for CardToken { fn from(value: api_models::payments::CardToken) -> Self { let api_models::payments::CardToken { card_holder_name, card_cvc, } = value; Self { card_holder_name, card_cvc, } } } impl From<CardToken> for payment_additional_types::CardTokenAdditionalData { fn from(value: CardToken) -> Self { let CardToken { card_holder_name, .. } = value; Self { card_holder_name } } } impl From<api_models::payments::BankDebitData> for BankDebitData { fn from(value: api_models::payments::BankDebitData) -> Self { match value { api_models::payments::BankDebitData::AchBankDebit { account_number, routing_number, card_holder_name, bank_account_holder_name, bank_name, bank_type, bank_holder_type, .. } => Self::AchBankDebit { account_number, routing_number, card_holder_name, bank_account_holder_name, bank_name, bank_type, bank_holder_type, }, api_models::payments::BankDebitData::SepaBankDebit { iban, bank_account_holder_name, .. } => Self::SepaBankDebit { iban, bank_account_holder_name, }, api_models::payments::BankDebitData::SepaGuarenteedBankDebit { iban, bank_account_holder_name, .. } => Self::SepaBankDebit { iban, bank_account_holder_name, }, api_models::payments::BankDebitData::BecsBankDebit { account_number, bsb_number, bank_account_holder_name, .. } => Self::BecsBankDebit { account_number, bsb_number, bank_account_holder_name, }, api_models::payments::BankDebitData::BacsBankDebit { account_number, sort_code, bank_account_holder_name, .. } => Self::BacsBankDebit { account_number, sort_code, bank_account_holder_name, }, } } } impl From<BankDebitData> for api_models::payments::additional_info::BankDebitAdditionalData { fn from(value: BankDebitData) -> Self { match value { BankDebitData::AchBankDebit { account_number, routing_number, bank_name, bank_type, bank_holder_type, card_holder_name, bank_account_holder_name, } => Self::Ach(Box::new( payment_additional_types::AchBankDebitAdditionalData { account_number: MaskedBankAccount::from(account_number), routing_number: MaskedRoutingNumber::from(routing_number), bank_name, bank_type, bank_holder_type, card_holder_name, bank_account_holder_name, }, )), BankDebitData::SepaBankDebit { iban, bank_account_holder_name, } => Self::Sepa(Box::new( payment_additional_types::SepaBankDebitAdditionalData { iban: MaskedIban::from(iban), bank_account_holder_name, }, )), BankDebitData::SepaGuarenteedBankDebit { iban, bank_account_holder_name, } => Self::SepaGuarenteedDebit(Box::new( payment_additional_types::SepaBankDebitAdditionalData { iban: MaskedIban::from(iban), bank_account_holder_name, }, )), BankDebitData::BecsBankDebit { account_number, bsb_number, bank_account_holder_name, } => Self::Becs(Box::new( payment_additional_types::BecsBankDebitAdditionalData { account_number: MaskedBankAccount::from(account_number), bsb_number, bank_account_holder_name, }, )), BankDebitData::BacsBankDebit { account_number, sort_code, bank_account_holder_name, } => Self::Bacs(Box::new( payment_additional_types::BacsBankDebitAdditionalData { account_number: MaskedBankAccount::from(account_number), sort_code: MaskedSortCode::from(sort_code), bank_account_holder_name, }, )), } } } impl From<api_models::payments::BankTransferData> for BankTransferData { fn from(value: api_models::payments::BankTransferData) -> Self { match value { api_models::payments::BankTransferData::AchBankTransfer { .. } => { Self::AchBankTransfer {} } api_models::payments::BankTransferData::SepaBankTransfer { .. } => { Self::SepaBankTransfer {} } api_models::payments::BankTransferData::BacsBankTransfer { .. } => { Self::BacsBankTransfer {} } api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => { Self::MultibancoBankTransfer {} } api_models::payments::BankTransferData::PermataBankTransfer { .. } => { Self::PermataBankTransfer {} } api_models::payments::BankTransferData::BcaBankTransfer { .. } => { Self::BcaBankTransfer {} } api_models::payments::BankTransferData::BniVaBankTransfer { .. } => { Self::BniVaBankTransfer {} } api_models::payments::BankTransferData::BriVaBankTransfer { .. } => { Self::BriVaBankTransfer {} } api_models::payments::BankTransferData::CimbVaBankTransfer { .. } => { Self::CimbVaBankTransfer {} } api_models::payments::BankTransferData::DanamonVaBankTransfer { .. } => { Self::DanamonVaBankTransfer {} } api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } => { Self::MandiriVaBankTransfer {} } api_models::payments::BankTransferData::Pix { pix_key, cpf, cnpj, source_bank_account_id, destination_bank_account_id, expiry_date, } => Self::Pix { pix_key, cpf, cnpj, source_bank_account_id, destination_bank_account_id, expiry_date, }, api_models::payments::BankTransferData::Pse {} => Self::Pse {}, api_models::payments::BankTransferData::LocalBankTransfer { bank_code } => { Self::LocalBankTransfer { bank_code } } api_models::payments::BankTransferData::InstantBankTransfer {} => { Self::InstantBankTransfer {} } api_models::payments::BankTransferData::InstantBankTransferFinland {} => { Self::InstantBankTransferFinland {} } api_models::payments::BankTransferData::InstantBankTransferPoland {} => { Self::InstantBankTransferPoland {} } api_models::payments::BankTransferData::IndonesianBankTransfer { bank_name } => { Self::IndonesianBankTransfer { bank_name } } } } } impl From<BankTransferData> for api_models::payments::additional_info::BankTransferAdditionalData { fn from(value: BankTransferData) -> Self { match value { BankTransferData::AchBankTransfer {} => Self::Ach {}, BankTransferData::SepaBankTransfer {} => Self::Sepa {}, BankTransferData::BacsBankTransfer {} => Self::Bacs {}, BankTransferData::MultibancoBankTransfer {} => Self::Multibanco {}, BankTransferData::PermataBankTransfer {} => Self::Permata {}, BankTransferData::BcaBankTransfer {} => Self::Bca {}, BankTransferData::BniVaBankTransfer {} => Self::BniVa {}, BankTransferData::BriVaBankTransfer {} => Self::BriVa {}, BankTransferData::CimbVaBankTransfer {} => Self::CimbVa {}, BankTransferData::DanamonVaBankTransfer {} => Self::DanamonVa {}, BankTransferData::MandiriVaBankTransfer {} => Self::MandiriVa {}, BankTransferData::Pix { pix_key, cpf, cnpj, source_bank_account_id, destination_bank_account_id, expiry_date, } => Self::Pix(Box::new( api_models::payments::additional_info::PixBankTransferAdditionalData { pix_key: pix_key.map(MaskedBankAccount::from), cpf: cpf.map(MaskedBankAccount::from), cnpj: cnpj.map(MaskedBankAccount::from), source_bank_account_id, destination_bank_account_id, expiry_date, }, )), BankTransferData::Pse {} => Self::Pse {}, BankTransferData::LocalBankTransfer { bank_code } => Self::LocalBankTransfer(Box::new( api_models::payments::additional_info::LocalBankTransferAdditionalData { bank_code: bank_code.map(MaskedBankAccount::from), }, )), BankTransferData::InstantBankTransfer {} => Self::InstantBankTransfer {}, BankTransferData::InstantBankTransferFinland {} => Self::InstantBankTransferFinland {}, BankTransferData::InstantBankTransferPoland {} => Self::InstantBankTransferPoland {}, BankTransferData::IndonesianBankTransfer { bank_name } => { Self::IndonesianBankTransfer { bank_name } } } } } impl From<api_models::payments::RealTimePaymentData> for RealTimePaymentData { fn from(value: api_models::payments::RealTimePaymentData) -> Self { match value { api_models::payments::RealTimePaymentData::Fps {} => Self::Fps {}, api_models::payments::RealTimePaymentData::DuitNow {} => Self::DuitNow {}, api_models::payments::RealTimePaymentData::PromptPay {} => Self::PromptPay {}, api_models::payments::RealTimePaymentData::VietQr {} => Self::VietQr {}, } } } impl From<RealTimePaymentData> for api_models::payments::RealTimePaymentData { fn from(value: RealTimePaymentData) -> Self { match value { RealTimePaymentData::Fps {} => Self::Fps {}, RealTimePaymentData::DuitNow {} => Self::DuitNow {}, RealTimePaymentData::PromptPay {} => Self::PromptPay {}, RealTimePaymentData::VietQr {} => Self::VietQr {}, } } } impl From<api_models::payments::OpenBankingData> for OpenBankingData { fn from(value: api_models::payments::OpenBankingData) -> Self { match value { api_models::payments::OpenBankingData::OpenBankingPIS {} => Self::OpenBankingPIS {}, } } } impl From<OpenBankingData> for api_models::payments::OpenBankingData { fn from(value: OpenBankingData) -> Self { match value { OpenBankingData::OpenBankingPIS {} => Self::OpenBankingPIS {}, } } } impl From<api_models::payments::MobilePaymentData> for MobilePaymentData { fn from(value: api_models::payments::MobilePaymentData) -> Self { match value { api_models::payments::MobilePaymentData::DirectCarrierBilling { msisdn, client_uid, } => Self::DirectCarrierBilling { msisdn, client_uid }, } } } impl From<MobilePaymentData> for api_models::payments::MobilePaymentData { fn from(value: MobilePaymentData) -> Self { match value { MobilePaymentData::DirectCarrierBilling { msisdn, client_uid } => { Self::DirectCarrierBilling { msisdn, client_uid } } } } } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCardValue1 { pub card_number: String, pub exp_year: String, pub exp_month: String, pub nickname: Option<String>, pub card_last_four: Option<String>, pub card_token: Option<String>, pub card_holder_name: Option<Secret<String>>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCardValue2 { pub card_security_code: Option<String>, pub card_fingerprint: Option<String>, pub external_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub payment_method_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedWalletValue1 { pub data: WalletData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedWalletValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankTransferValue1 { pub data: BankTransferData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankTransferValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankRedirectValue1 { pub data: BankRedirectData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankRedirectValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankDebitValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankDebitValue1 { pub data: BankDebitData, } 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 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::Skrill(_) => api_enums::PaymentMethodType::Skrill, Self::Paysera(_) => api_enums::PaymentMethodType::Paysera, 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::AmazonPay(_) => api_enums::PaymentMethodType::AmazonPay, 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::BluecodeRedirect {} => api_enums::PaymentMethodType::Bluecode, 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, Self::RevolutPay(_) => api_enums::PaymentMethodType::RevolutPay, } } } 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::FlexitiRedirect { .. } => api_enums::PaymentMethodType::Flexiti, 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, Self::BreadpayRedirect {} => api_enums::PaymentMethodType::Breadpay, } } } 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::SepaGuarenteedBankDebit { .. } => { api_enums::PaymentMethodType::SepaGuarenteedDebit } 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::Sepa, 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, Self::InstantBankTransferFinland {} => { api_enums::PaymentMethodType::InstantBankTransferFinland } Self::InstantBankTransferPoland {} => { api_enums::PaymentMethodType::InstantBankTransferPoland } Self::IndonesianBankTransfer { .. } => { api_enums::PaymentMethodType::IndonesianBankTransfer } } } } 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, Self::UpiQr(_) => api_enums::PaymentMethodType::UpiQr, } } } 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, Self::BhnCardNetwork(_) => api_enums::PaymentMethodType::BhnCardNetwork, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } 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: None, 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 From<ApplePayWalletData> for payment_methods::PaymentMethodDataWalletInfo { fn from(item: ApplePayWalletData) -> Self { Self { last4: item .payment_method .display_name .chars() .rev() .take(4) .collect::<Vec<_>>() .into_iter() .rev() .collect(), card_network: item.payment_method.network, card_type: Some(item.payment_method.pm_type), } } } impl From<GooglePayWalletData> for payment_methods::PaymentMethodDataWalletInfo { fn from(item: GooglePayWalletData) -> Self { Self { last4: item.info.card_details, card_network: item.info.card_network, card_type: Some(item.pm_type), } } } #[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)] pub enum PaymentMethodsData { Card(CardDetailsPaymentMethod), BankDetails(payment_methods::PaymentMethodDataBankCreds), //PaymentMethodDataBankCreds and its transformations should be moved to the domain models WalletDetails(payment_methods::PaymentMethodDataWalletInfo), //PaymentMethodDataWalletInfo and its transformations should be moved to the domain models NetworkToken(NetworkTokenDetailsPaymentMethod), } impl PaymentMethodsData { #[cfg(feature = "v1")] pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> { if let Self::Card(card) = self { card.co_badged_card_data.clone() } else { None } } #[cfg(feature = "v2")] pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> { todo!() } #[cfg(feature = "v1")] pub fn get_additional_payout_method_data( &self, ) -> Option<payout_method_utils::AdditionalPayoutMethodData> { match self { Self::Card(card_details) => { router_env::logger::info!("Populating AdditionalPayoutMethodData from Card payment method data for recurring payout"); Some(payout_method_utils::AdditionalPayoutMethodData::Card( Box::new(payout_method_utils::CardAdditionalData { card_issuer: card_details.card_issuer.clone(), card_network: card_details.card_network.clone(), bank_code: None, card_type: card_details.card_type.clone(), card_issuing_country: card_details.issuer_country.clone(), last4: card_details.last4_digits.clone(), card_isin: card_details.card_isin.clone(), card_extended_bin: None, card_exp_month: card_details.expiry_month.clone(), card_exp_year: card_details.expiry_year.clone(), card_holder_name: card_details.card_holder_name.clone(), }), )) } Self::BankDetails(_) | Self::WalletDetails(_) | Self::NetworkToken(_) => None, } } pub fn get_card_details(&self) -> Option<CardDetailsPaymentMethod> { if let Self::Card(card) = self { Some(card.clone()) } else { None } } } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct NetworkTokenDetailsPaymentMethod { pub last4_digits: Option<String>, pub issuer_country: Option<common_enums::CountryAlpha2>, pub network_token_expiry_month: Option<Secret<String>>, pub network_token_expiry_year: Option<Secret<String>>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, pub card_isin: Option<String>, pub card_issuer: Option<String>, pub card_network: Option<api_enums::CardNetwork>, pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, } fn saved_in_locker_default() -> bool { true } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)] pub struct CardDetailsPaymentMethod { pub last4_digits: Option<String>, pub issuer_country: Option<String>, pub expiry_month: Option<Secret<String>>, pub expiry_year: Option<Secret<String>>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, pub card_isin: Option<String>, pub card_issuer: Option<String>, pub card_network: Option<api_enums::CardNetwork>, pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct CardDetailsPaymentMethod { pub last4_digits: Option<String>, pub issuer_country: Option<String>, pub expiry_month: Option<Secret<String>>, pub expiry_year: Option<Secret<String>>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, pub card_isin: Option<String>, pub card_issuer: Option<String>, pub card_network: Option<api_enums::CardNetwork>, pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, } #[cfg(feature = "v2")] impl CardDetailsPaymentMethod { pub fn to_card_details_from_locker(self) -> payment_methods::CardDetailFromLocker { payment_methods::CardDetailFromLocker { card_number: None, card_holder_name: self.card_holder_name.clone(), card_issuer: self.card_issuer.clone(), card_network: self.card_network.clone(), card_type: self.card_type.clone(), issuer_country: self.clone().get_issuer_country_alpha2(), last4_digits: self.last4_digits, expiry_month: self.expiry_month, expiry_year: self.expiry_year, card_fingerprint: None, nick_name: self.nick_name, card_isin: self.card_isin, saved_to_locker: self.saved_to_locker, } } pub fn get_issuer_country_alpha2(self) -> Option<common_enums::CountryAlpha2> { self.issuer_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten() } } #[cfg(feature = "v1")] impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod { fn from(item: payment_methods::CardDetail) -> Self { Self { issuer_country: item.card_issuing_country.map(|c| c.to_string()), last4_digits: Some(item.card_number.get_last4()), expiry_month: Some(item.card_exp_month), expiry_year: Some(item.card_exp_year), card_holder_name: item.card_holder_name, nick_name: item.nick_name, card_isin: None, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, co_badged_card_data: None, } } } #[cfg(feature = "v2")] impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod { fn from(item: payment_methods::CardDetail) -> Self { Self { issuer_country: item.card_issuing_country.map(|c| c.to_string()), last4_digits: Some(item.card_number.get_last4()), expiry_month: Some(item.card_exp_month), expiry_year: Some(item.card_exp_year), card_holder_name: item.card_holder_name, nick_name: item.nick_name, card_isin: None, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, } } } #[cfg(feature = "v2")] impl From<NetworkTokenDetails> for NetworkTokenDetailsPaymentMethod { fn from(item: NetworkTokenDetails) -> Self { Self { issuer_country: item.card_issuing_country, last4_digits: Some(item.network_token.get_last4()), network_token_expiry_month: Some(item.network_token_exp_month), network_token_expiry_year: Some(item.network_token_exp_year), card_holder_name: item.card_holder_name, nick_name: item.nick_name, card_isin: None, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct SingleUsePaymentMethodToken { pub token: Secret<String>, pub merchant_connector_id: id_type::MerchantConnectorAccountId, } #[cfg(feature = "v2")] impl SingleUsePaymentMethodToken { pub fn get_single_use_token_from_payment_method_token( token: Secret<String>, mca_id: id_type::MerchantConnectorAccountId, ) -> Self { Self { token, merchant_connector_id: mca_id, } } } impl From<NetworkTokenDetailsPaymentMethod> for payment_methods::NetworkTokenDetailsPaymentMethod { fn from(item: NetworkTokenDetailsPaymentMethod) -> Self { Self { last4_digits: item.last4_digits, issuer_country: item.issuer_country, network_token_expiry_month: item.network_token_expiry_month, network_token_expiry_year: item.network_token_expiry_year, nick_name: item.nick_name, card_holder_name: item.card_holder_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct SingleUseTokenKey(String); #[cfg(feature = "v2")] impl SingleUseTokenKey { pub fn store_key(payment_method_id: &id_type::GlobalPaymentMethodId) -> Self { let new_token = format!("single_use_token_{}", payment_method_id.get_string_repr()); Self(new_token) } pub fn get_store_key(&self) -> &str { &self.0 } } #[cfg(feature = "v1")] impl From<Card> for payment_methods::CardDetail { fn from(card_data: Card) -> Self { Self { card_number: card_data.card_number.clone(), card_exp_month: card_data.card_exp_month.clone(), card_exp_year: card_data.card_exp_year.clone(), card_holder_name: None, nick_name: None, card_issuing_country: None, card_network: card_data.card_network.clone(), card_issuer: None, card_type: None, } } } #[cfg(feature = "v1")] impl From<NetworkTokenData> for payment_methods::CardDetail { fn from(network_token_data: NetworkTokenData) -> Self { Self { card_number: network_token_data.token_number.clone(), card_exp_month: network_token_data.token_exp_month.clone(), card_exp_year: network_token_data.token_exp_year.clone(), card_holder_name: None, nick_name: None, card_issuing_country: None, card_network: network_token_data.card_network.clone(), card_issuer: None, card_type: None, } } } #[cfg(feature = "v1")] impl From<( payment_methods::CardDetail, Option<&CardToken>, Option<payment_methods::CoBadgedCardData>, )> for Card { fn from( value: ( payment_methods::CardDetail, Option<&CardToken>, Option<payment_methods::CoBadgedCardData>, ), ) -> Self { let ( payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_issuing_country, card_type, }, card_token_data, co_badged_card_data, ) = value; // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked let name_on_card = if let Some(name) = card_holder_name.clone() { if name.clone().expose().is_empty() { card_token_data .and_then(|token_data| token_data.card_holder_name.clone()) .or(Some(name)) } else { card_holder_name } } else { card_token_data.and_then(|token_data| token_data.card_holder_name.clone()) }; Self { card_number, card_exp_month, card_exp_year, card_holder_name: name_on_card, card_cvc: card_token_data .cloned() .unwrap_or_default() .card_cvc .unwrap_or_default(), card_issuer, card_network, card_type, card_issuing_country, bank_code: None, nick_name, co_badged_card_data, } } } #[cfg(feature = "v1")] impl TryFrom<( cards::CardNumber, Option<&CardToken>, Option<payment_methods::CoBadgedCardData>, CardDetailsPaymentMethod, )> for Card { type Error = error_stack::Report<common_utils::errors::ValidationError>; fn try_from( value: ( cards::CardNumber, Option<&CardToken>, Option<payment_methods::CoBadgedCardData>, CardDetailsPaymentMethod, ), ) -> Result<Self, Self::Error> { let (card_number, card_token_data, co_badged_card_data, card_details) = value; // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked let name_on_card = if let Some(name) = card_details.card_holder_name.clone() { if name.clone().expose().is_empty() { card_token_data .and_then(|token_data| token_data.card_holder_name.clone()) .or(Some(name)) } else { Some(name) } } else { card_token_data.and_then(|token_data| token_data.card_holder_name.clone()) }; Ok(Self { card_number, card_exp_month: card_details .expiry_month .get_required_value("expiry_month")? .clone(), card_exp_year: card_details .expiry_year .get_required_value("expiry_year")? .clone(), card_holder_name: name_on_card, card_cvc: card_token_data .cloned() .unwrap_or_default() .card_cvc .unwrap_or_default(), card_issuer: card_details.card_issuer, card_network: card_details.card_network, card_type: card_details.card_type, card_issuing_country: card_details.issuer_country, bank_code: None, nick_name: card_details.nick_name, co_badged_card_data, }) } }
crates/hyperswitch_domain_models/src/payment_method_data.rs
hyperswitch_domain_models::src::payment_method_data
23,747
true
// File: crates/hyperswitch_domain_models/src/merchant_key_store.rs // Module: hyperswitch_domain_models::src::merchant_key_store use common_utils::{ crypto::Encryptable, custom_serde, date_time, errors::{CustomResult, ValidationError}, type_name, types::keymanager::{self, KeyManagerState}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use time::PrimitiveDateTime; use crate::type_encryption::{crypto_operation, CryptoOperation}; #[derive(Clone, Debug, serde::Serialize)] pub struct MerchantKeyStore { pub merchant_id: common_utils::id_type::MerchantId, pub key: Encryptable<Secret<Vec<u8>>>, #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, } #[async_trait::async_trait] impl super::behaviour::Conversion for MerchantKeyStore { type DstType = diesel_models::merchant_key_store::MerchantKeyStore; type NewDstType = diesel_models::merchant_key_store::MerchantKeyStoreNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::merchant_key_store::MerchantKeyStore { key: self.key.into(), merchant_id: self.merchant_id, created_at: self.created_at, }) } async fn convert_back( state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, _key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let identifier = keymanager::Identifier::Merchant(item.merchant_id.clone()); Ok(Self { key: crypto_operation( state, type_name!(Self::DstType), CryptoOperation::Decrypt(item.key), identifier, key.peek(), ) .await .and_then(|val| val.try_into_operation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), })?, merchant_id: item.merchant_id, created_at: item.created_at, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::merchant_key_store::MerchantKeyStoreNew { merchant_id: self.merchant_id, key: self.key.into(), created_at: date_time::now(), }) } } #[async_trait::async_trait] pub trait MerchantKeyStoreInterface { type Error; async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<MerchantKeyStore, Self::Error>; async fn get_merchant_key_store_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<MerchantKeyStore, Self::Error>; async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, Self::Error>; #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<MerchantKeyStore>, Self::Error>; async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, to: u32, ) -> CustomResult<Vec<MerchantKeyStore>, Self::Error>; }
crates/hyperswitch_domain_models/src/merchant_key_store.rs
hyperswitch_domain_models::src::merchant_key_store
838
true
// File: crates/hyperswitch_domain_models/src/routing.rs // Module: hyperswitch_domain_models::src::routing use std::collections::HashMap; use api_models::{enums as api_enums, routing}; use common_utils::id_type; use serde; #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingData { pub routed_through: Option<String>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub routing_info: PaymentRoutingInfo, pub algorithm: Option<routing::StraightThroughAlgorithm>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingData { // TODO: change this to RoutableConnectors enum pub routed_through: Option<String>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub pre_routing_connector_choice: Option<PreRoutingConnectorChoice>, pub algorithm_requested: Option<id_type::RoutingId>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)] #[serde(from = "PaymentRoutingInfoSerde", into = "PaymentRoutingInfoSerde")] pub struct PaymentRoutingInfo { pub algorithm: Option<routing::StraightThroughAlgorithm>, pub pre_routing_results: Option<HashMap<api_enums::PaymentMethodType, PreRoutingConnectorChoice>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)] #[serde(untagged)] pub enum PreRoutingConnectorChoice { Single(routing::RoutableConnectorChoice), Multiple(Vec<routing::RoutableConnectorChoice>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRoutingInfoInner { pub algorithm: Option<routing::StraightThroughAlgorithm>, pub pre_routing_results: Option<HashMap<api_enums::PaymentMethodType, PreRoutingConnectorChoice>>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum PaymentRoutingInfoSerde { OnlyAlgorithm(Box<routing::StraightThroughAlgorithm>), WithDetails(Box<PaymentRoutingInfoInner>), } impl From<PaymentRoutingInfoSerde> for PaymentRoutingInfo { fn from(value: PaymentRoutingInfoSerde) -> Self { match value { PaymentRoutingInfoSerde::OnlyAlgorithm(algo) => Self { algorithm: Some(*algo), pre_routing_results: None, }, PaymentRoutingInfoSerde::WithDetails(details) => Self { algorithm: details.algorithm, pre_routing_results: details.pre_routing_results, }, } } } impl From<PaymentRoutingInfo> for PaymentRoutingInfoSerde { fn from(value: PaymentRoutingInfo) -> Self { Self::WithDetails(Box::new(PaymentRoutingInfoInner { algorithm: value.algorithm, pre_routing_results: value.pre_routing_results, })) } }
crates/hyperswitch_domain_models/src/routing.rs
hyperswitch_domain_models::src::routing
623
true
// File: crates/hyperswitch_domain_models/src/mandates.rs // Module: hyperswitch_domain_models::src::mandates use std::collections::HashMap; use api_models::payments::{ MandateAmountData as ApiMandateAmountData, MandateData as ApiMandateData, MandateType, }; use common_enums::Currency; use common_types::payments as common_payments_types; use common_utils::{ date_time, errors::{CustomResult, ParsingError}, pii, types::MinorUnit, }; use error_stack::ResultExt; use time::PrimitiveDateTime; use crate::router_data::RecurringMandatePaymentData; #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct MandateDetails { pub update_mandate_id: Option<String>, } impl From<MandateDetails> for diesel_models::enums::MandateDetails { fn from(value: MandateDetails) -> Self { Self { update_mandate_id: value.update_mandate_id, } } } impl From<diesel_models::enums::MandateDetails> for MandateDetails { fn from(value: diesel_models::enums::MandateDetails) -> Self { Self { update_mandate_id: value.update_mandate_id, } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum MandateDataType { SingleUse(MandateAmountData), MultiUse(Option<MandateAmountData>), } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct MandateAmountData { pub amount: MinorUnit, pub currency: Currency, pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, pub metadata: Option<pii::SecretSerdeValue>, } // 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, Clone, serde::Serialize)] 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<common_payments_types::CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateDataType>, } impl From<MandateType> for MandateDataType { fn from(mandate_type: MandateType) -> Self { match mandate_type { MandateType::SingleUse(mandate_amount_data) => { Self::SingleUse(mandate_amount_data.into()) } MandateType::MultiUse(mandate_amount_data) => { Self::MultiUse(mandate_amount_data.map(|d| d.into())) } } } } impl From<MandateDataType> for diesel_models::enums::MandateDataType { fn from(value: MandateDataType) -> Self { match value { MandateDataType::SingleUse(data) => Self::SingleUse(data.into()), MandateDataType::MultiUse(None) => Self::MultiUse(None), MandateDataType::MultiUse(Some(data)) => Self::MultiUse(Some(data.into())), } } } impl From<diesel_models::enums::MandateDataType> for MandateDataType { fn from(value: diesel_models::enums::MandateDataType) -> Self { use diesel_models::enums::MandateDataType as DieselMandateDataType; match value { DieselMandateDataType::SingleUse(data) => Self::SingleUse(data.into()), DieselMandateDataType::MultiUse(None) => Self::MultiUse(None), DieselMandateDataType::MultiUse(Some(data)) => Self::MultiUse(Some(data.into())), } } } impl From<ApiMandateAmountData> for MandateAmountData { fn from(value: ApiMandateAmountData) -> Self { Self { amount: value.amount, currency: value.currency, start_date: value.start_date, end_date: value.end_date, metadata: value.metadata, } } } impl From<MandateAmountData> for diesel_models::enums::MandateAmountData { fn from(value: MandateAmountData) -> Self { Self { amount: value.amount, currency: value.currency, start_date: value.start_date, end_date: value.end_date, metadata: value.metadata, } } } impl From<diesel_models::enums::MandateAmountData> for MandateAmountData { fn from(value: diesel_models::enums::MandateAmountData) -> Self { Self { amount: value.amount, currency: value.currency, start_date: value.start_date, end_date: value.end_date, metadata: value.metadata, } } } impl From<ApiMandateData> for MandateData { fn from(value: ApiMandateData) -> Self { Self { customer_acceptance: value.customer_acceptance, mandate_type: value.mandate_type.map(|d| d.into()), update_mandate_id: value.update_mandate_id, } } } impl MandateAmountData { pub fn get_end_date( &self, format: date_time::DateFormat, ) -> error_stack::Result<Option<String>, ParsingError> { self.end_date .map(|date| { date_time::format_date(date, format) .change_context(ParsingError::DateTimeParsingError) }) .transpose() } pub fn get_metadata(&self) -> Option<pii::SecretSerdeValue> { self.metadata.clone() } } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsMandateReferenceRecord { pub connector_mandate_id: String, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<Currency>, pub mandate_metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>, pub connector_mandate_request_reference_id: Option<String>, } #[cfg(feature = "v1")] impl From<&PaymentsMandateReferenceRecord> for RecurringMandatePaymentData { fn from(mandate_reference_record: &PaymentsMandateReferenceRecord) -> Self { Self { payment_method_type: mandate_reference_record.payment_method_type, original_payment_authorized_amount: mandate_reference_record .original_payment_authorized_amount, original_payment_authorized_currency: mandate_reference_record .original_payment_authorized_currency, mandate_metadata: mandate_reference_record.mandate_metadata.clone(), } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ConnectorTokenReferenceRecord { pub connector_token: String, pub payment_method_subtype: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<MinorUnit>, pub original_payment_authorized_currency: Option<Currency>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_token_status: common_enums::ConnectorTokenStatus, pub connector_token_request_reference_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PayoutsMandateReferenceRecord { pub transfer_method_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PayoutsMandateReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>, ); impl std::ops::Deref for PayoutsMandateReference { type Target = HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for PayoutsMandateReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsTokenReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>, ); #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsMandateReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>, ); #[cfg(feature = "v1")] impl std::ops::Deref for PaymentsMandateReference { type Target = HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>; fn deref(&self) -> &Self::Target { &self.0 } } #[cfg(feature = "v1")] impl std::ops::DerefMut for PaymentsMandateReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(feature = "v2")] impl std::ops::Deref for PaymentsTokenReference { type Target = HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>; fn deref(&self) -> &Self::Target { &self.0 } } #[cfg(feature = "v2")] impl std::ops::DerefMut for PaymentsTokenReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CommonMandateReference { pub payments: Option<PaymentsMandateReference>, pub payouts: Option<PayoutsMandateReference>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CommonMandateReference { pub payments: Option<PaymentsTokenReference>, pub payouts: Option<PayoutsMandateReference>, } impl CommonMandateReference { pub fn get_mandate_details_value(&self) -> CustomResult<serde_json::Value, ParsingError> { let mut payments = self .payments .as_ref() .map_or_else(|| Ok(serde_json::json!({})), serde_json::to_value) .change_context(ParsingError::StructParseFailure("payment mandate details"))?; self.payouts .as_ref() .map(|payouts_mandate| { serde_json::to_value(payouts_mandate).map(|payouts_mandate_value| { payments.as_object_mut().map(|payments_object| { payments_object.insert("payouts".to_string(), payouts_mandate_value); }) }) }) .transpose() .change_context(ParsingError::StructParseFailure("payout mandate details"))?; Ok(payments) } #[cfg(feature = "v2")] /// Insert a new payment token reference for the given connector_id pub fn insert_payment_token_reference_record( &mut self, connector_id: &common_utils::id_type::MerchantConnectorAccountId, record: ConnectorTokenReferenceRecord, ) { match self.payments { Some(ref mut payments_reference) => { payments_reference.insert(connector_id.clone(), record); } None => { let mut payments_reference = HashMap::new(); payments_reference.insert(connector_id.clone(), record); self.payments = Some(PaymentsTokenReference(payments_reference)); } } } } impl From<diesel_models::CommonMandateReference> for CommonMandateReference { fn from(value: diesel_models::CommonMandateReference) -> Self { Self { payments: value.payments.map(|payments| payments.into()), payouts: value.payouts.map(|payouts| payouts.into()), } } } impl From<CommonMandateReference> for diesel_models::CommonMandateReference { fn from(value: CommonMandateReference) -> Self { Self { payments: value.payments.map(|payments| payments.into()), payouts: value.payouts.map(|payouts| payouts.into()), } } } impl From<diesel_models::PayoutsMandateReference> for PayoutsMandateReference { fn from(value: diesel_models::PayoutsMandateReference) -> Self { Self( value .0 .into_iter() .map(|(key, record)| (key, record.into())) .collect(), ) } } impl From<PayoutsMandateReference> for diesel_models::PayoutsMandateReference { fn from(value: PayoutsMandateReference) -> Self { Self( value .0 .into_iter() .map(|(key, record)| (key, record.into())) .collect(), ) } } #[cfg(feature = "v1")] impl From<diesel_models::PaymentsMandateReference> for PaymentsMandateReference { fn from(value: diesel_models::PaymentsMandateReference) -> Self { Self( value .0 .into_iter() .map(|(key, record)| (key, record.into())) .collect(), ) } } #[cfg(feature = "v1")] impl From<PaymentsMandateReference> for diesel_models::PaymentsMandateReference { fn from(value: PaymentsMandateReference) -> Self { Self( value .0 .into_iter() .map(|(key, record)| (key, record.into())) .collect(), ) } } #[cfg(feature = "v2")] impl From<diesel_models::PaymentsTokenReference> for PaymentsTokenReference { fn from(value: diesel_models::PaymentsTokenReference) -> Self { Self( value .0 .into_iter() .map(|(key, record)| (key, record.into())) .collect(), ) } } #[cfg(feature = "v2")] impl From<PaymentsTokenReference> for diesel_models::PaymentsTokenReference { fn from(value: PaymentsTokenReference) -> Self { Self( value .0 .into_iter() .map(|(key, record)| (key, record.into())) .collect(), ) } } impl From<diesel_models::PayoutsMandateReferenceRecord> for PayoutsMandateReferenceRecord { fn from(value: diesel_models::PayoutsMandateReferenceRecord) -> Self { Self { transfer_method_id: value.transfer_method_id, } } } impl From<PayoutsMandateReferenceRecord> for diesel_models::PayoutsMandateReferenceRecord { fn from(value: PayoutsMandateReferenceRecord) -> Self { Self { transfer_method_id: value.transfer_method_id, } } } #[cfg(feature = "v2")] impl From<diesel_models::ConnectorTokenReferenceRecord> for ConnectorTokenReferenceRecord { fn from(value: diesel_models::ConnectorTokenReferenceRecord) -> Self { let diesel_models::ConnectorTokenReferenceRecord { connector_token, payment_method_subtype, original_payment_authorized_amount, original_payment_authorized_currency, metadata, connector_token_status, connector_token_request_reference_id, } = value; Self { connector_token, payment_method_subtype, original_payment_authorized_amount, original_payment_authorized_currency, metadata, connector_token_status, connector_token_request_reference_id, } } } #[cfg(feature = "v1")] impl From<diesel_models::PaymentsMandateReferenceRecord> for PaymentsMandateReferenceRecord { fn from(value: diesel_models::PaymentsMandateReferenceRecord) -> Self { Self { connector_mandate_id: value.connector_mandate_id, payment_method_type: value.payment_method_type, original_payment_authorized_amount: value.original_payment_authorized_amount, original_payment_authorized_currency: value.original_payment_authorized_currency, mandate_metadata: value.mandate_metadata, connector_mandate_status: value.connector_mandate_status, connector_mandate_request_reference_id: value.connector_mandate_request_reference_id, } } } #[cfg(feature = "v2")] impl From<ConnectorTokenReferenceRecord> for diesel_models::ConnectorTokenReferenceRecord { fn from(value: ConnectorTokenReferenceRecord) -> Self { let ConnectorTokenReferenceRecord { connector_token, payment_method_subtype, original_payment_authorized_amount, original_payment_authorized_currency, metadata, connector_token_status, connector_token_request_reference_id, } = value; Self { connector_token, payment_method_subtype, original_payment_authorized_amount, original_payment_authorized_currency, metadata, connector_token_status, connector_token_request_reference_id, } } } #[cfg(feature = "v1")] impl From<PaymentsMandateReferenceRecord> for diesel_models::PaymentsMandateReferenceRecord { fn from(value: PaymentsMandateReferenceRecord) -> Self { Self { connector_mandate_id: value.connector_mandate_id, payment_method_type: value.payment_method_type, original_payment_authorized_amount: value.original_payment_authorized_amount, original_payment_authorized_currency: value.original_payment_authorized_currency, mandate_metadata: value.mandate_metadata, connector_mandate_status: value.connector_mandate_status, connector_mandate_request_reference_id: value.connector_mandate_request_reference_id, } } }
crates/hyperswitch_domain_models/src/mandates.rs
hyperswitch_domain_models::src::mandates
3,912
true
// File: crates/hyperswitch_domain_models/src/behaviour.rs // Module: hyperswitch_domain_models::src::behaviour use common_utils::{ errors::{CustomResult, ValidationError}, types::keymanager::{Identifier, KeyManagerState}, }; use masking::Secret; /// Trait for converting domain types to storage models #[async_trait::async_trait] pub trait Conversion { type DstType; type NewDstType; async fn convert(self) -> CustomResult<Self::DstType, ValidationError>; async fn convert_back( state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized; async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError>; } #[async_trait::async_trait] pub trait ReverseConversion<SrcType: Conversion> { async fn convert( self, state: &KeyManagerState, key: &Secret<Vec<u8>>, key_manager_identifier: Identifier, ) -> CustomResult<SrcType, ValidationError>; } #[async_trait::async_trait] impl<T: Send, U: Conversion<DstType = T>> ReverseConversion<U> for T { async fn convert( self, state: &KeyManagerState, key: &Secret<Vec<u8>>, key_manager_identifier: Identifier, ) -> CustomResult<U, ValidationError> { U::convert_back(state, self, key, key_manager_identifier).await } }
crates/hyperswitch_domain_models/src/behaviour.rs
hyperswitch_domain_models::src::behaviour
334
true
// File: crates/hyperswitch_domain_models/src/api.rs // Module: hyperswitch_domain_models::src::api use std::{collections::HashSet, fmt::Display}; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, impl_api_event_type, }; use super::payment_method_data::PaymentMethodData; #[derive(Debug, PartialEq)] pub enum ApplicationResponse<R> { Json(R), StatusOk, TextPlain(String), JsonForRedirection(api_models::payments::RedirectionResponse), Form(Box<RedirectionFormData>), PaymentLinkForm(Box<PaymentLinkAction>), FileData((Vec<u8>, mime::Mime)), JsonWithHeaders((R, Vec<(String, masking::Maskable<String>)>)), GenericLinkForm(Box<GenericLinks>), } impl<R> ApplicationResponse<R> { /// Get the json response from response #[inline] pub fn get_json_body( self, ) -> common_utils::errors::CustomResult<R, common_utils::errors::ValidationError> { match self { Self::Json(body) | Self::JsonWithHeaders((body, _)) => Ok(body), Self::TextPlain(_) | Self::JsonForRedirection(_) | Self::Form(_) | Self::PaymentLinkForm(_) | Self::FileData(_) | Self::GenericLinkForm(_) | Self::StatusOk => Err(common_utils::errors::ValidationError::InvalidValue { message: "expected either Json or JsonWithHeaders Response".to_string(), } .into()), } } } impl<T: ApiEventMetric> ApiEventMetric for ApplicationResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { match self { Self::Json(r) => r.get_api_event_type(), Self::JsonWithHeaders((r, _)) => r.get_api_event_type(), _ => None, } } } impl_api_event_type!(Miscellaneous, (PaymentLinkFormData, GenericLinkFormData)); #[derive(Debug, PartialEq)] pub struct RedirectionFormData { pub redirect_form: crate::router_response_types::RedirectForm, pub payment_method_data: Option<PaymentMethodData>, pub amount: String, pub currency: String, } #[derive(Debug, Eq, PartialEq)] pub enum PaymentLinkAction { PaymentLinkFormData(PaymentLinkFormData), PaymentLinkStatus(PaymentLinkStatusData), } #[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentLinkFormData { pub js_script: String, pub css_script: String, pub sdk_url: url::Url, pub html_meta_tags: String, } #[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentLinkStatusData { pub js_script: String, pub css_script: String, } #[derive(Debug, Eq, PartialEq)] pub struct GenericLinks { pub allowed_domains: HashSet<String>, pub data: GenericLinksData, pub locale: String, } #[derive(Debug, Eq, PartialEq)] pub enum GenericLinksData { ExpiredLink(GenericExpiredLinkData), PaymentMethodCollect(GenericLinkFormData), PayoutLink(GenericLinkFormData), PayoutLinkStatus(GenericLinkStatusData), PaymentMethodCollectStatus(GenericLinkStatusData), SecurePaymentLink(PaymentLinkFormData), } impl Display for GenericLinksData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match *self { Self::ExpiredLink(_) => "ExpiredLink", Self::PaymentMethodCollect(_) => "PaymentMethodCollect", Self::PayoutLink(_) => "PayoutLink", Self::PayoutLinkStatus(_) => "PayoutLinkStatus", Self::PaymentMethodCollectStatus(_) => "PaymentMethodCollectStatus", Self::SecurePaymentLink(_) => "SecurePaymentLink", } ) } } #[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] pub struct GenericExpiredLinkData { pub title: String, pub message: String, pub theme: String, } #[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] pub struct GenericLinkFormData { pub js_data: String, pub css_data: String, pub sdk_url: url::Url, pub html_meta_tags: String, } #[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] pub struct GenericLinkStatusData { pub js_data: String, pub css_data: String, }
crates/hyperswitch_domain_models/src/api.rs
hyperswitch_domain_models::src::api
1,003
true
// File: crates/hyperswitch_domain_models/src/relay.rs // Module: hyperswitch_domain_models::src::relay use common_enums::enums; use common_utils::{ self, errors::{CustomResult, ValidationError}, id_type::{self, GenerateId}, pii, types::{keymanager, MinorUnit}, }; use diesel_models::relay::RelayUpdateInternal; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use serde::{self, Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{router_data::ErrorResponse, router_response_types}; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Relay { pub id: id_type::RelayId, pub connector_resource_id: String, pub connector_id: id_type::MerchantConnectorAccountId, pub profile_id: id_type::ProfileId, pub merchant_id: id_type::MerchantId, pub relay_type: enums::RelayType, pub request_data: Option<RelayData>, pub status: enums::RelayStatus, pub connector_reference_id: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub response_data: Option<pii::SecretSerdeValue>, } impl Relay { pub fn new( relay_request: &api_models::relay::RelayRequest, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, ) -> Self { let relay_id = id_type::RelayId::generate(); Self { id: relay_id.clone(), connector_resource_id: relay_request.connector_resource_id.clone(), connector_id: relay_request.connector_id.clone(), profile_id: profile_id.clone(), merchant_id: merchant_id.clone(), relay_type: common_enums::RelayType::Refund, request_data: relay_request.data.clone().map(From::from), status: common_enums::RelayStatus::Created, connector_reference_id: None, error_code: None, error_message: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), response_data: None, } } } impl From<api_models::relay::RelayData> for RelayData { fn from(relay: api_models::relay::RelayData) -> Self { match relay { api_models::relay::RelayData::Refund(relay_refund_request) => { Self::Refund(RelayRefundData { amount: relay_refund_request.amount, currency: relay_refund_request.currency, reason: relay_refund_request.reason, }) } } } } impl From<api_models::relay::RelayRefundRequestData> for RelayRefundData { fn from(relay: api_models::relay::RelayRefundRequestData) -> Self { Self { amount: relay.amount, currency: relay.currency, reason: relay.reason, } } } impl RelayUpdate { pub fn from( response: Result<router_response_types::RefundsResponseData, ErrorResponse>, ) -> Self { match response { Err(error) => Self::ErrorUpdate { error_code: error.code, error_message: error.reason.unwrap_or(error.message), status: common_enums::RelayStatus::Failure, }, Ok(response) => Self::StatusUpdate { connector_reference_id: Some(response.connector_refund_id), status: common_enums::RelayStatus::from(response.refund_status), }, } } } impl From<RelayData> for api_models::relay::RelayData { fn from(relay: RelayData) -> Self { match relay { RelayData::Refund(relay_refund_request) => { Self::Refund(api_models::relay::RelayRefundRequestData { amount: relay_refund_request.amount, currency: relay_refund_request.currency, reason: relay_refund_request.reason, }) } } } } impl From<Relay> for api_models::relay::RelayResponse { fn from(value: Relay) -> Self { let error = value .error_code .zip(value.error_message) .map( |(error_code, error_message)| api_models::relay::RelayError { code: error_code, message: error_message, }, ); let data = value.request_data.map(|relay_data| match relay_data { RelayData::Refund(relay_refund_request) => { api_models::relay::RelayData::Refund(api_models::relay::RelayRefundRequestData { amount: relay_refund_request.amount, currency: relay_refund_request.currency, reason: relay_refund_request.reason, }) } }); Self { id: value.id, status: value.status, error, connector_resource_id: value.connector_resource_id, connector_id: value.connector_id, profile_id: value.profile_id, relay_type: value.relay_type, data, connector_reference_id: value.connector_reference_id, } } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "snake_case", untagged)] pub enum RelayData { Refund(RelayRefundData), } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct RelayRefundData { pub amount: MinorUnit, pub currency: enums::Currency, pub reason: Option<String>, } #[derive(Debug)] pub enum RelayUpdate { ErrorUpdate { error_code: String, error_message: String, status: enums::RelayStatus, }, StatusUpdate { connector_reference_id: Option<String>, status: common_enums::RelayStatus, }, } impl From<RelayUpdate> for RelayUpdateInternal { fn from(value: RelayUpdate) -> Self { match value { RelayUpdate::ErrorUpdate { error_code, error_message, status, } => Self { error_code: Some(error_code), error_message: Some(error_message), connector_reference_id: None, status: Some(status), modified_at: common_utils::date_time::now(), }, RelayUpdate::StatusUpdate { connector_reference_id, status, } => Self { connector_reference_id, status: Some(status), error_code: None, error_message: None, modified_at: common_utils::date_time::now(), }, } } } #[async_trait::async_trait] impl super::behaviour::Conversion for Relay { type DstType = diesel_models::relay::Relay; type NewDstType = diesel_models::relay::RelayNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::relay::Relay { id: self.id, connector_resource_id: self.connector_resource_id, connector_id: self.connector_id, profile_id: self.profile_id, merchant_id: self.merchant_id, relay_type: self.relay_type, request_data: self .request_data .map(|data| { serde_json::to_value(data).change_context(ValidationError::InvalidValue { message: "Failed while decrypting business profile data".to_string(), }) }) .transpose()? .map(Secret::new), status: self.status, connector_reference_id: self.connector_reference_id, error_code: self.error_code, error_message: self.error_message, created_at: self.created_at, modified_at: self.modified_at, response_data: self.response_data, }) } async fn convert_back( _state: &keymanager::KeyManagerState, item: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> { Ok(Self { id: item.id, connector_resource_id: item.connector_resource_id, connector_id: item.connector_id, profile_id: item.profile_id, merchant_id: item.merchant_id, relay_type: enums::RelayType::Refund, request_data: item .request_data .map(|data| { serde_json::from_value(data.expose()).change_context( ValidationError::InvalidValue { message: "Failed while decrypting business profile data".to_string(), }, ) }) .transpose()?, status: item.status, connector_reference_id: item.connector_reference_id, error_code: item.error_code, error_message: item.error_message, created_at: item.created_at, modified_at: item.modified_at, response_data: item.response_data, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::relay::RelayNew { id: self.id, connector_resource_id: self.connector_resource_id, connector_id: self.connector_id, profile_id: self.profile_id, merchant_id: self.merchant_id, relay_type: self.relay_type, request_data: self .request_data .map(|data| { serde_json::to_value(data).change_context(ValidationError::InvalidValue { message: "Failed while decrypting business profile data".to_string(), }) }) .transpose()? .map(Secret::new), status: self.status, connector_reference_id: self.connector_reference_id, error_code: self.error_code, error_message: self.error_message, created_at: self.created_at, modified_at: self.modified_at, response_data: self.response_data, }) } }
crates/hyperswitch_domain_models/src/relay.rs
hyperswitch_domain_models::src::relay
2,152
true
// File: crates/hyperswitch_domain_models/src/vault.rs // Module: hyperswitch_domain_models::src::vault use api_models::payment_methods; #[cfg(feature = "v2")] use error_stack; use serde::{Deserialize, Serialize}; #[cfg(feature = "v2")] use crate::errors; use crate::payment_method_data; #[derive(Debug, Deserialize, Serialize, Clone)] pub enum PaymentMethodVaultingData { Card(payment_methods::CardDetail), #[cfg(feature = "v2")] NetworkToken(payment_method_data::NetworkTokenDetails), CardNumber(cards::CardNumber), } impl PaymentMethodVaultingData { pub fn get_card(&self) -> Option<&payment_methods::CardDetail> { match self { Self::Card(card) => Some(card), #[cfg(feature = "v2")] Self::NetworkToken(_) => None, Self::CardNumber(_) => None, } } pub fn get_payment_methods_data(&self) -> payment_method_data::PaymentMethodsData { match self { Self::Card(card) => payment_method_data::PaymentMethodsData::Card( payment_method_data::CardDetailsPaymentMethod::from(card.clone()), ), #[cfg(feature = "v2")] Self::NetworkToken(network_token) => { payment_method_data::PaymentMethodsData::NetworkToken( payment_method_data::NetworkTokenDetailsPaymentMethod::from( network_token.clone(), ), ) } Self::CardNumber(_card_number) => payment_method_data::PaymentMethodsData::Card( payment_method_data::CardDetailsPaymentMethod { last4_digits: None, issuer_country: None, expiry_month: None, expiry_year: None, nick_name: None, card_holder_name: None, card_isin: None, card_issuer: None, card_network: None, card_type: None, saved_to_locker: false, #[cfg(feature = "v1")] co_badged_card_data: None, }, ), } } } pub trait VaultingDataInterface { fn get_vaulting_data_key(&self) -> String; } impl VaultingDataInterface for PaymentMethodVaultingData { fn get_vaulting_data_key(&self) -> String { match &self { Self::Card(card) => card.card_number.to_string(), #[cfg(feature = "v2")] Self::NetworkToken(network_token) => network_token.network_token.to_string(), Self::CardNumber(card_number) => card_number.to_string(), } } } #[cfg(feature = "v2")] impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodVaultingData { type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>; fn try_from(item: payment_methods::PaymentMethodCreateData) -> Result<Self, Self::Error> { match item { payment_methods::PaymentMethodCreateData::Card(card) => Ok(Self::Card(card)), payment_methods::PaymentMethodCreateData::ProxyCard(card) => Err( errors::api_error_response::ApiErrorResponse::UnprocessableEntity { message: "Proxy Card for PaymentMethodCreateData".to_string(), } .into(), ), } } }
crates/hyperswitch_domain_models/src/vault.rs
hyperswitch_domain_models::src::vault
697
true
// File: crates/hyperswitch_domain_models/src/master_key.rs // Module: hyperswitch_domain_models::src::master_key pub trait MasterKeyInterface { fn get_master_key(&self) -> &[u8]; }
crates/hyperswitch_domain_models/src/master_key.rs
hyperswitch_domain_models::src::master_key
48
true
// File: crates/hyperswitch_domain_models/src/chat.rs // Module: hyperswitch_domain_models::src::chat use common_utils::id_type; use masking::Secret; #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct GetDataMessage { pub message: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct HyperswitchAiDataRequest { pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, pub org_id: id_type::OrganizationId, pub query: GetDataMessage, pub entity_type: common_enums::EntityType, }
crates/hyperswitch_domain_models/src/chat.rs
hyperswitch_domain_models::src::chat
140
true
// File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs // Module: hyperswitch_domain_models::src::payments::payment_attempt #[cfg(all(feature = "v1", feature = "olap"))] use api_models::enums::Connector; use common_enums as storage_enums; #[cfg(feature = "v2")] use common_types::payments as common_payments_types; #[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, OvercaptureEnabledBool, RequestExtendedAuthorizationBool, }; #[cfg(feature = "v2")] use common_utils::{ crypto::Encryptable, encryption::Encryption, ext_traits::Encode, types::keymanager::ToEncryptable, }; use common_utils::{ errors::{CustomResult, ValidationError}, ext_traits::{OptionExt, ValueExt}, id_type, pii, types::{ keymanager::{self, KeyManagerState}, ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy, MinorUnit, }, }; #[cfg(feature = "v1")] use diesel_models::{ ConnectorMandateReferenceId, NetworkDetails, PaymentAttemptUpdate as DieselPaymentAttemptUpdate, }; use diesel_models::{ PaymentAttempt as DieselPaymentAttempt, PaymentAttemptNew as DieselPaymentAttemptNew, }; #[cfg(feature = "v2")] use diesel_models::{ PaymentAttemptFeatureMetadata as DieselPaymentAttemptFeatureMetadata, PaymentAttemptRecoveryData as DieselPassiveChurnRecoveryData, }; use error_stack::ResultExt; #[cfg(feature = "v2")] use masking::PeekInterface; use masking::Secret; #[cfg(feature = "v1")] use router_env::logger; #[cfg(feature = "v2")] use rustc_hash::FxHashMap; #[cfg(feature = "v1")] use serde::Deserialize; use serde::Serialize; #[cfg(feature = "v2")] use serde_json::Value; use time::PrimitiveDateTime; #[cfg(all(feature = "v1", feature = "olap"))] use super::PaymentIntent; #[cfg(feature = "v2")] use crate::{ address::Address, consts, merchant_key_store::MerchantKeyStore, router_response_types, type_encryption::{crypto_operation, CryptoOperation}, }; use crate::{behaviour, errors, ForeignIDRef}; #[cfg(feature = "v1")] use crate::{ mandates::{MandateDataType, MandateDetails}, router_request_types, }; #[async_trait::async_trait] pub trait PaymentAttemptInterface { type Error; #[cfg(feature = "v1")] async fn insert_payment_attempt( &self, payment_attempt: PaymentAttemptNew, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v2")] async fn insert_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, payment_attempt: PaymentAttempt, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn update_payment_attempt_with_attempt_id( &self, this: PaymentAttempt, payment_attempt: PaymentAttemptUpdate, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v2")] async fn update_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, this: PaymentAttempt, payment_attempt: PaymentAttemptUpdate, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &ConnectorTransactionId, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, payment_id: &id_type::GlobalPaymentId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, merchant_id: &id_type::MerchantId, connector_txn_id: &str, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_attempt_by_profile_id_connector_transaction_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, profile_id: &id_type::ProfileId, connector_transaction_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, attempt_id: &str, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_attempt_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, attempt_id: &id_type::GlobalAttemptId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_attempts_by_payment_intent_id( &self, state: &KeyManagerState, payment_id: &id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentAttempt>, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, preprocessing_id: &str, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; #[cfg(feature = "v1")] async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentAttempt>, Self::Error>; #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filters_for_payments( &self, pi: &[PaymentIntent], merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentListFilters, Self::Error>; #[cfg(all(feature = "v1", feature = "olap"))] #[allow(clippy::too_many_arguments)] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<Connector>>, payment_method: Option<Vec<storage_enums::PaymentMethod>>, payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>, authentication_type: Option<Vec<storage_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<storage_enums::CardNetwork>>, card_discovery: Option<Vec<storage_enums::CardDiscovery>>, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<i64, Self::Error>; #[cfg(all(feature = "v2", feature = "olap"))] #[allow(clippy::too_many_arguments)] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method_type: Option<Vec<storage_enums::PaymentMethod>>, payment_method_subtype: Option<Vec<storage_enums::PaymentMethodType>>, authentication_type: Option<Vec<storage_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<storage_enums::CardNetwork>>, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<i64, Self::Error>; } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AttemptAmountDetails { /// The total amount for this payment attempt. This includes all the surcharge and tax amounts. net_amount: MinorUnit, /// The amount that has to be captured, amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant order_tax_amount: Option<MinorUnit>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AttemptAmountDetailsSetter { /// The total amount for this payment attempt. This includes all the surcharge and tax amounts. pub net_amount: MinorUnit, /// The amount that has to be captured, 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. 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>, } /// Set the fields of amount details, since the fields are not public impl From<AttemptAmountDetailsSetter> for AttemptAmountDetails { fn from(setter: AttemptAmountDetailsSetter) -> Self { Self { net_amount: setter.net_amount, amount_to_capture: setter.amount_to_capture, surcharge_amount: setter.surcharge_amount, tax_on_surcharge: setter.tax_on_surcharge, amount_capturable: setter.amount_capturable, shipping_cost: setter.shipping_cost, order_tax_amount: setter.order_tax_amount, } } } impl AttemptAmountDetails { pub fn get_net_amount(&self) -> MinorUnit { self.net_amount } pub fn get_amount_to_capture(&self) -> Option<MinorUnit> { self.amount_to_capture } pub fn get_surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn get_tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } pub fn get_amount_capturable(&self) -> MinorUnit { self.amount_capturable } pub fn get_shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn get_order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn set_amount_to_capture(&mut self, amount_to_capture: MinorUnit) { self.amount_to_capture = Some(amount_to_capture); } /// Validate the amount to capture that is sent in the request pub fn validate_amount_to_capture( &self, request_amount_to_capture: MinorUnit, ) -> Result<(), ValidationError> { common_utils::fp_utils::when(request_amount_to_capture > self.get_net_amount(), || { Err(ValidationError::IncorrectValueProvided { field_name: "amount_to_capture", }) }) } } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct ErrorDetails { /// The error code that was returned by the connector. /// This is a mandatory field. This is used to lookup the global status map record for unified code and retries pub code: String, /// The error message that was returned by the connector. /// This is a mandatory field. This is used to lookup the global status map record for unified message and retries pub message: String, /// The detailed error reason that was returned by the connector. pub reason: Option<String>, /// The unified code that is generated by the application based on the global status map record. /// This can be relied upon for common error code across all connectors pub unified_code: Option<String>, /// The unified message that is generated by the application based on the global status map record. /// This can be relied upon for common error code across all connectors /// If there is translation available, message will be translated to the requested language 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>, } #[cfg(feature = "v2")] impl From<ErrorDetails> for api_models::payments::RecordAttemptErrorDetails { fn from(error_details: ErrorDetails) -> Self { Self { code: error_details.code, message: error_details.message, network_decline_code: error_details.network_decline_code, network_advice_code: error_details.network_advice_code, network_error_message: error_details.network_error_message, } } } /// Domain model for the payment attempt. /// Few fields which are related are grouped together for better readability and understandability. /// These fields will be flattened and stored in the database in individual columns #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, router_derive::ToEncryption)] pub struct PaymentAttempt { /// Payment id for the payment attempt pub payment_id: id_type::GlobalPaymentId, /// Merchant id for the payment attempt pub merchant_id: id_type::MerchantId, /// Group id for the payment attempt pub attempts_group_id: Option<String>, /// Amount details for the payment attempt pub amount_details: AttemptAmountDetails, /// Status of the payment attempt. This is the status that is updated by the connector. /// The intent status is updated by the AttemptStatus. pub status: storage_enums::AttemptStatus, /// Name of the connector that was used for the payment attempt. The connector is either decided by /// either running the routing algorithm or by straight through processing request. /// This will be updated before calling the connector // TODO: use connector enum, this should be done in v1 as well as a part of moving to domain types wherever possible pub connector: Option<String>, /// Error details in case the payment attempt failed pub error: Option<ErrorDetails>, /// The authentication type that was requested for the payment attempt. /// This authentication type maybe decided by step up 3ds or by running the decision engine. pub authentication_type: storage_enums::AuthenticationType, /// The time at which the payment attempt was created pub created_at: PrimitiveDateTime, /// The time at which the payment attempt was last modified pub modified_at: PrimitiveDateTime, pub last_synced: Option<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>, /// Browser information required for 3DS authentication pub browser_info: Option<common_utils::types::BrowserInformation>, /// Payment token is the token used for temporary use in case the payment method is stored in vault pub payment_token: Option<String>, /// Metadata that is returned by the connector. pub connector_metadata: Option<pii::SecretSerdeValue>, pub payment_experience: Option<storage_enums::PaymentExperience>, /// The insensitive data of the payment method data is stored here pub payment_method_data: Option<pii::SecretSerdeValue>, /// The result of the routing algorithm. /// This will store the list of connectors and other related information that was used to route the payment. // TODO: change this to type instead of serde_json::Value pub routing_result: Option<Value>, pub preprocessing_step_id: Option<String>, /// Number of captures that have happened for the payment attempt pub multiple_capture_count: Option<i16>, /// A reference to the payment at connector side. This is returned by the connector pub connector_response_reference_id: Option<String>, /// Whether the payment was updated by postgres or redis pub updated_by: String, /// The authentication data which is used for external authentication pub redirection_data: Option<router_response_types::RedirectForm>, pub encoded_data: Option<Secret<String>>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Whether external 3DS authentication was attempted for this payment. /// This is based on the configuration of the merchant in the business profile pub external_three_ds_authentication_attempted: Option<bool>, /// The connector that was used for external authentication pub authentication_connector: Option<String>, /// The foreign key reference to the authentication details pub authentication_id: Option<id_type::AuthenticationId>, pub fingerprint_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<Secret<common_payments_types::CustomerAcceptance>>, /// The profile id for the payment attempt. This will be derived from payment intent. pub profile_id: id_type::ProfileId, /// The organization id for the payment attempt. This will be derived from payment intent. pub organization_id: id_type::OrganizationId, /// Payment method type for the payment attempt pub payment_method_type: storage_enums::PaymentMethod, /// Foreig key reference of Payment method id in case the payment instrument was stored pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// The reference to the payment at the connector side pub connector_payment_id: Option<String>, /// The payment method subtype for the payment attempt. pub payment_method_subtype: storage_enums::PaymentMethodType, /// The authentication type that was applied for the payment attempt. pub authentication_applied: Option<common_enums::AuthenticationType>, /// A reference to the payment at connector side. This is returned by the connector pub external_reference_id: Option<String>, /// The billing address for the payment method #[encrypt(ty = Value)] pub payment_method_billing_address: Option<Encryptable<Address>>, /// The global identifier for the payment attempt pub id: id_type::GlobalAttemptId, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<diesel_models::ConnectorTokenDetails>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<common_enums::CardDiscovery>, /// Split payment data pub charges: Option<common_types::payments::ConnectorChargeResponseData>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// merchant who owns the credentials of the processor, i.e. processor owner pub processor_merchant_id: id_type::MerchantId, /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) pub created_by: Option<CreatedBy>, pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, /// stores the authorized amount in case of partial authorization pub authorized_amount: Option<MinorUnit>, } impl PaymentAttempt { #[cfg(feature = "v1")] pub fn get_payment_method(&self) -> Option<storage_enums::PaymentMethod> { self.payment_method } #[cfg(feature = "v2")] pub fn get_payment_method(&self) -> Option<storage_enums::PaymentMethod> { // TODO: check if we can fix this Some(self.payment_method_type) } #[cfg(feature = "v1")] pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethodType> { self.payment_method_type } #[cfg(feature = "v2")] pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethodType> { // TODO: check if we can fix this Some(self.payment_method_subtype) } #[cfg(feature = "v1")] pub fn get_id(&self) -> &str { &self.attempt_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &id_type::GlobalAttemptId { &self.id } #[cfg(feature = "v1")] pub fn get_connector_payment_id(&self) -> Option<&str> { self.connector_transaction_id.as_deref() } #[cfg(feature = "v2")] pub fn get_connector_payment_id(&self) -> Option<&str> { self.connector_payment_id.as_deref() } /// Construct the domain model from the ConfirmIntentRequest and PaymentIntent #[cfg(feature = "v2")] pub async fn create_domain_model( payment_intent: &super::PaymentIntent, cell_id: id_type::CellId, storage_scheme: storage_enums::MerchantStorageScheme, request: &api_models::payments::PaymentsConfirmIntentRequest, encrypted_data: DecryptedPaymentAttempt, ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> { let id = id_type::GlobalAttemptId::generate(&cell_id); let intent_amount_details = payment_intent.amount_details.clone(); let attempt_amount_details = intent_amount_details.create_attempt_amount_details(request); let now = common_utils::date_time::now(); let payment_method_billing_address = encrypted_data .payment_method_billing_address .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?; let connector_token = Some(diesel_models::ConnectorTokenDetails { connector_mandate_id: None, connector_token_request_reference_id: Some(common_utils::generate_id_with_len( consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH, )), }); let authentication_type = payment_intent.authentication_type.unwrap_or_default(); Ok(Self { payment_id: payment_intent.id.clone(), merchant_id: payment_intent.merchant_id.clone(), attempts_group_id: None, amount_details: attempt_amount_details, status: common_enums::AttemptStatus::Started, // This will be decided by the routing algorithm and updated in update trackers // right before calling the connector connector: None, authentication_type, created_at: now, modified_at: now, last_synced: None, cancellation_reason: None, browser_info: request.browser_info.clone(), payment_token: request.payment_token.clone(), connector_metadata: None, payment_experience: None, payment_method_data: None, routing_result: None, preprocessing_step_id: None, multiple_capture_count: None, connector_response_reference_id: None, updated_by: storage_scheme.to_string(), redirection_data: None, encoded_data: None, merchant_connector_id: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, charges: None, client_source: None, client_version: None, customer_acceptance: request.customer_acceptance.clone().map(Secret::new), profile_id: payment_intent.profile_id.clone(), organization_id: payment_intent.organization_id.clone(), payment_method_type: request.payment_method_type, payment_method_id: request.payment_method_id.clone(), connector_payment_id: None, payment_method_subtype: request.payment_method_subtype, authentication_applied: None, external_reference_id: None, payment_method_billing_address, error: None, connector_token_details: connector_token, id, card_discovery: None, feature_metadata: None, processor_merchant_id: payment_intent.merchant_id.clone(), created_by: None, connector_request_reference_id: None, network_transaction_id: None, authorized_amount: None, }) } #[cfg(feature = "v2")] pub async fn proxy_create_domain_model( payment_intent: &super::PaymentIntent, cell_id: id_type::CellId, storage_scheme: storage_enums::MerchantStorageScheme, request: &api_models::payments::ProxyPaymentsRequest, encrypted_data: DecryptedPaymentAttempt, ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> { let id = id_type::GlobalAttemptId::generate(&cell_id); let intent_amount_details = payment_intent.amount_details.clone(); let attempt_amount_details = intent_amount_details.proxy_create_attempt_amount_details(request); let now = common_utils::date_time::now(); let payment_method_billing_address = encrypted_data .payment_method_billing_address .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?; let connector_token = Some(diesel_models::ConnectorTokenDetails { connector_mandate_id: None, connector_token_request_reference_id: Some(common_utils::generate_id_with_len( consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH, )), }); let payment_method_type_data = payment_intent.get_payment_method_type(); let payment_method_subtype_data = payment_intent.get_payment_method_sub_type(); let authentication_type = payment_intent.authentication_type.unwrap_or_default(); Ok(Self { payment_id: payment_intent.id.clone(), merchant_id: payment_intent.merchant_id.clone(), attempts_group_id: None, amount_details: attempt_amount_details, status: common_enums::AttemptStatus::Started, connector: Some(request.connector.clone()), authentication_type, created_at: now, modified_at: now, last_synced: None, cancellation_reason: None, browser_info: request.browser_info.clone(), payment_token: None, connector_metadata: None, payment_experience: None, payment_method_data: None, routing_result: None, preprocessing_step_id: None, multiple_capture_count: None, connector_response_reference_id: None, updated_by: storage_scheme.to_string(), redirection_data: None, encoded_data: None, merchant_connector_id: Some(request.merchant_connector_id.clone()), external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, charges: None, client_source: None, client_version: None, customer_acceptance: None, profile_id: payment_intent.profile_id.clone(), organization_id: payment_intent.organization_id.clone(), payment_method_type: payment_method_type_data .unwrap_or(common_enums::PaymentMethod::Card), payment_method_id: None, connector_payment_id: None, payment_method_subtype: payment_method_subtype_data .unwrap_or(common_enums::PaymentMethodType::Credit), authentication_applied: None, external_reference_id: None, payment_method_billing_address, error: None, connector_token_details: connector_token, feature_metadata: None, id, card_discovery: None, processor_merchant_id: payment_intent.merchant_id.clone(), created_by: None, connector_request_reference_id: None, network_transaction_id: None, authorized_amount: None, }) } #[cfg(feature = "v2")] pub async fn external_vault_proxy_create_domain_model( payment_intent: &super::PaymentIntent, cell_id: id_type::CellId, storage_scheme: storage_enums::MerchantStorageScheme, request: &api_models::payments::ExternalVaultProxyPaymentsRequest, encrypted_data: DecryptedPaymentAttempt, ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> { let id = id_type::GlobalAttemptId::generate(&cell_id); let intent_amount_details = payment_intent.amount_details.clone(); let attempt_amount_details = AttemptAmountDetails { net_amount: intent_amount_details.order_amount, amount_to_capture: None, surcharge_amount: None, tax_on_surcharge: None, amount_capturable: intent_amount_details.order_amount, shipping_cost: None, order_tax_amount: None, }; let now = common_utils::date_time::now(); let payment_method_billing_address = encrypted_data .payment_method_billing_address .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?; let connector_token = Some(diesel_models::ConnectorTokenDetails { connector_mandate_id: None, connector_token_request_reference_id: Some(common_utils::generate_id_with_len( consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH, )), }); let payment_method_type_data = payment_intent.get_payment_method_type(); let payment_method_subtype_data = payment_intent.get_payment_method_sub_type(); let authentication_type = payment_intent.authentication_type.unwrap_or_default(); Ok(Self { payment_id: payment_intent.id.clone(), merchant_id: payment_intent.merchant_id.clone(), attempts_group_id: None, amount_details: attempt_amount_details, status: common_enums::AttemptStatus::Started, connector: None, authentication_type, created_at: now, modified_at: now, last_synced: None, cancellation_reason: None, browser_info: request.browser_info.clone(), payment_token: request.payment_token.clone(), connector_metadata: None, payment_experience: None, payment_method_data: None, routing_result: None, preprocessing_step_id: None, multiple_capture_count: None, connector_response_reference_id: None, updated_by: storage_scheme.to_string(), redirection_data: None, encoded_data: None, merchant_connector_id: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, charges: None, client_source: None, client_version: None, customer_acceptance: request.customer_acceptance.clone().map(Secret::new), profile_id: payment_intent.profile_id.clone(), organization_id: payment_intent.organization_id.clone(), payment_method_type: payment_method_type_data .unwrap_or(common_enums::PaymentMethod::Card), payment_method_id: request.payment_method_id.clone(), connector_payment_id: None, payment_method_subtype: payment_method_subtype_data .unwrap_or(common_enums::PaymentMethodType::Credit), authentication_applied: None, external_reference_id: None, payment_method_billing_address, error: None, connector_token_details: connector_token, feature_metadata: None, id, card_discovery: None, processor_merchant_id: payment_intent.merchant_id.clone(), created_by: None, connector_request_reference_id: None, network_transaction_id: None, authorized_amount: None, }) } /// Construct the domain model from the ConfirmIntentRequest and PaymentIntent #[cfg(feature = "v2")] pub async fn create_domain_model_using_record_request( payment_intent: &super::PaymentIntent, cell_id: id_type::CellId, storage_scheme: storage_enums::MerchantStorageScheme, request: &api_models::payments::PaymentsAttemptRecordRequest, encrypted_data: DecryptedPaymentAttempt, ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> { let id = id_type::GlobalAttemptId::generate(&cell_id); let amount_details = AttemptAmountDetailsSetter::from(&request.amount_details); let now = common_utils::date_time::now(); // we consume transaction_created_at from webhook request, if it is not present we take store current time as transaction_created_at. let transaction_created_at = request .transaction_created_at .unwrap_or(common_utils::date_time::now()); // This function is called in the record attempt flow, which tells us that this is a payment attempt created by an external system. let feature_metadata = PaymentAttemptFeatureMetadata { revenue_recovery: Some({ PaymentAttemptRevenueRecoveryData { attempt_triggered_by: request.triggered_by, charge_id: request.feature_metadata.as_ref().and_then(|metadata| { metadata .revenue_recovery .as_ref() .and_then(|data| data.charge_id.clone()) }), } }), }; let payment_method_data = request .payment_method_data .as_ref() .map(|data| data.payment_method_data.clone().encode_to_value()) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode additional payment method data")? .map(pii::SecretSerdeValue::new); let payment_method_billing_address = encrypted_data .payment_method_billing_address .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?; let error = request.error.as_ref().map(ErrorDetails::from); let connector_payment_id = request .connector_transaction_id .as_ref() .map(|txn_id| txn_id.get_id().clone()); let connector = request.connector.map(|connector| connector.to_string()); let connector_request_reference_id = payment_intent .merchant_reference_id .as_ref() .map(|id| id.get_string_repr().to_owned()); Ok(Self { payment_id: payment_intent.id.clone(), merchant_id: payment_intent.merchant_id.clone(), attempts_group_id: None, amount_details: AttemptAmountDetails::from(amount_details), status: request.status, connector, authentication_type: storage_enums::AuthenticationType::NoThreeDs, created_at: transaction_created_at, modified_at: now, last_synced: None, cancellation_reason: None, browser_info: None, payment_token: None, connector_metadata: None, payment_experience: None, payment_method_data, routing_result: None, preprocessing_step_id: None, multiple_capture_count: None, connector_response_reference_id: None, updated_by: storage_scheme.to_string(), redirection_data: None, encoded_data: None, merchant_connector_id: request.payment_merchant_connector_id.clone(), external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, client_source: None, client_version: None, customer_acceptance: None, profile_id: payment_intent.profile_id.clone(), organization_id: payment_intent.organization_id.clone(), payment_method_type: request.payment_method_type, payment_method_id: None, connector_payment_id, payment_method_subtype: request.payment_method_subtype, authentication_applied: None, external_reference_id: None, payment_method_billing_address, error, feature_metadata: Some(feature_metadata), id, connector_token_details: Some(diesel_models::ConnectorTokenDetails { connector_mandate_id: Some(request.processor_payment_method_token.clone()), connector_token_request_reference_id: None, }), card_discovery: None, charges: None, processor_merchant_id: payment_intent.merchant_id.clone(), created_by: None, connector_request_reference_id, network_transaction_id: None, authorized_amount: None, }) } pub fn get_attempt_merchant_connector_account_id( &self, ) -> CustomResult< id_type::MerchantConnectorAccountId, errors::api_error_response::ApiErrorResponse, > { let merchant_connector_id = self .merchant_connector_id .clone() .get_required_value("merchant_connector_id") .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Merchant connector id is None")?; Ok(merchant_connector_id) } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct PaymentAttempt { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, pub net_amount: NetAmount, pub currency: Option<storage_enums::Currency>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, pub offer_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub error_code: Option<String>, pub payment_token: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_data: Option<serde_json::Value>, pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, // providing a location to store mandate details intermediately for transaction pub mandate_details: Option<MandateDataType>, pub error_reason: Option<String>, pub multiple_capture_count: Option<i16>, // reference to the payment at connector side pub connector_response_reference_id: Option<String>, pub amount_capturable: MinorUnit, pub updated_by: String, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<id_type::AuthenticationId>, pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, pub charge_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub issuer_error_code: Option<String>, pub issuer_error_message: Option<String>, /// merchant who owns the credentials of the processor, i.e. processor owner pub processor_merchant_id: id_type::MerchantId, /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) pub created_by: Option<CreatedBy>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, pub routing_approach: Option<storage_enums::RoutingApproach>, pub connector_request_reference_id: Option<String>, pub debit_routing_savings: Option<MinorUnit>, pub network_transaction_id: Option<String>, pub is_overcapture_enabled: Option<OvercaptureEnabledBool>, pub network_details: Option<NetworkDetails>, pub is_stored_credential: Option<bool>, /// stores the authorized amount in case of partial authorization pub authorized_amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default)] pub struct NetAmount { /// The payment amount order_amount: MinorUnit, /// The shipping cost of the order shipping_cost: Option<MinorUnit>, /// Tax amount related to the order order_tax_amount: Option<MinorUnit>, /// The surcharge amount to be added to the order surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v1")] impl NetAmount { pub fn new( order_amount: MinorUnit, shipping_cost: Option<MinorUnit>, order_tax_amount: Option<MinorUnit>, surcharge_amount: Option<MinorUnit>, tax_on_surcharge: Option<MinorUnit>, ) -> Self { Self { order_amount, shipping_cost, order_tax_amount, surcharge_amount, tax_on_surcharge, } } pub fn get_order_amount(&self) -> MinorUnit { self.order_amount } pub fn get_shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn get_order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn get_surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn get_tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount .map(|surcharge_amount| surcharge_amount + self.tax_on_surcharge.unwrap_or_default()) } pub fn get_total_amount(&self) -> MinorUnit { self.order_amount + self.shipping_cost.unwrap_or_default() + self.order_tax_amount.unwrap_or_default() + self.surcharge_amount.unwrap_or_default() + self.tax_on_surcharge.unwrap_or_default() } pub fn get_additional_amount(&self) -> MinorUnit { self.get_total_amount() - self.get_order_amount() } pub fn set_order_amount(&mut self, order_amount: MinorUnit) { self.order_amount = order_amount; } pub fn set_order_tax_amount(&mut self, order_tax_amount: Option<MinorUnit>) { self.order_tax_amount = order_tax_amount; } pub fn set_surcharge_details( &mut self, surcharge_details: Option<router_request_types::SurchargeDetails>, ) { self.surcharge_amount = surcharge_details .clone() .map(|details| details.surcharge_amount); self.tax_on_surcharge = surcharge_details.map(|details| details.tax_on_surcharge_amount); } pub fn from_payments_request( payments_request: &api_models::payments::PaymentsRequest, order_amount: MinorUnit, ) -> Self { let surcharge_amount = payments_request .surcharge_details .map(|surcharge_details| surcharge_details.surcharge_amount); let tax_on_surcharge = payments_request .surcharge_details .and_then(|surcharge_details| surcharge_details.tax_amount); Self { order_amount, shipping_cost: payments_request.shipping_cost, order_tax_amount: payments_request.order_tax_amount, surcharge_amount, tax_on_surcharge, } } #[cfg(feature = "v1")] pub fn from_payments_request_and_payment_attempt( payments_request: &api_models::payments::PaymentsRequest, payment_attempt: Option<&PaymentAttempt>, ) -> Option<Self> { let option_order_amount = payments_request .amount .map(MinorUnit::from) .or(payment_attempt .map(|payment_attempt| payment_attempt.net_amount.get_order_amount())); option_order_amount.map(|order_amount| { let shipping_cost = payments_request.shipping_cost.or(payment_attempt .and_then(|payment_attempt| payment_attempt.net_amount.get_shipping_cost())); let order_tax_amount = payment_attempt .and_then(|payment_attempt| payment_attempt.net_amount.get_order_tax_amount()); let surcharge_amount = payments_request .surcharge_details .map(|surcharge_details| surcharge_details.get_surcharge_amount()) .or_else(|| { payment_attempt.and_then(|payment_attempt| { payment_attempt.net_amount.get_surcharge_amount() }) }); let tax_on_surcharge = payments_request .surcharge_details .and_then(|surcharge_details| surcharge_details.get_tax_amount()) .or_else(|| { payment_attempt.and_then(|payment_attempt| { payment_attempt.net_amount.get_tax_on_surcharge() }) }); Self { order_amount, shipping_cost, order_tax_amount, surcharge_amount, tax_on_surcharge, } }) } } #[cfg(feature = "v2")] impl PaymentAttempt { #[track_caller] pub fn get_total_amount(&self) -> MinorUnit { self.amount_details.get_net_amount() } pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> { self.amount_details.surcharge_amount } pub fn extract_card_network(&self) -> Option<common_enums::CardNetwork> { todo!() } } #[cfg(feature = "v1")] impl PaymentAttempt { pub fn get_total_amount(&self) -> MinorUnit { self.net_amount.get_total_amount() } pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> { self.net_amount.get_total_surcharge_amount() } pub fn set_debit_routing_savings(&mut self, debit_routing_savings: Option<&MinorUnit>) { self.debit_routing_savings = debit_routing_savings.copied(); } pub fn extract_card_network(&self) -> Option<common_enums::CardNetwork> { self.payment_method_data .as_ref() .and_then(|value| { value .clone() .parse_value::<api_models::payments::AdditionalPaymentData>( "AdditionalPaymentData", ) .ok() }) .and_then(|data| data.get_additional_card_info()) .and_then(|card_info| card_info.card_network) } pub fn get_payment_method_data(&self) -> Option<api_models::payments::AdditionalPaymentData> { self.payment_method_data .clone() .and_then(|data| match data { serde_json::Value::Null => None, _ => Some(data.parse_value("AdditionalPaymentData")), }) .transpose() .map_err(|err| logger::error!("Failed to parse AdditionalPaymentData {err:?}")) .ok() .flatten() } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct PaymentListFilters { pub connector: Vec<String>, pub currency: Vec<storage_enums::Currency>, pub status: Vec<storage_enums::IntentStatus>, pub payment_method: Vec<storage_enums::PaymentMethod>, pub payment_method_type: Vec<storage_enums::PaymentMethodType>, pub authentication_type: Vec<storage_enums::AuthenticationType>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Serialize, Deserialize)] pub struct PaymentAttemptNew { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, /// amount + surcharge_amount + tax_amount /// This field will always be derived before updating in the Database pub net_amount: NetAmount, pub currency: Option<storage_enums::Currency>, // pub auto_capture: Option<bool>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, pub offer_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub capture_method: Option<storage_enums::CaptureMethod>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub payment_token: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_data: Option<serde_json::Value>, pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, pub mandate_details: Option<MandateDataType>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub updated_by: String, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<id_type::AuthenticationId>, pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, /// merchant who owns the credentials of the processor, i.e. processor owner pub processor_merchant_id: id_type::MerchantId, /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) pub created_by: Option<CreatedBy>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, pub routing_approach: Option<storage_enums::RoutingApproach>, pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub network_details: Option<NetworkDetails>, pub is_stored_credential: Option<bool>, pub authorized_amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentAttemptUpdate { Update { net_amount: NetAmount, currency: storage_enums::Currency, status: storage_enums::AttemptStatus, authentication_type: Option<storage_enums::AuthenticationType>, payment_method: Option<storage_enums::PaymentMethod>, payment_token: Option<String>, payment_method_data: Option<serde_json::Value>, payment_method_type: Option<storage_enums::PaymentMethodType>, payment_experience: Option<storage_enums::PaymentExperience>, business_sub_label: Option<String>, amount_to_capture: Option<MinorUnit>, capture_method: Option<storage_enums::CaptureMethod>, fingerprint_id: Option<String>, payment_method_billing_address_id: Option<String>, updated_by: String, network_transaction_id: Option<String>, }, UpdateTrackers { payment_token: Option<String>, connector: Option<String>, straight_through_algorithm: Option<serde_json::Value>, amount_capturable: Option<MinorUnit>, surcharge_amount: Option<MinorUnit>, tax_amount: Option<MinorUnit>, updated_by: String, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, routing_approach: Option<storage_enums::RoutingApproach>, is_stored_credential: Option<bool>, }, AuthenticationTypeUpdate { authentication_type: storage_enums::AuthenticationType, updated_by: String, }, ConfirmUpdate { net_amount: NetAmount, currency: storage_enums::Currency, status: storage_enums::AttemptStatus, authentication_type: Option<storage_enums::AuthenticationType>, capture_method: Option<storage_enums::CaptureMethod>, payment_method: Option<storage_enums::PaymentMethod>, browser_info: Option<serde_json::Value>, connector: Option<String>, payment_token: Option<String>, payment_method_data: Option<serde_json::Value>, payment_method_type: Option<storage_enums::PaymentMethodType>, payment_experience: Option<storage_enums::PaymentExperience>, business_sub_label: Option<String>, straight_through_algorithm: Option<serde_json::Value>, error_code: Option<Option<String>>, error_message: Option<Option<String>>, updated_by: String, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, external_three_ds_authentication_attempted: Option<bool>, authentication_connector: Option<String>, authentication_id: Option<id_type::AuthenticationId>, payment_method_billing_address_id: Option<String>, fingerprint_id: Option<String>, payment_method_id: Option<String>, client_source: Option<String>, client_version: Option<String>, customer_acceptance: Option<pii::SecretSerdeValue>, connector_mandate_detail: Option<ConnectorMandateReferenceId>, card_discovery: Option<common_enums::CardDiscovery>, routing_approach: Option<storage_enums::RoutingApproach>, connector_request_reference_id: Option<String>, network_transaction_id: Option<String>, is_stored_credential: Option<bool>, request_extended_authorization: Option<RequestExtendedAuthorizationBool>, }, RejectUpdate { status: storage_enums::AttemptStatus, error_code: Option<Option<String>>, error_message: Option<Option<String>>, updated_by: String, }, BlocklistUpdate { status: storage_enums::AttemptStatus, error_code: Option<Option<String>>, error_message: Option<Option<String>>, updated_by: String, }, PaymentMethodDetailsUpdate { payment_method_id: Option<String>, updated_by: String, }, ConnectorMandateDetailUpdate { connector_mandate_detail: Option<ConnectorMandateReferenceId>, updated_by: String, }, VoidUpdate { status: storage_enums::AttemptStatus, cancellation_reason: Option<String>, updated_by: String, }, ResponseUpdate { status: storage_enums::AttemptStatus, connector: Option<String>, connector_transaction_id: Option<String>, network_transaction_id: Option<String>, authentication_type: Option<storage_enums::AuthenticationType>, payment_method_id: Option<String>, mandate_id: Option<String>, connector_metadata: Option<serde_json::Value>, payment_token: Option<String>, error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, connector_response_reference_id: Option<String>, amount_capturable: Option<MinorUnit>, updated_by: String, authentication_data: Option<serde_json::Value>, encoded_data: Option<String>, unified_code: Option<Option<String>>, unified_message: Option<Option<String>>, capture_before: Option<PrimitiveDateTime>, extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, payment_method_data: Option<serde_json::Value>, connector_mandate_detail: Option<ConnectorMandateReferenceId>, charges: Option<common_types::payments::ConnectorChargeResponseData>, setup_future_usage_applied: Option<storage_enums::FutureUsage>, debit_routing_savings: Option<MinorUnit>, is_overcapture_enabled: Option<OvercaptureEnabledBool>, authorized_amount: Option<MinorUnit>, }, UnresolvedResponseUpdate { status: storage_enums::AttemptStatus, connector: Option<String>, connector_transaction_id: Option<String>, payment_method_id: Option<String>, error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, connector_response_reference_id: Option<String>, updated_by: String, }, StatusUpdate { status: storage_enums::AttemptStatus, updated_by: String, }, ErrorUpdate { connector: Option<String>, status: storage_enums::AttemptStatus, error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, amount_capturable: Option<MinorUnit>, updated_by: String, unified_code: Option<Option<String>>, unified_message: Option<Option<String>>, connector_transaction_id: Option<String>, payment_method_data: Option<serde_json::Value>, authentication_type: Option<storage_enums::AuthenticationType>, issuer_error_code: Option<String>, issuer_error_message: Option<String>, network_details: Option<NetworkDetails>, }, CaptureUpdate { amount_to_capture: Option<MinorUnit>, multiple_capture_count: Option<i16>, updated_by: String, }, AmountToCaptureUpdate { status: storage_enums::AttemptStatus, amount_capturable: MinorUnit, updated_by: String, }, PreprocessingUpdate { status: storage_enums::AttemptStatus, payment_method_id: Option<String>, connector_metadata: Option<serde_json::Value>, preprocessing_step_id: Option<String>, connector_transaction_id: Option<String>, connector_response_reference_id: Option<String>, updated_by: String, }, ConnectorResponse { authentication_data: Option<serde_json::Value>, encoded_data: Option<String>, connector_transaction_id: Option<String>, connector: Option<String>, charges: Option<common_types::payments::ConnectorChargeResponseData>, updated_by: String, }, IncrementalAuthorizationAmountUpdate { net_amount: NetAmount, amount_capturable: MinorUnit, }, AuthenticationUpdate { status: storage_enums::AttemptStatus, external_three_ds_authentication_attempted: Option<bool>, authentication_connector: Option<String>, authentication_id: Option<id_type::AuthenticationId>, updated_by: String, }, ManualUpdate { status: Option<storage_enums::AttemptStatus>, error_code: Option<String>, error_message: Option<String>, error_reason: Option<String>, updated_by: String, unified_code: Option<String>, unified_message: Option<String>, connector_transaction_id: Option<String>, }, PostSessionTokensUpdate { updated_by: String, connector_metadata: Option<serde_json::Value>, }, } #[cfg(feature = "v1")] impl PaymentAttemptUpdate { pub fn to_storage_model(self) -> diesel_models::PaymentAttemptUpdate { match self { Self::Update { net_amount, currency, status, authentication_type, payment_method, payment_token, payment_method_data, payment_method_type, payment_experience, business_sub_label, amount_to_capture, capture_method, fingerprint_id, network_transaction_id, payment_method_billing_address_id, updated_by, } => DieselPaymentAttemptUpdate::Update { amount: net_amount.get_order_amount(), currency, status, authentication_type, payment_method, payment_token, payment_method_data, payment_method_type, payment_experience, business_sub_label, amount_to_capture, capture_method, surcharge_amount: net_amount.get_surcharge_amount(), tax_amount: net_amount.get_tax_on_surcharge(), fingerprint_id, payment_method_billing_address_id, network_transaction_id, updated_by, }, Self::UpdateTrackers { payment_token, connector, straight_through_algorithm, amount_capturable, updated_by, surcharge_amount, tax_amount, merchant_connector_id, routing_approach, is_stored_credential, } => DieselPaymentAttemptUpdate::UpdateTrackers { payment_token, connector, straight_through_algorithm, amount_capturable, surcharge_amount, tax_amount, updated_by, merchant_connector_id, routing_approach: routing_approach.map(|approach| match approach { storage_enums::RoutingApproach::Other(_) => { // we need to make sure Other variant is not stored in DB, in the rare case // where we attempt to store an unknown value, we default to the default value storage_enums::RoutingApproach::default() } _ => approach, }), is_stored_credential, }, Self::AuthenticationTypeUpdate { authentication_type, updated_by, } => DieselPaymentAttemptUpdate::AuthenticationTypeUpdate { authentication_type, updated_by, }, Self::BlocklistUpdate { status, error_code, error_message, updated_by, } => DieselPaymentAttemptUpdate::BlocklistUpdate { status, error_code, error_message, updated_by, }, Self::ConnectorMandateDetailUpdate { connector_mandate_detail, updated_by, } => DieselPaymentAttemptUpdate::ConnectorMandateDetailUpdate { connector_mandate_detail, updated_by, }, Self::PaymentMethodDetailsUpdate { payment_method_id, updated_by, } => DieselPaymentAttemptUpdate::PaymentMethodDetailsUpdate { payment_method_id, updated_by, }, Self::ConfirmUpdate { net_amount, currency, status, authentication_type, capture_method, payment_method, browser_info, connector, payment_token, payment_method_data, payment_method_type, payment_experience, business_sub_label, straight_through_algorithm, error_code, error_message, fingerprint_id, updated_by, merchant_connector_id: connector_id, payment_method_id, external_three_ds_authentication_attempted, authentication_connector, authentication_id, payment_method_billing_address_id, client_source, client_version, customer_acceptance, connector_mandate_detail, card_discovery, routing_approach, connector_request_reference_id, network_transaction_id, is_stored_credential, request_extended_authorization, } => DieselPaymentAttemptUpdate::ConfirmUpdate { amount: net_amount.get_order_amount(), currency, status, authentication_type, capture_method, payment_method, browser_info, connector, payment_token, payment_method_data, payment_method_type, payment_experience, business_sub_label, straight_through_algorithm, error_code, error_message, surcharge_amount: net_amount.get_surcharge_amount(), tax_amount: net_amount.get_tax_on_surcharge(), fingerprint_id, updated_by, merchant_connector_id: connector_id, payment_method_id, external_three_ds_authentication_attempted, authentication_connector, authentication_id, payment_method_billing_address_id, client_source, client_version, customer_acceptance, shipping_cost: net_amount.get_shipping_cost(), order_tax_amount: net_amount.get_order_tax_amount(), connector_mandate_detail, card_discovery, routing_approach: routing_approach.map(|approach| match approach { // we need to make sure Other variant is not stored in DB, in the rare case // where we attempt to store an unknown value, we default to the default value storage_enums::RoutingApproach::Other(_) => { storage_enums::RoutingApproach::default() } _ => approach, }), connector_request_reference_id, network_transaction_id, is_stored_credential, request_extended_authorization, }, Self::VoidUpdate { status, cancellation_reason, updated_by, } => DieselPaymentAttemptUpdate::VoidUpdate { status, cancellation_reason, updated_by, }, Self::ResponseUpdate { status, connector, connector_transaction_id, authentication_type, payment_method_id, mandate_id, connector_metadata, payment_token, error_code, error_message, error_reason, connector_response_reference_id, amount_capturable, updated_by, authentication_data, encoded_data, unified_code, unified_message, capture_before, extended_authorization_applied, payment_method_data, connector_mandate_detail, charges, setup_future_usage_applied, network_transaction_id, debit_routing_savings: _, is_overcapture_enabled, authorized_amount, } => DieselPaymentAttemptUpdate::ResponseUpdate { status, connector, connector_transaction_id, authentication_type, payment_method_id, mandate_id, connector_metadata, payment_token, error_code, error_message, error_reason, connector_response_reference_id, amount_capturable, updated_by, authentication_data, encoded_data, unified_code, unified_message, capture_before, extended_authorization_applied, payment_method_data, connector_mandate_detail, charges, setup_future_usage_applied, network_transaction_id, is_overcapture_enabled, authorized_amount, }, Self::UnresolvedResponseUpdate { status, connector, connector_transaction_id, payment_method_id, error_code, error_message, error_reason, connector_response_reference_id, updated_by, } => DieselPaymentAttemptUpdate::UnresolvedResponseUpdate { status, connector, connector_transaction_id, payment_method_id, error_code, error_message, error_reason, connector_response_reference_id, updated_by, }, Self::StatusUpdate { status, updated_by } => { DieselPaymentAttemptUpdate::StatusUpdate { status, updated_by } } Self::ErrorUpdate { connector, status, error_code, error_message, error_reason, amount_capturable, updated_by, unified_code, unified_message, connector_transaction_id, payment_method_data, authentication_type, issuer_error_code, issuer_error_message, network_details, } => DieselPaymentAttemptUpdate::ErrorUpdate { connector, status, error_code, error_message, error_reason, amount_capturable, updated_by, unified_code, unified_message, connector_transaction_id, payment_method_data, authentication_type, issuer_error_code, issuer_error_message, network_details, }, Self::CaptureUpdate { multiple_capture_count, updated_by, amount_to_capture, } => DieselPaymentAttemptUpdate::CaptureUpdate { multiple_capture_count, updated_by, amount_to_capture, }, Self::PreprocessingUpdate { status, payment_method_id, connector_metadata, preprocessing_step_id, connector_transaction_id, connector_response_reference_id, updated_by, } => DieselPaymentAttemptUpdate::PreprocessingUpdate { status, payment_method_id, connector_metadata, preprocessing_step_id, connector_transaction_id, connector_response_reference_id, updated_by, }, Self::RejectUpdate { status, error_code, error_message, updated_by, } => DieselPaymentAttemptUpdate::RejectUpdate { status, error_code, error_message, updated_by, }, Self::AmountToCaptureUpdate { status, amount_capturable, updated_by, } => DieselPaymentAttemptUpdate::AmountToCaptureUpdate { status, amount_capturable, updated_by, }, Self::ConnectorResponse { authentication_data, encoded_data, connector_transaction_id, connector, charges, updated_by, } => DieselPaymentAttemptUpdate::ConnectorResponse { authentication_data, encoded_data, connector_transaction_id, charges, connector, updated_by, }, Self::IncrementalAuthorizationAmountUpdate { net_amount, amount_capturable, } => DieselPaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { amount: net_amount.get_order_amount(), amount_capturable, }, Self::AuthenticationUpdate { status, external_three_ds_authentication_attempted, authentication_connector, authentication_id, updated_by, } => DieselPaymentAttemptUpdate::AuthenticationUpdate { status, external_three_ds_authentication_attempted, authentication_connector, authentication_id, updated_by, }, Self::ManualUpdate { status, error_code, error_message, error_reason, updated_by, unified_code, unified_message, connector_transaction_id, } => DieselPaymentAttemptUpdate::ManualUpdate { status, error_code, error_message, error_reason, updated_by, unified_code, unified_message, connector_transaction_id, }, Self::PostSessionTokensUpdate { updated_by, connector_metadata, } => DieselPaymentAttemptUpdate::PostSessionTokensUpdate { updated_by, connector_metadata, }, } } pub fn get_debit_routing_savings(&self) -> Option<&MinorUnit> { match self { Self::ResponseUpdate { debit_routing_savings, .. } => debit_routing_savings.as_ref(), Self::Update { .. } | Self::UpdateTrackers { .. } | Self::AuthenticationTypeUpdate { .. } | Self::ConfirmUpdate { .. } | Self::RejectUpdate { .. } | Self::BlocklistUpdate { .. } | Self::PaymentMethodDetailsUpdate { .. } | Self::ConnectorMandateDetailUpdate { .. } | Self::VoidUpdate { .. } | Self::UnresolvedResponseUpdate { .. } | Self::StatusUpdate { .. } | Self::ErrorUpdate { .. } | Self::CaptureUpdate { .. } | Self::AmountToCaptureUpdate { .. } | Self::PreprocessingUpdate { .. } | Self::ConnectorResponse { .. } | Self::IncrementalAuthorizationAmountUpdate { .. } | Self::AuthenticationUpdate { .. } | Self::ManualUpdate { .. } | Self::PostSessionTokensUpdate { .. } => None, } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize)] pub struct ConfirmIntentResponseUpdate { pub status: storage_enums::AttemptStatus, pub connector_payment_id: Option<String>, pub updated_by: String, pub redirection_data: Option<router_response_types::RedirectForm>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub amount_capturable: Option<MinorUnit>, pub connector_token_details: Option<diesel_models::ConnectorTokenDetails>, pub connector_response_reference_id: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize)] pub enum PaymentAttemptUpdate { /// Update the payment attempt on confirming the intent, before calling the connector ConfirmIntent { status: storage_enums::AttemptStatus, updated_by: String, connector: String, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, authentication_type: storage_enums::AuthenticationType, connector_request_reference_id: Option<String>, connector_response_reference_id: Option<String>, }, /// Update the payment attempt on confirming the intent, before calling the connector, when payment_method_id is present ConfirmIntentTokenized { status: storage_enums::AttemptStatus, updated_by: String, connector: String, merchant_connector_id: id_type::MerchantConnectorAccountId, authentication_type: storage_enums::AuthenticationType, payment_method_id: id_type::GlobalPaymentMethodId, connector_request_reference_id: Option<String>, }, /// Update the payment attempt on confirming the intent, after calling the connector on success response ConfirmIntentResponse(Box<ConfirmIntentResponseUpdate>), /// Update the payment attempt after force syncing with the connector SyncUpdate { status: storage_enums::AttemptStatus, amount_capturable: Option<MinorUnit>, updated_by: String, }, PreCaptureUpdate { amount_to_capture: Option<MinorUnit>, updated_by: String, }, /// Update the payment after attempting capture with the connector CaptureUpdate { status: storage_enums::AttemptStatus, amount_capturable: Option<MinorUnit>, updated_by: String, }, /// Update the payment attempt on confirming the intent, after calling the connector on error response ErrorUpdate { status: storage_enums::AttemptStatus, amount_capturable: Option<MinorUnit>, error: ErrorDetails, updated_by: String, connector_payment_id: Option<String>, }, VoidUpdate { status: storage_enums::AttemptStatus, cancellation_reason: Option<String>, updated_by: String, }, } #[cfg(feature = "v2")] impl ForeignIDRef for PaymentAttempt { fn foreign_id(&self) -> String { todo!() } } #[cfg(feature = "v1")] impl ForeignIDRef for PaymentAttempt { fn foreign_id(&self) -> String { self.attempt_id.clone() } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl behaviour::Conversion for PaymentAttempt { type DstType = DieselPaymentAttempt; type NewDstType = DieselPaymentAttemptNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let card_network = self .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()); let (connector_transaction_id, processor_transaction_data) = self .connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Ok(DieselPaymentAttempt { payment_id: self.payment_id, merchant_id: self.merchant_id, attempt_id: self.attempt_id, status: self.status, amount: self.net_amount.get_order_amount(), currency: self.currency, save_to_locker: self.save_to_locker, connector: self.connector, error_message: self.error_message, offer_amount: self.offer_amount, surcharge_amount: self.net_amount.get_surcharge_amount(), tax_amount: self.net_amount.get_tax_on_surcharge(), payment_method_id: self.payment_method_id, payment_method: self.payment_method, connector_transaction_id, capture_method: self.capture_method, capture_on: self.capture_on, confirm: self.confirm, authentication_type: self.authentication_type, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, amount_to_capture: self.amount_to_capture, mandate_id: self.mandate_id, browser_info: self.browser_info, error_code: self.error_code, payment_token: self.payment_token, connector_metadata: self.connector_metadata, payment_experience: self.payment_experience, payment_method_type: self.payment_method_type, payment_method_data: self.payment_method_data, business_sub_label: self.business_sub_label, straight_through_algorithm: self.straight_through_algorithm, preprocessing_step_id: self.preprocessing_step_id, mandate_details: self.mandate_details.map(Into::into), error_reason: self.error_reason, multiple_capture_count: self.multiple_capture_count, connector_response_reference_id: self.connector_response_reference_id, amount_capturable: self.amount_capturable, updated_by: self.updated_by, merchant_connector_id: self.merchant_connector_id, authentication_data: self.authentication_data, encoded_data: self.encoded_data, unified_code: self.unified_code, unified_message: self.unified_message, net_amount: Some(self.net_amount.get_total_amount()), external_three_ds_authentication_attempted: self .external_three_ds_authentication_attempted, authentication_connector: self.authentication_connector, authentication_id: self.authentication_id, mandate_data: self.mandate_data.map(Into::into), fingerprint_id: self.fingerprint_id, payment_method_billing_address_id: self.payment_method_billing_address_id, charge_id: self.charge_id, client_source: self.client_source, client_version: self.client_version, customer_acceptance: self.customer_acceptance, profile_id: self.profile_id, organization_id: self.organization_id, card_network, order_tax_amount: self.net_amount.get_order_tax_amount(), shipping_cost: self.net_amount.get_shipping_cost(), connector_mandate_detail: self.connector_mandate_detail, request_extended_authorization: self.request_extended_authorization, extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, processor_transaction_data, card_discovery: self.card_discovery, charges: self.charges, issuer_error_code: self.issuer_error_code, issuer_error_message: self.issuer_error_message, setup_future_usage_applied: self.setup_future_usage_applied, // Below fields are deprecated. Please add any new fields above this line. connector_transaction_data: None, processor_merchant_id: Some(self.processor_merchant_id), created_by: self.created_by.map(|cb| cb.to_string()), routing_approach: self.routing_approach, connector_request_reference_id: self.connector_request_reference_id, network_transaction_id: self.network_transaction_id, is_overcapture_enabled: self.is_overcapture_enabled, network_details: self.network_details, is_stored_credential: self.is_stored_credential, authorized_amount: self.authorized_amount, }) } async fn convert_back( _state: &KeyManagerState, storage_model: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { async { let connector_transaction_id = storage_model .get_optional_connector_transaction_id() .cloned(); Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id.clone(), attempt_id: storage_model.attempt_id, status: storage_model.status, net_amount: NetAmount::new( storage_model.amount, storage_model.shipping_cost, storage_model.order_tax_amount, storage_model.surcharge_amount, storage_model.tax_amount, ), currency: storage_model.currency, save_to_locker: storage_model.save_to_locker, connector: storage_model.connector, error_message: storage_model.error_message, offer_amount: storage_model.offer_amount, payment_method_id: storage_model.payment_method_id, payment_method: storage_model.payment_method, connector_transaction_id, capture_method: storage_model.capture_method, capture_on: storage_model.capture_on, confirm: storage_model.confirm, authentication_type: storage_model.authentication_type, created_at: storage_model.created_at, modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, cancellation_reason: storage_model.cancellation_reason, amount_to_capture: storage_model.amount_to_capture, mandate_id: storage_model.mandate_id, browser_info: storage_model.browser_info, error_code: storage_model.error_code, payment_token: storage_model.payment_token, connector_metadata: storage_model.connector_metadata, payment_experience: storage_model.payment_experience, payment_method_type: storage_model.payment_method_type, payment_method_data: storage_model.payment_method_data, business_sub_label: storage_model.business_sub_label, straight_through_algorithm: storage_model.straight_through_algorithm, preprocessing_step_id: storage_model.preprocessing_step_id, mandate_details: storage_model.mandate_details.map(Into::into), error_reason: storage_model.error_reason, multiple_capture_count: storage_model.multiple_capture_count, connector_response_reference_id: storage_model.connector_response_reference_id, amount_capturable: storage_model.amount_capturable, updated_by: storage_model.updated_by, authentication_data: storage_model.authentication_data, encoded_data: storage_model.encoded_data, merchant_connector_id: storage_model.merchant_connector_id, unified_code: storage_model.unified_code, unified_message: storage_model.unified_message, external_three_ds_authentication_attempted: storage_model .external_three_ds_authentication_attempted, authentication_connector: storage_model.authentication_connector, authentication_id: storage_model.authentication_id, mandate_data: storage_model.mandate_data.map(Into::into), payment_method_billing_address_id: storage_model.payment_method_billing_address_id, fingerprint_id: storage_model.fingerprint_id, charge_id: storage_model.charge_id, client_source: storage_model.client_source, client_version: storage_model.client_version, customer_acceptance: storage_model.customer_acceptance, profile_id: storage_model.profile_id, organization_id: storage_model.organization_id, connector_mandate_detail: storage_model.connector_mandate_detail, request_extended_authorization: storage_model.request_extended_authorization, extended_authorization_applied: storage_model.extended_authorization_applied, capture_before: storage_model.capture_before, card_discovery: storage_model.card_discovery, charges: storage_model.charges, issuer_error_code: storage_model.issuer_error_code, issuer_error_message: storage_model.issuer_error_message, processor_merchant_id: storage_model .processor_merchant_id .unwrap_or(storage_model.merchant_id), created_by: storage_model .created_by .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), setup_future_usage_applied: storage_model.setup_future_usage_applied, routing_approach: storage_model.routing_approach, connector_request_reference_id: storage_model.connector_request_reference_id, debit_routing_savings: None, network_transaction_id: storage_model.network_transaction_id, is_overcapture_enabled: storage_model.is_overcapture_enabled, network_details: storage_model.network_details, is_stored_credential: storage_model.is_stored_credential, authorized_amount: storage_model.authorized_amount, }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting payment attempt".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let card_network = self .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()); Ok(DieselPaymentAttemptNew { payment_id: self.payment_id, merchant_id: self.merchant_id, attempt_id: self.attempt_id, status: self.status, amount: self.net_amount.get_order_amount(), currency: self.currency, save_to_locker: self.save_to_locker, connector: self.connector, error_message: self.error_message, offer_amount: self.offer_amount, surcharge_amount: self.net_amount.get_surcharge_amount(), tax_amount: self.net_amount.get_tax_on_surcharge(), payment_method_id: self.payment_method_id, payment_method: self.payment_method, capture_method: self.capture_method, capture_on: self.capture_on, confirm: self.confirm, authentication_type: self.authentication_type, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, amount_to_capture: self.amount_to_capture, mandate_id: self.mandate_id, browser_info: self.browser_info, payment_token: self.payment_token, error_code: self.error_code, connector_metadata: self.connector_metadata, payment_experience: self.payment_experience, payment_method_type: self.payment_method_type, payment_method_data: self.payment_method_data, business_sub_label: self.business_sub_label, straight_through_algorithm: self.straight_through_algorithm, preprocessing_step_id: self.preprocessing_step_id, mandate_details: self.mandate_details.map(Into::into), error_reason: self.error_reason, connector_response_reference_id: self.connector_response_reference_id, multiple_capture_count: self.multiple_capture_count, amount_capturable: self.amount_capturable, updated_by: self.updated_by, merchant_connector_id: self.merchant_connector_id, authentication_data: self.authentication_data, encoded_data: self.encoded_data, unified_code: self.unified_code, unified_message: self.unified_message, net_amount: Some(self.net_amount.get_total_amount()), external_three_ds_authentication_attempted: self .external_three_ds_authentication_attempted, authentication_connector: self.authentication_connector, authentication_id: self.authentication_id, mandate_data: self.mandate_data.map(Into::into), fingerprint_id: self.fingerprint_id, payment_method_billing_address_id: self.payment_method_billing_address_id, client_source: self.client_source, client_version: self.client_version, customer_acceptance: self.customer_acceptance, profile_id: self.profile_id, organization_id: self.organization_id, card_network, order_tax_amount: self.net_amount.get_order_tax_amount(), shipping_cost: self.net_amount.get_shipping_cost(), connector_mandate_detail: self.connector_mandate_detail, request_extended_authorization: self.request_extended_authorization, extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, card_discovery: self.card_discovery, processor_merchant_id: Some(self.processor_merchant_id), created_by: self.created_by.map(|cb| cb.to_string()), setup_future_usage_applied: self.setup_future_usage_applied, routing_approach: self.routing_approach, connector_request_reference_id: self.connector_request_reference_id, network_transaction_id: self.network_transaction_id, network_details: self.network_details, is_stored_credential: self.is_stored_credential, authorized_amount: self.authorized_amount, }) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl behaviour::Conversion for PaymentAttempt { type DstType = DieselPaymentAttempt; type NewDstType = DieselPaymentAttemptNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { use common_utils::encryption::Encryption; let card_network = self .payment_method_data .as_ref() .and_then(|data| data.peek().as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()); let Self { payment_id, merchant_id, attempts_group_id, status, error, amount_details, authentication_type, created_at, modified_at, last_synced, cancellation_reason, browser_info, payment_token, connector_metadata, payment_experience, payment_method_data, routing_result, preprocessing_step_id, multiple_capture_count, connector_response_reference_id, updated_by, redirection_data, encoded_data, merchant_connector_id, external_three_ds_authentication_attempted, authentication_connector, authentication_id, fingerprint_id, client_source, client_version, customer_acceptance, profile_id, organization_id, payment_method_type, connector_payment_id, payment_method_subtype, authentication_applied, external_reference_id, id, payment_method_id, payment_method_billing_address, connector, connector_token_details, card_discovery, charges, feature_metadata, processor_merchant_id, created_by, connector_request_reference_id, network_transaction_id, authorized_amount, } = self; let AttemptAmountDetails { net_amount, tax_on_surcharge, surcharge_amount, order_tax_amount, shipping_cost, amount_capturable, amount_to_capture, } = amount_details; let (connector_payment_id, connector_payment_data) = connector_payment_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); let feature_metadata = feature_metadata.as_ref().map(From::from); Ok(DieselPaymentAttempt { payment_id, merchant_id, id, status, error_message: error.as_ref().map(|details| details.message.clone()), payment_method_id, payment_method_type_v2: payment_method_type, connector_payment_id, authentication_type, created_at, modified_at, last_synced, cancellation_reason, amount_to_capture, browser_info, error_code: error.as_ref().map(|details| details.code.clone()), payment_token, connector_metadata, payment_experience, payment_method_subtype, payment_method_data, preprocessing_step_id, error_reason: error.as_ref().and_then(|details| details.reason.clone()), multiple_capture_count, connector_response_reference_id, amount_capturable, updated_by, merchant_connector_id, redirection_data: redirection_data.map(From::from), encoded_data, unified_code: error .as_ref() .and_then(|details| details.unified_code.clone()), unified_message: error .as_ref() .and_then(|details| details.unified_message.clone()), net_amount, external_three_ds_authentication_attempted, authentication_connector, authentication_id, fingerprint_id, client_source, client_version, customer_acceptance, profile_id, organization_id, card_network, order_tax_amount, shipping_cost, routing_result, authentication_applied, external_reference_id, connector, surcharge_amount, tax_on_surcharge, payment_method_billing_address: payment_method_billing_address.map(Encryption::from), connector_payment_data, connector_token_details, card_discovery, request_extended_authorization: None, extended_authorization_applied: None, capture_before: None, charges, feature_metadata, network_advice_code: error .as_ref() .and_then(|details| details.network_advice_code.clone()), network_decline_code: error .as_ref() .and_then(|details| details.network_decline_code.clone()), network_error_message: error .as_ref() .and_then(|details| details.network_error_message.clone()), processor_merchant_id: Some(processor_merchant_id), created_by: created_by.map(|cb| cb.to_string()), connector_request_reference_id, network_transaction_id, is_overcapture_enabled: None, network_details: None, attempts_group_id, is_stored_credential: None, authorized_amount, }) } async fn convert_back( state: &KeyManagerState, storage_model: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { async { let connector_payment_id = storage_model .get_optional_connector_transaction_id() .cloned(); let decrypted_data = crypto_operation( state, common_utils::type_name!(Self::DstType), CryptoOperation::BatchDecrypt(EncryptedPaymentAttempt::to_encryptable( EncryptedPaymentAttempt { payment_method_billing_address: storage_model .payment_method_billing_address, }, )), key_manager_identifier, key.peek(), ) .await .and_then(|val| val.try_into_batchoperation())?; let decrypted_data = EncryptedPaymentAttempt::from_encryptable(decrypted_data) .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Invalid batch operation data")?; let payment_method_billing_address = decrypted_data .payment_method_billing_address .map(|billing| { billing.deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing Address")?; let amount_details = AttemptAmountDetails { net_amount: storage_model.net_amount, tax_on_surcharge: storage_model.tax_on_surcharge, surcharge_amount: storage_model.surcharge_amount, order_tax_amount: storage_model.order_tax_amount, shipping_cost: storage_model.shipping_cost, amount_capturable: storage_model.amount_capturable, amount_to_capture: storage_model.amount_to_capture, }; let error = storage_model .error_code .zip(storage_model.error_message) .map(|(error_code, error_message)| ErrorDetails { code: error_code, message: error_message, reason: storage_model.error_reason, unified_code: storage_model.unified_code, unified_message: storage_model.unified_message, network_advice_code: storage_model.network_advice_code, network_decline_code: storage_model.network_decline_code, network_error_message: storage_model.network_error_message, }); Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id.clone(), attempts_group_id: storage_model.attempts_group_id, id: storage_model.id, status: storage_model.status, amount_details, error, payment_method_id: storage_model.payment_method_id, payment_method_type: storage_model.payment_method_type_v2, connector_payment_id, authentication_type: storage_model.authentication_type, created_at: storage_model.created_at, modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, cancellation_reason: storage_model.cancellation_reason, browser_info: storage_model.browser_info, payment_token: storage_model.payment_token, connector_metadata: storage_model.connector_metadata, payment_experience: storage_model.payment_experience, payment_method_data: storage_model.payment_method_data, routing_result: storage_model.routing_result, preprocessing_step_id: storage_model.preprocessing_step_id, multiple_capture_count: storage_model.multiple_capture_count, connector_response_reference_id: storage_model.connector_response_reference_id, updated_by: storage_model.updated_by, redirection_data: storage_model.redirection_data.map(From::from), encoded_data: storage_model.encoded_data, merchant_connector_id: storage_model.merchant_connector_id, external_three_ds_authentication_attempted: storage_model .external_three_ds_authentication_attempted, authentication_connector: storage_model.authentication_connector, authentication_id: storage_model.authentication_id, fingerprint_id: storage_model.fingerprint_id, charges: storage_model.charges, client_source: storage_model.client_source, client_version: storage_model.client_version, customer_acceptance: storage_model.customer_acceptance, profile_id: storage_model.profile_id, organization_id: storage_model.organization_id, payment_method_subtype: storage_model.payment_method_subtype, authentication_applied: storage_model.authentication_applied, external_reference_id: storage_model.external_reference_id, connector: storage_model.connector, payment_method_billing_address, connector_token_details: storage_model.connector_token_details, card_discovery: storage_model.card_discovery, feature_metadata: storage_model.feature_metadata.map(From::from), processor_merchant_id: storage_model .processor_merchant_id .unwrap_or(storage_model.merchant_id), created_by: storage_model .created_by .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), connector_request_reference_id: storage_model.connector_request_reference_id, network_transaction_id: storage_model.network_transaction_id, authorized_amount: storage_model.authorized_amount, }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting payment attempt".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { use common_utils::encryption::Encryption; let Self { payment_id, merchant_id, attempts_group_id, status, error, amount_details, authentication_type, created_at, modified_at, last_synced, cancellation_reason, browser_info, payment_token, connector_metadata, payment_experience, payment_method_data, routing_result: _, preprocessing_step_id, multiple_capture_count, connector_response_reference_id, updated_by, redirection_data, encoded_data, merchant_connector_id, external_three_ds_authentication_attempted, authentication_connector, authentication_id, fingerprint_id, client_source, client_version, customer_acceptance, profile_id, organization_id, payment_method_type, connector_payment_id, payment_method_subtype, authentication_applied: _, external_reference_id: _, id, payment_method_id, payment_method_billing_address, connector, connector_token_details, card_discovery, charges, feature_metadata, processor_merchant_id, created_by, connector_request_reference_id, network_transaction_id, authorized_amount, } = self; let card_network = payment_method_data .as_ref() .and_then(|data| data.peek().as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()); let error_details = error; Ok(DieselPaymentAttemptNew { payment_id, merchant_id, status, network_transaction_id, error_message: error_details .as_ref() .map(|details| details.message.clone()), surcharge_amount: amount_details.surcharge_amount, tax_on_surcharge: amount_details.tax_on_surcharge, payment_method_id, authentication_type, created_at, modified_at, last_synced, cancellation_reason, browser_info, payment_token, error_code: error_details.as_ref().map(|details| details.code.clone()), connector_metadata, payment_experience, payment_method_data, preprocessing_step_id, error_reason: error_details .as_ref() .and_then(|details| details.reason.clone()), connector_response_reference_id, multiple_capture_count, amount_capturable: amount_details.amount_capturable, updated_by, merchant_connector_id, redirection_data: redirection_data.map(From::from), encoded_data, unified_code: error_details .as_ref() .and_then(|details| details.unified_code.clone()), unified_message: error_details .as_ref() .and_then(|details| details.unified_message.clone()), net_amount: amount_details.net_amount, external_three_ds_authentication_attempted, authentication_connector, authentication_id, fingerprint_id, client_source, client_version, customer_acceptance, profile_id, organization_id, card_network, order_tax_amount: amount_details.order_tax_amount, shipping_cost: amount_details.shipping_cost, amount_to_capture: amount_details.amount_to_capture, payment_method_billing_address: payment_method_billing_address.map(Encryption::from), payment_method_subtype, connector_payment_id: connector_payment_id .as_ref() .map(|txn_id| ConnectorTransactionId::TxnId(txn_id.clone())), payment_method_type_v2: payment_method_type, id, charges, connector_token_details, card_discovery, extended_authorization_applied: None, request_extended_authorization: None, capture_before: None, feature_metadata: feature_metadata.as_ref().map(From::from), connector, network_advice_code: error_details .as_ref() .and_then(|details| details.network_advice_code.clone()), network_decline_code: error_details .as_ref() .and_then(|details| details.network_decline_code.clone()), network_error_message: error_details .as_ref() .and_then(|details| details.network_error_message.clone()), processor_merchant_id: Some(processor_merchant_id), created_by: created_by.map(|cb| cb.to_string()), connector_request_reference_id, network_details: None, attempts_group_id, is_stored_credential: None, authorized_amount, }) } } #[cfg(feature = "v2")] impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal { fn from(update: PaymentAttemptUpdate) -> Self { match update { PaymentAttemptUpdate::ConfirmIntent { status, updated_by, connector, merchant_connector_id, authentication_type, connector_request_reference_id, connector_response_reference_id, } => Self { status: Some(status), payment_method_id: None, error_message: None, modified_at: common_utils::date_time::now(), browser_info: None, error_code: None, error_reason: None, updated_by, merchant_connector_id, unified_code: None, unified_message: None, connector_payment_id: None, connector_payment_data: None, connector: Some(connector), redirection_data: None, connector_metadata: None, amount_capturable: None, amount_to_capture: None, connector_token_details: None, authentication_type: Some(authentication_type), feature_metadata: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_request_reference_id, connector_response_reference_id, cancellation_reason: None, }, PaymentAttemptUpdate::ErrorUpdate { status, error, connector_payment_id, amount_capturable, updated_by, } => { // Apply automatic hashing for long connector payment IDs let (connector_payment_id, connector_payment_data) = connector_payment_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { status: Some(status), payment_method_id: None, error_message: Some(error.message), error_code: Some(error.code), modified_at: common_utils::date_time::now(), browser_info: None, error_reason: error.reason, updated_by, merchant_connector_id: None, unified_code: None, unified_message: None, connector_payment_id, connector_payment_data, connector: None, redirection_data: None, connector_metadata: None, amount_capturable, amount_to_capture: None, connector_token_details: None, authentication_type: None, feature_metadata: None, network_advice_code: error.network_advice_code, network_decline_code: error.network_decline_code, network_error_message: error.network_error_message, connector_request_reference_id: None, connector_response_reference_id: None, cancellation_reason: None, } } PaymentAttemptUpdate::ConfirmIntentResponse(confirm_intent_response_update) => { let ConfirmIntentResponseUpdate { status, connector_payment_id, updated_by, redirection_data, connector_metadata, amount_capturable, connector_token_details, connector_response_reference_id, } = *confirm_intent_response_update; // Apply automatic hashing for long connector payment IDs let (connector_payment_id, connector_payment_data) = connector_payment_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { status: Some(status), payment_method_id: None, amount_capturable, error_message: None, error_code: None, modified_at: common_utils::date_time::now(), browser_info: None, error_reason: None, updated_by, merchant_connector_id: None, unified_code: None, unified_message: None, connector_payment_id, connector_payment_data, connector: None, redirection_data: redirection_data .map(diesel_models::payment_attempt::RedirectForm::from), connector_metadata, amount_to_capture: None, connector_token_details, authentication_type: None, feature_metadata: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_request_reference_id: None, connector_response_reference_id, cancellation_reason: None, } } PaymentAttemptUpdate::SyncUpdate { status, amount_capturable, updated_by, } => Self { status: Some(status), payment_method_id: None, amount_capturable, error_message: None, error_code: None, modified_at: common_utils::date_time::now(), browser_info: None, error_reason: None, updated_by, merchant_connector_id: None, unified_code: None, unified_message: None, connector_payment_id: None, connector_payment_data: None, connector: None, redirection_data: None, connector_metadata: None, amount_to_capture: None, connector_token_details: None, authentication_type: None, feature_metadata: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, cancellation_reason: None, }, PaymentAttemptUpdate::CaptureUpdate { status, amount_capturable, updated_by, } => Self { status: Some(status), payment_method_id: None, amount_capturable, amount_to_capture: None, error_message: None, error_code: None, modified_at: common_utils::date_time::now(), browser_info: None, error_reason: None, updated_by, merchant_connector_id: None, unified_code: None, unified_message: None, connector_payment_id: None, connector_payment_data: None, connector: None, redirection_data: None, connector_metadata: None, connector_token_details: None, authentication_type: None, feature_metadata: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, cancellation_reason: None, }, PaymentAttemptUpdate::PreCaptureUpdate { amount_to_capture, updated_by, } => Self { amount_to_capture, payment_method_id: None, error_message: None, modified_at: common_utils::date_time::now(), browser_info: None, error_code: None, error_reason: None, updated_by, merchant_connector_id: None, unified_code: None, unified_message: None, connector_payment_id: None, connector_payment_data: None, connector: None, redirection_data: None, status: None, connector_metadata: None, amount_capturable: None, connector_token_details: None, authentication_type: None, feature_metadata: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, cancellation_reason: None, }, PaymentAttemptUpdate::ConfirmIntentTokenized { status, updated_by, connector, merchant_connector_id, authentication_type, payment_method_id, connector_request_reference_id, } => Self { status: Some(status), payment_method_id: Some(payment_method_id), error_message: None, modified_at: common_utils::date_time::now(), browser_info: None, error_code: None, error_reason: None, updated_by, merchant_connector_id: Some(merchant_connector_id), unified_code: None, unified_message: None, connector_payment_id: None, connector_payment_data: None, connector: Some(connector), redirection_data: None, connector_metadata: None, amount_capturable: None, amount_to_capture: None, connector_token_details: None, authentication_type: Some(authentication_type), feature_metadata: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_request_reference_id, connector_response_reference_id: None, cancellation_reason: None, }, PaymentAttemptUpdate::VoidUpdate { status, cancellation_reason, updated_by, } => Self { status: Some(status), cancellation_reason, error_message: None, error_code: None, modified_at: common_utils::date_time::now(), browser_info: None, error_reason: None, updated_by, merchant_connector_id: None, unified_code: None, unified_message: None, connector_payment_id: None, connector_payment_data: None, connector: None, redirection_data: None, connector_metadata: None, amount_capturable: None, amount_to_capture: None, connector_token_details: None, authentication_type: None, feature_metadata: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, payment_method_id: None, }, } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, PartialEq)] pub struct PaymentAttemptFeatureMetadata { pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, PartialEq)] pub struct PaymentAttemptRevenueRecoveryData { pub attempt_triggered_by: common_enums::TriggeredBy, // stripe specific field used to identify duplicate attempts. pub charge_id: Option<String>, } #[cfg(feature = "v2")] impl From<&PaymentAttemptFeatureMetadata> for DieselPaymentAttemptFeatureMetadata { fn from(item: &PaymentAttemptFeatureMetadata) -> Self { let revenue_recovery = item.revenue_recovery .as_ref() .map(|recovery_data| DieselPassiveChurnRecoveryData { attempt_triggered_by: recovery_data.attempt_triggered_by, charge_id: recovery_data.charge_id.clone(), }); Self { revenue_recovery } } } #[cfg(feature = "v2")] impl From<DieselPaymentAttemptFeatureMetadata> for PaymentAttemptFeatureMetadata { fn from(item: DieselPaymentAttemptFeatureMetadata) -> Self { let revenue_recovery = item.revenue_recovery .map(|recovery_data| PaymentAttemptRevenueRecoveryData { attempt_triggered_by: recovery_data.attempt_triggered_by, charge_id: recovery_data.charge_id, }); Self { revenue_recovery } } }
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
hyperswitch_domain_models::src::payments::payment_attempt
25,167
true
// File: crates/hyperswitch_domain_models/src/payments/payment_intent.rs // Module: hyperswitch_domain_models::src::payments::payment_intent use common_types::primitive_wrappers; #[cfg(feature = "v1")] use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V2; #[cfg(feature = "v2")] use common_utils::errors::ParsingError; #[cfg(feature = "v2")] use common_utils::ext_traits::{Encode, ValueExt}; use common_utils::{ consts::PAYMENTS_LIST_MAX_LIMIT_V1, crypto::Encryptable, encryption::Encryption, errors::{CustomResult, ValidationError}, id_type, pii::{self, Email}, type_name, types::{ keymanager::{self, KeyManagerState, ToEncryptable}, CreatedBy, MinorUnit, }, }; use diesel_models::{ PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew, }; use error_stack::ResultExt; #[cfg(feature = "v2")] use masking::ExposeInterface; use masking::{Deserialize, PeekInterface, Secret}; use serde::Serialize; use time::PrimitiveDateTime; #[cfg(all(feature = "v1", feature = "olap"))] use super::payment_attempt::PaymentAttempt; use super::PaymentIntent; #[cfg(feature = "v2")] use crate::address::Address; #[cfg(feature = "v2")] use crate::routing; use crate::{ behaviour, merchant_key_store::MerchantKeyStore, type_encryption::{crypto_operation, CryptoOperation}, }; #[cfg(feature = "v1")] use crate::{errors, RemoteStorageObject}; #[async_trait::async_trait] pub trait PaymentIntentInterface { type Error; async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, Self::Error>; async fn insert_payment_intent( &self, state: &KeyManagerState, new: PaymentIntent, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::PaymentReferenceId, profile_id: &id_type::ProfileId, merchant_key_store: &MerchantKeyStore, storage_scheme: &common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_intent_by_id( &self, state: &KeyManagerState, id: &id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, Self::Error>; #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intent_by_constraints( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, Self::Error>; #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intents_by_time_range_constraints( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, time_range: &common_utils::types::TimeRange, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, Self::Error>; #[cfg(feature = "olap")] async fn get_intent_status_with_count( &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, Self::Error>; #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, Self::Error>; #[cfg(all(feature = "v2", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result< Vec<( PaymentIntent, Option<super::payment_attempt::PaymentAttempt>, )>, Self::Error, >; #[cfg(all(feature = "v2", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<Option<String>>, Self::Error>; #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<String>, Self::Error>; } #[derive(Clone, Debug, PartialEq, router_derive::DebugAsDisplay, Serialize, Deserialize)] pub struct CustomerData { pub name: Option<Secret<String>>, pub email: Option<Email>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize)] pub struct PaymentIntentUpdateFields { pub amount: Option<MinorUnit>, pub currency: Option<common_enums::Currency>, pub shipping_cost: Option<MinorUnit>, pub tax_details: Option<diesel_models::TaxDetails>, pub skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, pub skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub routing_algorithm_id: Option<id_type::RoutingId>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub billing_address: Option<Encryptable<Address>>, pub shipping_address: Option<Encryptable<Address>>, pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub setup_future_usage: Option<common_enums::FutureUsage>, pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub order_details: Option<Vec<Secret<diesel_models::types::OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<diesel_models::types::FeatureMetadata>, pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>, pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, pub session_expiry: Option<PrimitiveDateTime>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, pub active_attempt_id: Option<Option<id_type::GlobalAttemptId>>, // updated_by is set internally, field not present in request pub updated_by: String, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, pub currency: common_enums::Currency, pub setup_future_usage: Option<common_enums::FutureUsage>, pub status: common_enums::IntentStatus, pub customer_id: Option<id_type::CustomerId>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub return_url: Option<String>, pub business_country: Option<common_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<serde_json::Value>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub payment_confirm_source: Option<common_enums::PaymentSource>, pub updated_by: String, pub fingerprint_id: Option<String>, pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<diesel_models::TaxDetails>, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub is_confirm_operation: bool, pub payment_channel: Option<common_enums::PaymentChannel>, pub feature_metadata: Option<Secret<serde_json::Value>>, pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize)] pub enum PaymentIntentUpdate { ResponseUpdate { status: common_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, fingerprint_id: Option<String>, incremental_authorization_allowed: Option<bool>, feature_metadata: Option<Secret<serde_json::Value>>, }, MetadataUpdate { metadata: serde_json::Value, updated_by: String, }, Update(Box<PaymentIntentUpdateFields>), PaymentCreateUpdate { return_url: Option<String>, status: Option<common_enums::IntentStatus>, customer_id: Option<id_type::CustomerId>, shipping_address_id: Option<String>, billing_address_id: Option<String>, customer_details: Option<Encryptable<Secret<serde_json::Value>>>, updated_by: String, }, MerchantStatusUpdate { status: common_enums::IntentStatus, shipping_address_id: Option<String>, billing_address_id: Option<String>, updated_by: String, }, PGStatusUpdate { status: common_enums::IntentStatus, incremental_authorization_allowed: Option<bool>, updated_by: String, feature_metadata: Option<Secret<serde_json::Value>>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, attempt_count: i16, updated_by: String, }, StatusAndAttemptUpdate { status: common_enums::IntentStatus, active_attempt_id: String, attempt_count: i16, updated_by: String, }, ApproveUpdate { status: common_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, RejectUpdate { status: common_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, SurchargeApplicableUpdate { surcharge_applicable: bool, updated_by: String, }, IncrementalAuthorizationAmountUpdate { amount: MinorUnit, }, AuthorizationCountUpdate { authorization_count: i32, }, CompleteAuthorizeUpdate { shipping_address_id: Option<String>, }, ManualUpdate { status: Option<common_enums::IntentStatus>, updated_by: String, }, SessionResponseUpdate { tax_details: diesel_models::TaxDetails, shipping_address_id: Option<String>, updated_by: String, shipping_details: Option<Encryptable<Secret<serde_json::Value>>>, }, } #[cfg(feature = "v1")] impl PaymentIntentUpdate { pub fn is_confirm_operation(&self) -> bool { match self { Self::Update(value) => value.is_confirm_operation, _ => false, } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize)] pub enum PaymentIntentUpdate { /// PreUpdate tracker of ConfirmIntent ConfirmIntent { status: common_enums::IntentStatus, active_attempt_id: Option<id_type::GlobalAttemptId>, updated_by: String, }, /// PostUpdate tracker of ConfirmIntent ConfirmIntentPostUpdate { status: common_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, feature_metadata: Option<Box<diesel_models::types::FeatureMetadata>>, }, /// SyncUpdate of ConfirmIntent in PostUpdateTrackers SyncUpdate { status: common_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, }, CaptureUpdate { status: common_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, }, /// Update the payment intent details on payment sdk session call, before calling the connector. SessionIntentUpdate { prerouting_algorithm: routing::PaymentRoutingInfo, updated_by: String, }, RecordUpdate { status: common_enums::IntentStatus, feature_metadata: Box<Option<diesel_models::types::FeatureMetadata>>, updated_by: String, active_attempt_id: Option<id_type::GlobalAttemptId>, }, /// UpdateIntent UpdateIntent(Box<PaymentIntentUpdateFields>), /// VoidUpdate for payment cancellation VoidUpdate { status: common_enums::IntentStatus, updated_by: String, }, } #[cfg(feature = "v2")] impl PaymentIntentUpdate { pub fn is_confirm_operation(&self) -> bool { matches!(self, Self::ConfirmIntent { .. }) } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Default)] pub struct PaymentIntentUpdateInternal { pub amount: Option<MinorUnit>, pub currency: Option<common_enums::Currency>, pub status: Option<common_enums::IntentStatus>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<id_type::CustomerId>, pub return_url: Option<String>, pub setup_future_usage: Option<common_enums::FutureUsage>, pub off_session: Option<bool>, pub metadata: Option<serde_json::Value>, pub billing_address_id: Option<String>, pub shipping_address_id: Option<String>, pub modified_at: Option<PrimitiveDateTime>, pub active_attempt_id: Option<String>, pub business_country: Option<common_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub attempt_count: Option<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>, pub payment_confirm_source: Option<common_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub fingerprint_id: Option<String>, pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<diesel_models::TaxDetails>, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub feature_metadata: Option<Secret<serde_json::Value>>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>, } // This conversion is used in the `update_payment_intent` function #[cfg(feature = "v2")] impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal { type Error = error_stack::Report<ParsingError>; fn try_from(payment_intent_update: PaymentIntentUpdate) -> Result<Self, Self::Error> { match payment_intent_update { PaymentIntentUpdate::ConfirmIntent { status, active_attempt_id, updated_by, } => Ok(Self { status: Some(status), active_attempt_id: Some(active_attempt_id), prerouting_algorithm: None, modified_at: common_utils::date_time::now(), amount: None, amount_captured: None, currency: None, shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, surcharge_applicable: None, surcharge_amount: None, tax_on_surcharge: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing_address: None, shipping_address: 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, feature_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, updated_by, force_3ds_challenge: None, is_iframe_redirection_enabled: None, enable_partial_authorization: None, }), PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by, amount_captured, feature_metadata, } => Ok(Self { status: Some(status), active_attempt_id: None, prerouting_algorithm: None, modified_at: common_utils::date_time::now(), amount_captured, amount: None, currency: None, shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, surcharge_applicable: None, surcharge_amount: None, tax_on_surcharge: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing_address: None, shipping_address: 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, feature_metadata: feature_metadata.map(|val| *val), payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, updated_by, force_3ds_challenge: None, is_iframe_redirection_enabled: None, enable_partial_authorization: None, }), PaymentIntentUpdate::SyncUpdate { status, amount_captured, updated_by, } => Ok(Self { status: Some(status), active_attempt_id: None, prerouting_algorithm: None, modified_at: common_utils::date_time::now(), amount: None, currency: None, amount_captured, shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, surcharge_applicable: None, surcharge_amount: None, tax_on_surcharge: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing_address: None, shipping_address: 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, feature_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, updated_by, force_3ds_challenge: None, is_iframe_redirection_enabled: None, enable_partial_authorization: None, }), PaymentIntentUpdate::CaptureUpdate { status, amount_captured, updated_by, } => Ok(Self { status: Some(status), amount_captured, active_attempt_id: None, prerouting_algorithm: None, modified_at: common_utils::date_time::now(), amount: None, currency: None, shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, surcharge_applicable: None, surcharge_amount: None, tax_on_surcharge: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing_address: None, shipping_address: 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, feature_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, updated_by, force_3ds_challenge: None, is_iframe_redirection_enabled: None, enable_partial_authorization: None, }), PaymentIntentUpdate::SessionIntentUpdate { prerouting_algorithm, updated_by, } => Ok(Self { status: None, active_attempt_id: None, modified_at: common_utils::date_time::now(), amount_captured: None, prerouting_algorithm: Some( prerouting_algorithm .encode_to_value() .attach_printable("Failed to Serialize prerouting_algorithm")?, ), amount: None, currency: None, shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, surcharge_applicable: None, surcharge_amount: None, tax_on_surcharge: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing_address: None, shipping_address: 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, feature_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, updated_by, force_3ds_challenge: None, is_iframe_redirection_enabled: None, enable_partial_authorization: None, }), PaymentIntentUpdate::UpdateIntent(boxed_intent) => { let PaymentIntentUpdateFields { amount, currency, shipping_cost, tax_details, skip_external_tax_calculation, skip_surcharge_calculation, surcharge_amount, tax_on_surcharge, routing_algorithm_id, capture_method, authentication_type, billing_address, shipping_address, customer_present, description, return_url, setup_future_usage, apply_mit_exemption, statement_descriptor, order_details, allowed_payment_method_types, metadata, connector_metadata, feature_metadata, payment_link_config, request_incremental_authorization, session_expiry, frm_metadata, request_external_three_ds_authentication, active_attempt_id, updated_by, force_3ds_challenge, is_iframe_redirection_enabled, enable_partial_authorization, } = *boxed_intent; Ok(Self { status: None, active_attempt_id, prerouting_algorithm: None, modified_at: common_utils::date_time::now(), amount_captured: None, amount, currency, shipping_cost, tax_details, skip_external_tax_calculation: skip_external_tax_calculation .map(|val| val.as_bool()), surcharge_applicable: skip_surcharge_calculation.map(|val| val.as_bool()), surcharge_amount, tax_on_surcharge, routing_algorithm_id, capture_method, authentication_type, billing_address: billing_address.map(Encryption::from), shipping_address: shipping_address.map(Encryption::from), customer_present: customer_present.map(|val| val.as_bool()), description, return_url, setup_future_usage, apply_mit_exemption: apply_mit_exemption.map(|val| val.as_bool()), statement_descriptor, order_details, allowed_payment_method_types: allowed_payment_method_types .map(|allowed_payment_method_types| { allowed_payment_method_types.encode_to_value() }) .and_then(|r| r.ok().map(Secret::new)), metadata, connector_metadata, feature_metadata, payment_link_config, request_incremental_authorization, session_expiry, frm_metadata, request_external_three_ds_authentication: request_external_three_ds_authentication.map(|val| val.as_bool()), updated_by, force_3ds_challenge, is_iframe_redirection_enabled, enable_partial_authorization, }) } PaymentIntentUpdate::RecordUpdate { status, feature_metadata, updated_by, active_attempt_id, } => Ok(Self { status: Some(status), amount_captured: None, active_attempt_id: Some(active_attempt_id), modified_at: common_utils::date_time::now(), amount: None, currency: None, shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, surcharge_applicable: None, surcharge_amount: None, tax_on_surcharge: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing_address: None, shipping_address: 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, feature_metadata: *feature_metadata, payment_link_config: None, request_incremental_authorization: None, prerouting_algorithm: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, updated_by, force_3ds_challenge: None, is_iframe_redirection_enabled: None, enable_partial_authorization: None, }), PaymentIntentUpdate::VoidUpdate { status, updated_by } => Ok(Self { status: Some(status), amount_captured: None, active_attempt_id: None, prerouting_algorithm: None, modified_at: common_utils::date_time::now(), amount: None, currency: None, shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, surcharge_applicable: None, surcharge_amount: None, tax_on_surcharge: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing_address: None, shipping_address: 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, feature_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, updated_by, force_3ds_challenge: None, is_iframe_redirection_enabled: None, enable_partial_authorization: None, }), } } } #[cfg(feature = "v1")] impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fn from(payment_intent_update: PaymentIntentUpdate) -> Self { match payment_intent_update { PaymentIntentUpdate::MetadataUpdate { metadata, updated_by, } => Self { metadata: Some(metadata), modified_at: Some(common_utils::date_time::now()), updated_by, ..Default::default() }, PaymentIntentUpdate::Update(value) => Self { amount: Some(value.amount), currency: Some(value.currency), setup_future_usage: value.setup_future_usage, status: Some(value.status), customer_id: value.customer_id, shipping_address_id: value.shipping_address_id, billing_address_id: value.billing_address_id, return_url: value.return_url, business_country: value.business_country, business_label: value.business_label, description: value.description, statement_descriptor_name: value.statement_descriptor_name, statement_descriptor_suffix: value.statement_descriptor_suffix, order_details: value.order_details, metadata: value.metadata, payment_confirm_source: value.payment_confirm_source, updated_by: value.updated_by, session_expiry: value.session_expiry, fingerprint_id: value.fingerprint_id, request_external_three_ds_authentication: value .request_external_three_ds_authentication, frm_metadata: value.frm_metadata, customer_details: value.customer_details, billing_details: value.billing_details, merchant_order_reference_id: value.merchant_order_reference_id, shipping_details: value.shipping_details, is_payment_processor_token_flow: value.is_payment_processor_token_flow, tax_details: value.tax_details, tax_status: value.tax_status, discount_amount: value.discount_amount, order_date: value.order_date, shipping_amount_tax: value.shipping_amount_tax, duty_amount: value.duty_amount, ..Default::default() }, PaymentIntentUpdate::PaymentCreateUpdate { return_url, status, customer_id, shipping_address_id, billing_address_id, customer_details, updated_by, } => Self { return_url, status, customer_id, shipping_address_id, billing_address_id, customer_details, modified_at: Some(common_utils::date_time::now()), updated_by, ..Default::default() }, PaymentIntentUpdate::PGStatusUpdate { status, updated_by, incremental_authorization_allowed, feature_metadata, } => Self { status: Some(status), modified_at: Some(common_utils::date_time::now()), updated_by, incremental_authorization_allowed, feature_metadata, ..Default::default() }, PaymentIntentUpdate::MerchantStatusUpdate { status, shipping_address_id, billing_address_id, updated_by, } => Self { status: Some(status), shipping_address_id, billing_address_id, modified_at: Some(common_utils::date_time::now()), updated_by, ..Default::default() }, PaymentIntentUpdate::ResponseUpdate { // amount, // currency, status, amount_captured, fingerprint_id, // customer_id, updated_by, incremental_authorization_allowed, feature_metadata, } => Self { // amount, // currency: Some(currency), status: Some(status), amount_captured, fingerprint_id, // customer_id, modified_at: Some(common_utils::date_time::now()), updated_by, incremental_authorization_allowed, feature_metadata, ..Default::default() }, PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id, attempt_count, updated_by, } => Self { active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, ..Default::default() }, PaymentIntentUpdate::StatusAndAttemptUpdate { status, active_attempt_id, attempt_count, updated_by, } => Self { status: Some(status), active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, ..Default::default() }, PaymentIntentUpdate::ApproveUpdate { status, merchant_decision, updated_by, } => Self { status: Some(status), merchant_decision, updated_by, ..Default::default() }, PaymentIntentUpdate::RejectUpdate { status, merchant_decision, updated_by, } => Self { status: Some(status), merchant_decision, updated_by, ..Default::default() }, PaymentIntentUpdate::SurchargeApplicableUpdate { surcharge_applicable, updated_by, } => Self { surcharge_applicable: Some(surcharge_applicable), updated_by, ..Default::default() }, PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => Self { amount: Some(amount), ..Default::default() }, PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count, } => Self { authorization_count: Some(authorization_count), ..Default::default() }, PaymentIntentUpdate::CompleteAuthorizeUpdate { shipping_address_id, } => Self { shipping_address_id, ..Default::default() }, PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self { status, modified_at: Some(common_utils::date_time::now()), updated_by, ..Default::default() }, PaymentIntentUpdate::SessionResponseUpdate { tax_details, shipping_address_id, updated_by, shipping_details, } => Self { tax_details: Some(tax_details), shipping_address_id, updated_by, shipping_details, ..Default::default() }, } } } #[cfg(feature = "v1")] use diesel_models::{ PaymentIntentUpdate as DieselPaymentIntentUpdate, PaymentIntentUpdateFields as DieselPaymentIntentUpdateFields, }; // TODO: check where this conversion is used // #[cfg(feature = "v2")] // impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { // fn from(value: PaymentIntentUpdate) -> Self { // match value { // PaymentIntentUpdate::ConfirmIntent { status, updated_by } => { // Self::ConfirmIntent { status, updated_by } // } // PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => { // Self::ConfirmIntentPostUpdate { status, updated_by } // } // } // } // } #[cfg(feature = "v1")] impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { fn from(value: PaymentIntentUpdate) -> Self { match value { PaymentIntentUpdate::ResponseUpdate { status, amount_captured, fingerprint_id, updated_by, incremental_authorization_allowed, feature_metadata, } => Self::ResponseUpdate { status, amount_captured, fingerprint_id, updated_by, incremental_authorization_allowed, feature_metadata, }, PaymentIntentUpdate::MetadataUpdate { metadata, updated_by, } => Self::MetadataUpdate { metadata, updated_by, }, PaymentIntentUpdate::Update(value) => { Self::Update(Box::new(DieselPaymentIntentUpdateFields { amount: value.amount, currency: value.currency, setup_future_usage: value.setup_future_usage, status: value.status, customer_id: value.customer_id, shipping_address_id: value.shipping_address_id, billing_address_id: value.billing_address_id, return_url: value.return_url, business_country: value.business_country, business_label: value.business_label, description: value.description, statement_descriptor_name: value.statement_descriptor_name, statement_descriptor_suffix: value.statement_descriptor_suffix, order_details: value.order_details, metadata: value.metadata, payment_confirm_source: value.payment_confirm_source, updated_by: value.updated_by, session_expiry: value.session_expiry, fingerprint_id: value.fingerprint_id, request_external_three_ds_authentication: value .request_external_three_ds_authentication, frm_metadata: value.frm_metadata, customer_details: value.customer_details.map(Encryption::from), billing_details: value.billing_details.map(Encryption::from), merchant_order_reference_id: value.merchant_order_reference_id, shipping_details: value.shipping_details.map(Encryption::from), is_payment_processor_token_flow: value.is_payment_processor_token_flow, tax_details: value.tax_details, force_3ds_challenge: value.force_3ds_challenge, is_iframe_redirection_enabled: value.is_iframe_redirection_enabled, payment_channel: value.payment_channel, feature_metadata: value.feature_metadata, tax_status: value.tax_status, discount_amount: value.discount_amount, order_date: value.order_date, shipping_amount_tax: value.shipping_amount_tax, duty_amount: value.duty_amount, enable_partial_authorization: value.enable_partial_authorization, enable_overcapture: value.enable_overcapture, })) } PaymentIntentUpdate::PaymentCreateUpdate { return_url, status, customer_id, shipping_address_id, billing_address_id, customer_details, updated_by, } => Self::PaymentCreateUpdate { return_url, status, customer_id, shipping_address_id, billing_address_id, customer_details: customer_details.map(Encryption::from), updated_by, }, PaymentIntentUpdate::MerchantStatusUpdate { status, shipping_address_id, billing_address_id, updated_by, } => Self::MerchantStatusUpdate { status, shipping_address_id, billing_address_id, updated_by, }, PaymentIntentUpdate::PGStatusUpdate { status, updated_by, incremental_authorization_allowed, feature_metadata, } => Self::PGStatusUpdate { status, updated_by, incremental_authorization_allowed, feature_metadata, }, PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id, attempt_count, updated_by, } => Self::PaymentAttemptAndAttemptCountUpdate { active_attempt_id, attempt_count, updated_by, }, PaymentIntentUpdate::StatusAndAttemptUpdate { status, active_attempt_id, attempt_count, updated_by, } => Self::StatusAndAttemptUpdate { status, active_attempt_id, attempt_count, updated_by, }, PaymentIntentUpdate::ApproveUpdate { status, merchant_decision, updated_by, } => Self::ApproveUpdate { status, merchant_decision, updated_by, }, PaymentIntentUpdate::RejectUpdate { status, merchant_decision, updated_by, } => Self::RejectUpdate { status, merchant_decision, updated_by, }, PaymentIntentUpdate::SurchargeApplicableUpdate { surcharge_applicable, updated_by, } => Self::SurchargeApplicableUpdate { surcharge_applicable: Some(surcharge_applicable), updated_by, }, PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => { Self::IncrementalAuthorizationAmountUpdate { amount } } PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count, } => Self::AuthorizationCountUpdate { authorization_count, }, PaymentIntentUpdate::CompleteAuthorizeUpdate { shipping_address_id, } => Self::CompleteAuthorizeUpdate { shipping_address_id, }, PaymentIntentUpdate::ManualUpdate { status, updated_by } => { Self::ManualUpdate { status, updated_by } } PaymentIntentUpdate::SessionResponseUpdate { tax_details, shipping_address_id, updated_by, shipping_details, } => Self::SessionResponseUpdate { tax_details, shipping_address_id, updated_by, shipping_details: shipping_details.map(Encryption::from), }, } } } #[cfg(feature = "v1")] impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInternal { fn from(value: PaymentIntentUpdateInternal) -> Self { let modified_at = common_utils::date_time::now(); let PaymentIntentUpdateInternal { amount, currency, status, amount_captured, customer_id, return_url, setup_future_usage, off_session, metadata, billing_address_id, shipping_address_id, modified_at: _, active_attempt_id, business_country, business_label, description, statement_descriptor_name, statement_descriptor_suffix, order_details, attempt_count, merchant_decision, payment_confirm_source, updated_by, surcharge_applicable, incremental_authorization_allowed, authorization_count, session_expiry, fingerprint_id, request_external_three_ds_authentication, frm_metadata, customer_details, billing_details, merchant_order_reference_id, shipping_details, is_payment_processor_token_flow, tax_details, force_3ds_challenge, is_iframe_redirection_enabled, payment_channel, feature_metadata, tax_status, discount_amount, order_date, shipping_amount_tax, duty_amount, enable_partial_authorization, enable_overcapture, } = value; Self { amount, currency, status, amount_captured, customer_id, return_url: None, // deprecated setup_future_usage, off_session, metadata, billing_address_id, shipping_address_id, modified_at, active_attempt_id, business_country, business_label, description, statement_descriptor_name, statement_descriptor_suffix, order_details, attempt_count, merchant_decision, payment_confirm_source, updated_by, surcharge_applicable, incremental_authorization_allowed, authorization_count, session_expiry, fingerprint_id, request_external_three_ds_authentication, frm_metadata, customer_details: customer_details.map(Encryption::from), billing_details: billing_details.map(Encryption::from), merchant_order_reference_id, shipping_details: shipping_details.map(Encryption::from), is_payment_processor_token_flow, tax_details, force_3ds_challenge, is_iframe_redirection_enabled, extended_return_url: return_url, payment_channel, feature_metadata, tax_status, discount_amount, order_date, shipping_amount_tax, duty_amount, enable_partial_authorization, enable_overcapture, } } } #[cfg(feature = "v1")] pub enum PaymentIntentFetchConstraints { Single { payment_intent_id: id_type::PaymentId, }, List(Box<PaymentIntentListParams>), } #[cfg(feature = "v1")] impl PaymentIntentFetchConstraints { pub fn get_profile_id_list(&self) -> Option<Vec<id_type::ProfileId>> { if let Self::List(pi_list_params) = self { pi_list_params.profile_id.clone() } else { None } } } #[cfg(feature = "v2")] pub enum PaymentIntentFetchConstraints { List(Box<PaymentIntentListParams>), } #[cfg(feature = "v2")] impl PaymentIntentFetchConstraints { pub fn get_profile_id(&self) -> Option<id_type::ProfileId> { let Self::List(pi_list_params) = self; pi_list_params.profile_id.clone() } } #[cfg(feature = "v1")] pub struct PaymentIntentListParams { pub offset: u32, pub starting_at: Option<PrimitiveDateTime>, pub ending_at: Option<PrimitiveDateTime>, pub amount_filter: Option<api_models::payments::AmountFilter>, pub connector: Option<Vec<api_models::enums::Connector>>, pub currency: Option<Vec<common_enums::Currency>>, pub status: Option<Vec<common_enums::IntentStatus>>, pub payment_method: Option<Vec<common_enums::PaymentMethod>>, pub payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, pub authentication_type: Option<Vec<common_enums::AuthenticationType>>, pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, pub profile_id: Option<Vec<id_type::ProfileId>>, pub customer_id: Option<id_type::CustomerId>, pub starting_after_id: Option<id_type::PaymentId>, pub ending_before_id: Option<id_type::PaymentId>, pub limit: Option<u32>, pub order: api_models::payments::Order, pub card_network: Option<Vec<common_enums::CardNetwork>>, pub card_discovery: Option<Vec<common_enums::CardDiscovery>>, pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] pub struct PaymentIntentListParams { pub offset: u32, pub starting_at: Option<PrimitiveDateTime>, pub ending_at: Option<PrimitiveDateTime>, pub amount_filter: Option<api_models::payments::AmountFilter>, pub connector: Option<Vec<api_models::enums::Connector>>, pub currency: Option<Vec<common_enums::Currency>>, pub status: Option<Vec<common_enums::IntentStatus>>, pub payment_method_type: Option<Vec<common_enums::PaymentMethod>>, pub payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>, pub authentication_type: Option<Vec<common_enums::AuthenticationType>>, pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, pub profile_id: Option<id_type::ProfileId>, pub customer_id: Option<id_type::GlobalCustomerId>, pub starting_after_id: Option<id_type::GlobalPaymentId>, pub ending_before_id: Option<id_type::GlobalPaymentId>, pub limit: Option<u32>, pub order: api_models::payments::Order, pub card_network: Option<Vec<common_enums::CardNetwork>>, pub merchant_order_reference_id: Option<String>, pub payment_id: Option<id_type::GlobalPaymentId>, } #[cfg(feature = "v1")] impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchConstraints { fn from(value: api_models::payments::PaymentListConstraints) -> Self { let api_models::payments::PaymentListConstraints { customer_id, starting_after, ending_before, limit, created, created_lt, created_gt, created_lte, created_gte, } = value; Self::List(Box::new(PaymentIntentListParams { offset: 0, starting_at: created_gte.or(created_gt).or(created), ending_at: created_lte.or(created_lt).or(created), amount_filter: None, connector: None, currency: None, status: None, payment_method: None, payment_method_type: None, authentication_type: None, merchant_connector_id: None, profile_id: None, customer_id, starting_after_id: starting_after, ending_before_id: ending_before, limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)), order: Default::default(), card_network: None, card_discovery: None, merchant_order_reference_id: None, })) } } #[cfg(feature = "v2")] impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchConstraints { fn from(value: api_models::payments::PaymentListConstraints) -> Self { let api_models::payments::PaymentListConstraints { customer_id, starting_after, ending_before, limit, created, created_lt, created_gt, created_lte, created_gte, payment_id, profile_id, start_amount, end_amount, connector, currency, status, payment_method_type, payment_method_subtype, authentication_type, merchant_connector_id, order_on, order_by, card_network, merchant_order_reference_id, offset, } = value; Self::List(Box::new(PaymentIntentListParams { offset: offset.unwrap_or_default(), starting_at: created_gte.or(created_gt).or(created), ending_at: created_lte.or(created_lt).or(created), amount_filter: (start_amount.is_some() || end_amount.is_some()).then_some({ api_models::payments::AmountFilter { start_amount, end_amount, } }), connector, currency, status, payment_method_type, payment_method_subtype, authentication_type, merchant_connector_id, profile_id, customer_id, starting_after_id: starting_after, ending_before_id: ending_before, limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)), order: api_models::payments::Order { on: order_on, by: order_by, }, card_network, merchant_order_reference_id, payment_id, })) } } #[cfg(feature = "v1")] impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints { fn from(value: common_utils::types::TimeRange) -> Self { Self::List(Box::new(PaymentIntentListParams { offset: 0, starting_at: Some(value.start_time), ending_at: value.end_time, amount_filter: None, connector: None, currency: None, status: None, payment_method: None, payment_method_type: None, authentication_type: None, merchant_connector_id: None, profile_id: None, customer_id: None, starting_after_id: None, ending_before_id: None, limit: None, order: Default::default(), card_network: None, card_discovery: None, merchant_order_reference_id: None, })) } } #[cfg(feature = "v1")] impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentFetchConstraints { fn from(value: api_models::payments::PaymentListFilterConstraints) -> Self { let api_models::payments::PaymentListFilterConstraints { payment_id, profile_id, customer_id, limit, offset, amount_filter, time_range, connector, currency, status, payment_method, payment_method_type, authentication_type, merchant_connector_id, order, card_network, card_discovery, merchant_order_reference_id, } = value; if let Some(payment_intent_id) = payment_id { Self::Single { payment_intent_id } } else { Self::List(Box::new(PaymentIntentListParams { offset: offset.unwrap_or_default(), starting_at: time_range.map(|t| t.start_time), ending_at: time_range.and_then(|t| t.end_time), amount_filter, connector, currency, status, payment_method, payment_method_type, authentication_type, merchant_connector_id, profile_id: profile_id.map(|profile_id| vec![profile_id]), customer_id, starting_after_id: None, ending_before_id: None, limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V2)), order, card_network, card_discovery, merchant_order_reference_id, })) } } } #[cfg(feature = "v1")] impl<T> TryFrom<(T, Option<Vec<id_type::ProfileId>>)> for PaymentIntentFetchConstraints where Self: From<T>, { type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>; fn try_from( (constraints, auth_profile_id_list): (T, Option<Vec<id_type::ProfileId>>), ) -> Result<Self, Self::Error> { let payment_intent_constraints = Self::from(constraints); if let Self::List(mut pi_list_params) = payment_intent_constraints { let profile_id_from_request_body = pi_list_params.profile_id; match (profile_id_from_request_body, auth_profile_id_list) { (None, None) => pi_list_params.profile_id = None, (None, Some(auth_profile_id_list)) => { pi_list_params.profile_id = Some(auth_profile_id_list) } (Some(profile_id_from_request_body), None) => { pi_list_params.profile_id = Some(profile_id_from_request_body) } (Some(profile_id_from_request_body), Some(auth_profile_id_list)) => { let profile_id_from_request_body_is_available_in_auth_profile_id_list = profile_id_from_request_body .iter() .all(|profile_id| auth_profile_id_list.contains(profile_id)); if profile_id_from_request_body_is_available_in_auth_profile_id_list { pi_list_params.profile_id = Some(profile_id_from_request_body) } else { // This scenario is very unlikely to happen let inaccessible_profile_ids: Vec<_> = profile_id_from_request_body .iter() .filter(|profile_id| !auth_profile_id_list.contains(profile_id)) .collect(); return Err(error_stack::Report::new( errors::api_error_response::ApiErrorResponse::PreconditionFailed { message: format!( "Access not available for the given profile_id {inaccessible_profile_ids:?}", ), }, )); } } } Ok(Self::List(pi_list_params)) } else { Ok(payment_intent_constraints) } } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl behaviour::Conversion for PaymentIntent { type DstType = DieselPaymentIntent; type NewDstType = DieselPaymentIntentNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let Self { merchant_id, amount_details, status, amount_captured, customer_id, description, return_url, metadata, statement_descriptor, created_at, modified_at, last_synced, setup_future_usage, active_attempt_id, active_attempt_id_type, active_attempts_group_id, order_details, allowed_payment_method_types, connector_metadata, feature_metadata, attempt_count, profile_id, payment_link_id, frm_merchant_decision, updated_by, request_incremental_authorization, split_txns_enabled, authorization_count, session_expiry, request_external_three_ds_authentication, frm_metadata, customer_details, merchant_reference_id, billing_address, shipping_address, capture_method, id, authentication_type, prerouting_algorithm, organization_id, enable_payment_link, apply_mit_exemption, customer_present, routing_algorithm_id, payment_link_config, split_payments, force_3ds_challenge, force_3ds_challenge_trigger, processor_merchant_id, created_by, is_iframe_redirection_enabled, is_payment_id_from_merchant, enable_partial_authorization, } = self; Ok(DieselPaymentIntent { skip_external_tax_calculation: Some(amount_details.get_external_tax_action_as_bool()), surcharge_applicable: Some(amount_details.get_surcharge_action_as_bool()), merchant_id, status, amount: amount_details.order_amount, currency: amount_details.currency, amount_captured, customer_id, description, return_url, metadata, statement_descriptor, created_at, modified_at, last_synced, setup_future_usage: Some(setup_future_usage), active_attempt_id, active_attempt_id_type: Some(active_attempt_id_type), active_attempts_group_id, order_details: order_details.map(|order_details| { order_details .into_iter() .map(|order_detail| Secret::new(order_detail.expose())) .collect::<Vec<_>>() }), allowed_payment_method_types: allowed_payment_method_types .map(|allowed_payment_method_types| { allowed_payment_method_types .encode_to_value() .change_context(ValidationError::InvalidValue { message: "Failed to serialize allowed_payment_method_types".to_string(), }) }) .transpose()? .map(Secret::new), connector_metadata: connector_metadata .map(|cm| { cm.encode_to_value() .change_context(ValidationError::InvalidValue { message: "Failed to serialize connector_metadata".to_string(), }) }) .transpose()? .map(Secret::new), feature_metadata, attempt_count, profile_id, frm_merchant_decision, payment_link_id, updated_by, request_incremental_authorization: Some(request_incremental_authorization), split_txns_enabled: Some(split_txns_enabled), authorization_count, session_expiry, request_external_three_ds_authentication: Some( request_external_three_ds_authentication.as_bool(), ), frm_metadata, customer_details: customer_details.map(Encryption::from), billing_address: billing_address.map(Encryption::from), shipping_address: shipping_address.map(Encryption::from), capture_method: Some(capture_method), id, authentication_type, prerouting_algorithm: prerouting_algorithm .map(|prerouting_algorithm| { prerouting_algorithm.encode_to_value().change_context( ValidationError::InvalidValue { message: "Failed to serialize prerouting_algorithm".to_string(), }, ) }) .transpose()?, merchant_reference_id, surcharge_amount: amount_details.surcharge_amount, tax_on_surcharge: amount_details.tax_on_surcharge, organization_id, shipping_cost: amount_details.shipping_cost, tax_details: amount_details.tax_details, enable_payment_link: Some(enable_payment_link.as_bool()), apply_mit_exemption: Some(apply_mit_exemption.as_bool()), customer_present: Some(customer_present.as_bool()), payment_link_config, routing_algorithm_id, psd2_sca_exemption_type: None, request_extended_authorization: None, platform_merchant_id: None, split_payments, force_3ds_challenge, force_3ds_challenge_trigger, processor_merchant_id: Some(processor_merchant_id), created_by: created_by.map(|cb| cb.to_string()), is_iframe_redirection_enabled, is_payment_id_from_merchant, payment_channel: None, tax_status: None, discount_amount: None, shipping_amount_tax: None, duty_amount: None, order_date: None, enable_partial_authorization, enable_overcapture: None, mit_category: None, }) } async fn convert_back( state: &KeyManagerState, storage_model: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { async { let decrypted_data = crypto_operation( state, type_name!(Self::DstType), CryptoOperation::BatchDecrypt(super::EncryptedPaymentIntent::to_encryptable( super::EncryptedPaymentIntent { billing_address: storage_model.billing_address, shipping_address: storage_model.shipping_address, customer_details: storage_model.customer_details, }, )), key_manager_identifier, key.peek(), ) .await .and_then(|val| val.try_into_batchoperation())?; let data = super::EncryptedPaymentIntent::from_encryptable(decrypted_data) .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Invalid batch operation data")?; let amount_details = super::AmountDetails { order_amount: storage_model.amount, currency: storage_model.currency, surcharge_amount: storage_model.surcharge_amount, tax_on_surcharge: storage_model.tax_on_surcharge, shipping_cost: storage_model.shipping_cost, tax_details: storage_model.tax_details, skip_external_tax_calculation: common_enums::TaxCalculationOverride::from( storage_model.skip_external_tax_calculation, ), skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::from( storage_model.surcharge_applicable, ), amount_captured: storage_model.amount_captured, }; let billing_address = data .billing_address .map(|billing| { billing.deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing Address")?; let shipping_address = data .shipping_address .map(|shipping| { shipping.deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing Address")?; let allowed_payment_method_types = storage_model .allowed_payment_method_types .map(|allowed_payment_method_types| { allowed_payment_method_types.parse_value("Vec<PaymentMethodType>") }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed)?; Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { merchant_id: storage_model.merchant_id.clone(), status: storage_model.status, amount_details, amount_captured: storage_model.amount_captured, customer_id: storage_model.customer_id, description: storage_model.description, return_url: storage_model.return_url, metadata: storage_model.metadata, statement_descriptor: storage_model.statement_descriptor, created_at: storage_model.created_at, modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, setup_future_usage: storage_model.setup_future_usage.unwrap_or_default(), active_attempt_id: storage_model.active_attempt_id, active_attempt_id_type: storage_model.active_attempt_id_type.unwrap_or_default(), active_attempts_group_id: storage_model.active_attempts_group_id, order_details: storage_model.order_details.map(|order_details| { order_details .into_iter() .map(|order_detail| Secret::new(order_detail.expose())) .collect::<Vec<_>>() }), allowed_payment_method_types, connector_metadata: storage_model .connector_metadata .map(|cm| cm.parse_value("ConnectorMetadata")) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Failed to deserialize connector_metadata")?, feature_metadata: storage_model.feature_metadata, attempt_count: storage_model.attempt_count, profile_id: storage_model.profile_id, frm_merchant_decision: storage_model.frm_merchant_decision, payment_link_id: storage_model.payment_link_id, updated_by: storage_model.updated_by, request_incremental_authorization: storage_model .request_incremental_authorization .unwrap_or_default(), split_txns_enabled: storage_model.split_txns_enabled.unwrap_or_default(), authorization_count: storage_model.authorization_count, session_expiry: storage_model.session_expiry, request_external_three_ds_authentication: storage_model .request_external_three_ds_authentication .into(), frm_metadata: storage_model.frm_metadata, customer_details: data.customer_details, billing_address, shipping_address, capture_method: storage_model.capture_method.unwrap_or_default(), id: storage_model.id, merchant_reference_id: storage_model.merchant_reference_id, organization_id: storage_model.organization_id, authentication_type: storage_model.authentication_type, prerouting_algorithm: storage_model .prerouting_algorithm .map(|prerouting_algorithm_value| { prerouting_algorithm_value .parse_value("PaymentRoutingInfo") .change_context(common_utils::errors::CryptoError::DecodingFailed) }) .transpose()?, enable_payment_link: storage_model.enable_payment_link.into(), apply_mit_exemption: storage_model.apply_mit_exemption.into(), customer_present: storage_model.customer_present.into(), payment_link_config: storage_model.payment_link_config, routing_algorithm_id: storage_model.routing_algorithm_id, split_payments: storage_model.split_payments, force_3ds_challenge: storage_model.force_3ds_challenge, force_3ds_challenge_trigger: storage_model.force_3ds_challenge_trigger, processor_merchant_id: storage_model .processor_merchant_id .unwrap_or(storage_model.merchant_id), created_by: storage_model .created_by .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), is_iframe_redirection_enabled: storage_model.is_iframe_redirection_enabled, is_payment_id_from_merchant: storage_model.is_payment_id_from_merchant, enable_partial_authorization: storage_model.enable_partial_authorization, }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting payment intent".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let amount_details = self.amount_details; Ok(DieselPaymentIntentNew { surcharge_applicable: Some(amount_details.get_surcharge_action_as_bool()), skip_external_tax_calculation: Some(amount_details.get_external_tax_action_as_bool()), merchant_id: self.merchant_id, status: self.status, amount: amount_details.order_amount, currency: amount_details.currency, amount_captured: self.amount_captured, customer_id: self.customer_id, description: self.description, return_url: self.return_url, metadata: self.metadata, statement_descriptor: self.statement_descriptor, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, setup_future_usage: Some(self.setup_future_usage), active_attempt_id: self.active_attempt_id, order_details: self.order_details, allowed_payment_method_types: self .allowed_payment_method_types .map(|allowed_payment_method_types| { allowed_payment_method_types .encode_to_value() .change_context(ValidationError::InvalidValue { message: "Failed to serialize allowed_payment_method_types".to_string(), }) }) .transpose()? .map(Secret::new), connector_metadata: self .connector_metadata .map(|cm| { cm.encode_to_value() .change_context(ValidationError::InvalidValue { message: "Failed to serialize connector_metadata".to_string(), }) }) .transpose()? .map(Secret::new), feature_metadata: self.feature_metadata, attempt_count: self.attempt_count, profile_id: self.profile_id, frm_merchant_decision: self.frm_merchant_decision, payment_link_id: self.payment_link_id, updated_by: self.updated_by, request_incremental_authorization: Some(self.request_incremental_authorization), split_txns_enabled: Some(self.split_txns_enabled), authorization_count: self.authorization_count, session_expiry: self.session_expiry, request_external_three_ds_authentication: Some( self.request_external_three_ds_authentication.as_bool(), ), frm_metadata: self.frm_metadata, customer_details: self.customer_details.map(Encryption::from), billing_address: self.billing_address.map(Encryption::from), shipping_address: self.shipping_address.map(Encryption::from), capture_method: Some(self.capture_method), id: self.id, merchant_reference_id: self.merchant_reference_id, authentication_type: self.authentication_type, prerouting_algorithm: self .prerouting_algorithm .map(|prerouting_algorithm| { prerouting_algorithm.encode_to_value().change_context( ValidationError::InvalidValue { message: "Failed to serialize prerouting_algorithm".to_string(), }, ) }) .transpose()?, surcharge_amount: amount_details.surcharge_amount, tax_on_surcharge: amount_details.tax_on_surcharge, organization_id: self.organization_id, shipping_cost: amount_details.shipping_cost, tax_details: amount_details.tax_details, enable_payment_link: Some(self.enable_payment_link.as_bool()), apply_mit_exemption: Some(self.apply_mit_exemption.as_bool()), platform_merchant_id: None, force_3ds_challenge: self.force_3ds_challenge, force_3ds_challenge_trigger: self.force_3ds_challenge_trigger, processor_merchant_id: Some(self.processor_merchant_id), created_by: self.created_by.map(|cb| cb.to_string()), is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, routing_algorithm_id: self.routing_algorithm_id, is_payment_id_from_merchant: self.is_payment_id_from_merchant, payment_channel: None, tax_status: None, discount_amount: None, mit_category: None, shipping_amount_tax: None, duty_amount: None, order_date: None, enable_partial_authorization: self.enable_partial_authorization, }) } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl behaviour::Conversion for PaymentIntent { type DstType = DieselPaymentIntent; type NewDstType = DieselPaymentIntentNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(DieselPaymentIntent { payment_id: self.payment_id, merchant_id: self.merchant_id, status: self.status, amount: self.amount, currency: self.currency, amount_captured: self.amount_captured, customer_id: self.customer_id, description: self.description, return_url: None, // deprecated metadata: self.metadata, connector_id: self.connector_id, shipping_address_id: self.shipping_address_id, billing_address_id: self.billing_address_id, statement_descriptor_name: self.statement_descriptor_name, statement_descriptor_suffix: self.statement_descriptor_suffix, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, setup_future_usage: self.setup_future_usage, off_session: self.off_session, client_secret: self.client_secret, active_attempt_id: self.active_attempt.get_id(), business_country: self.business_country, business_label: self.business_label, order_details: self.order_details, allowed_payment_method_types: self.allowed_payment_method_types, connector_metadata: self.connector_metadata, feature_metadata: self.feature_metadata, attempt_count: self.attempt_count, profile_id: self.profile_id, merchant_decision: self.merchant_decision, payment_link_id: self.payment_link_id, payment_confirm_source: self.payment_confirm_source, updated_by: self.updated_by, surcharge_applicable: self.surcharge_applicable, request_incremental_authorization: self.request_incremental_authorization, incremental_authorization_allowed: self.incremental_authorization_allowed, authorization_count: self.authorization_count, fingerprint_id: self.fingerprint_id, session_expiry: self.session_expiry, request_external_three_ds_authentication: self.request_external_three_ds_authentication, charges: None, split_payments: self.split_payments, frm_metadata: self.frm_metadata, customer_details: self.customer_details.map(Encryption::from), billing_details: self.billing_details.map(Encryption::from), merchant_order_reference_id: self.merchant_order_reference_id, shipping_details: self.shipping_details.map(Encryption::from), is_payment_processor_token_flow: self.is_payment_processor_token_flow, organization_id: self.organization_id, shipping_cost: self.shipping_cost, tax_details: self.tax_details, skip_external_tax_calculation: self.skip_external_tax_calculation, request_extended_authorization: self.request_extended_authorization, psd2_sca_exemption_type: self.psd2_sca_exemption_type, platform_merchant_id: None, processor_merchant_id: Some(self.processor_merchant_id), created_by: self.created_by.map(|cb| cb.to_string()), force_3ds_challenge: self.force_3ds_challenge, force_3ds_challenge_trigger: self.force_3ds_challenge_trigger, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, extended_return_url: self.return_url, is_payment_id_from_merchant: self.is_payment_id_from_merchant, payment_channel: self.payment_channel, tax_status: self.tax_status, discount_amount: self.discount_amount, order_date: self.order_date, shipping_amount_tax: self.shipping_amount_tax, duty_amount: self.duty_amount, enable_partial_authorization: self.enable_partial_authorization, enable_overcapture: self.enable_overcapture, mit_category: self.mit_category, }) } async fn convert_back( state: &KeyManagerState, storage_model: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { async { let decrypted_data = crypto_operation( state, type_name!(Self::DstType), CryptoOperation::BatchDecrypt(super::EncryptedPaymentIntent::to_encryptable( super::EncryptedPaymentIntent { billing_details: storage_model.billing_details, shipping_details: storage_model.shipping_details, customer_details: storage_model.customer_details, }, )), key_manager_identifier, key.peek(), ) .await .and_then(|val| val.try_into_batchoperation())?; let data = super::EncryptedPaymentIntent::from_encryptable(decrypted_data) .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Invalid batch operation data")?; Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id.clone(), status: storage_model.status, amount: storage_model.amount, currency: storage_model.currency, amount_captured: storage_model.amount_captured, customer_id: storage_model.customer_id, description: storage_model.description, return_url: storage_model .extended_return_url .or(storage_model.return_url), // fallback to legacy metadata: storage_model.metadata, connector_id: storage_model.connector_id, shipping_address_id: storage_model.shipping_address_id, billing_address_id: storage_model.billing_address_id, statement_descriptor_name: storage_model.statement_descriptor_name, statement_descriptor_suffix: storage_model.statement_descriptor_suffix, created_at: storage_model.created_at, modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, setup_future_usage: storage_model.setup_future_usage, off_session: storage_model.off_session, client_secret: storage_model.client_secret, active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id), business_country: storage_model.business_country, business_label: storage_model.business_label, order_details: storage_model.order_details, allowed_payment_method_types: storage_model.allowed_payment_method_types, connector_metadata: storage_model.connector_metadata, feature_metadata: storage_model.feature_metadata, attempt_count: storage_model.attempt_count, profile_id: storage_model.profile_id, merchant_decision: storage_model.merchant_decision, payment_link_id: storage_model.payment_link_id, payment_confirm_source: storage_model.payment_confirm_source, updated_by: storage_model.updated_by, surcharge_applicable: storage_model.surcharge_applicable, request_incremental_authorization: storage_model.request_incremental_authorization, incremental_authorization_allowed: storage_model.incremental_authorization_allowed, authorization_count: storage_model.authorization_count, fingerprint_id: storage_model.fingerprint_id, session_expiry: storage_model.session_expiry, request_external_three_ds_authentication: storage_model .request_external_three_ds_authentication, split_payments: storage_model.split_payments, frm_metadata: storage_model.frm_metadata, shipping_cost: storage_model.shipping_cost, tax_details: storage_model.tax_details, customer_details: data.customer_details, billing_details: data.billing_details, merchant_order_reference_id: storage_model.merchant_order_reference_id, shipping_details: data.shipping_details, is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow, organization_id: storage_model.organization_id, skip_external_tax_calculation: storage_model.skip_external_tax_calculation, request_extended_authorization: storage_model.request_extended_authorization, psd2_sca_exemption_type: storage_model.psd2_sca_exemption_type, processor_merchant_id: storage_model .processor_merchant_id .unwrap_or(storage_model.merchant_id), created_by: storage_model .created_by .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), force_3ds_challenge: storage_model.force_3ds_challenge, force_3ds_challenge_trigger: storage_model.force_3ds_challenge_trigger, is_iframe_redirection_enabled: storage_model.is_iframe_redirection_enabled, is_payment_id_from_merchant: storage_model.is_payment_id_from_merchant, payment_channel: storage_model.payment_channel, tax_status: storage_model.tax_status, discount_amount: storage_model.discount_amount, shipping_amount_tax: storage_model.shipping_amount_tax, duty_amount: storage_model.duty_amount, order_date: storage_model.order_date, enable_partial_authorization: storage_model.enable_partial_authorization, enable_overcapture: storage_model.enable_overcapture, mit_category: storage_model.mit_category, }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting payment intent".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(DieselPaymentIntentNew { payment_id: self.payment_id, merchant_id: self.merchant_id, status: self.status, amount: self.amount, currency: self.currency, amount_captured: self.amount_captured, customer_id: self.customer_id, description: self.description, return_url: None, // deprecated metadata: self.metadata, connector_id: self.connector_id, shipping_address_id: self.shipping_address_id, billing_address_id: self.billing_address_id, statement_descriptor_name: self.statement_descriptor_name, statement_descriptor_suffix: self.statement_descriptor_suffix, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, setup_future_usage: self.setup_future_usage, off_session: self.off_session, client_secret: self.client_secret, active_attempt_id: self.active_attempt.get_id(), business_country: self.business_country, business_label: self.business_label, order_details: self.order_details, allowed_payment_method_types: self.allowed_payment_method_types, connector_metadata: self.connector_metadata, feature_metadata: self.feature_metadata, attempt_count: self.attempt_count, profile_id: self.profile_id, merchant_decision: self.merchant_decision, payment_link_id: self.payment_link_id, payment_confirm_source: self.payment_confirm_source, updated_by: self.updated_by, surcharge_applicable: self.surcharge_applicable, request_incremental_authorization: self.request_incremental_authorization, incremental_authorization_allowed: self.incremental_authorization_allowed, authorization_count: self.authorization_count, fingerprint_id: self.fingerprint_id, session_expiry: self.session_expiry, request_external_three_ds_authentication: self.request_external_three_ds_authentication, charges: None, split_payments: self.split_payments, frm_metadata: self.frm_metadata, customer_details: self.customer_details.map(Encryption::from), billing_details: self.billing_details.map(Encryption::from), merchant_order_reference_id: self.merchant_order_reference_id, shipping_details: self.shipping_details.map(Encryption::from), is_payment_processor_token_flow: self.is_payment_processor_token_flow, organization_id: self.organization_id, shipping_cost: self.shipping_cost, tax_details: self.tax_details, skip_external_tax_calculation: self.skip_external_tax_calculation, request_extended_authorization: self.request_extended_authorization, psd2_sca_exemption_type: self.psd2_sca_exemption_type, platform_merchant_id: None, processor_merchant_id: Some(self.processor_merchant_id), created_by: self.created_by.map(|cb| cb.to_string()), force_3ds_challenge: self.force_3ds_challenge, force_3ds_challenge_trigger: self.force_3ds_challenge_trigger, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, extended_return_url: self.return_url, is_payment_id_from_merchant: self.is_payment_id_from_merchant, payment_channel: self.payment_channel, tax_status: self.tax_status, discount_amount: self.discount_amount, order_date: self.order_date, shipping_amount_tax: self.shipping_amount_tax, duty_amount: self.duty_amount, enable_partial_authorization: self.enable_partial_authorization, enable_overcapture: self.enable_overcapture, mit_category: self.mit_category, }) } }
crates/hyperswitch_domain_models/src/payments/payment_intent.rs
hyperswitch_domain_models::src::payments::payment_intent
18,138
true
// File: crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs // Module: hyperswitch_domain_models::src::router_request_types::subscriptions use api_models::payments::Address; use common_utils::id_type; use crate::connector_endpoints; #[derive(Debug, Clone)] pub struct SubscriptionItem { pub item_price_id: String, pub quantity: Option<u32>, } #[derive(Debug, Clone)] pub struct SubscriptionCreateRequest { pub customer_id: id_type::CustomerId, pub subscription_id: id_type::SubscriptionId, pub subscription_items: Vec<SubscriptionItem>, pub billing_address: Address, pub auto_collection: SubscriptionAutoCollection, pub connector_params: connector_endpoints::ConnectorParams, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum SubscriptionAutoCollection { On, Off, } #[derive(Debug, Clone)] pub struct GetSubscriptionPlansRequest { pub limit: Option<u32>, pub offset: Option<u32>, } impl GetSubscriptionPlansRequest { pub fn new(limit: Option<u32>, offset: Option<u32>) -> Self { Self { limit, offset } } } impl Default for GetSubscriptionPlansRequest { fn default() -> Self { Self { limit: Some(10), offset: Some(0), } } } #[derive(Debug, Clone)] pub struct GetSubscriptionPlanPricesRequest { pub plan_price_id: String, } #[derive(Debug, Clone)] pub struct GetSubscriptionEstimateRequest { pub price_id: String, }
crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs
hyperswitch_domain_models::src::router_request_types::subscriptions
332
true
// File: crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs // Module: hyperswitch_domain_models::src::router_request_types::fraud_check use api_models; use common_enums; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, pii::Email, }; use diesel_models::types::OrderDetailsWithAmount; use masking::Secret; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::router_request_types; #[derive(Debug, Clone)] pub struct FraudCheckSaleData { pub amount: i64, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub currency: Option<common_enums::Currency>, pub email: Option<Email>, } #[derive(Debug, Clone)] pub struct FraudCheckCheckoutData { pub amount: i64, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub currency: Option<common_enums::Currency>, pub browser_info: Option<router_request_types::BrowserInformation>, pub payment_method_data: Option<api_models::payments::AdditionalPaymentData>, pub email: Option<Email>, pub gateway: Option<String>, } #[derive(Debug, Clone)] pub struct FraudCheckTransactionData { pub amount: i64, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub currency: Option<common_enums::Currency>, pub payment_method: Option<common_enums::PaymentMethod>, pub error_code: Option<String>, pub error_message: Option<String>, pub connector_transaction_id: Option<String>, //The name of the payment gateway or financial institution that processed the transaction. pub connector: Option<String>, } #[derive(Debug, Clone)] pub struct FraudCheckRecordReturnData { pub amount: i64, pub currency: Option<common_enums::Currency>, pub refund_method: RefundMethod, pub refund_transaction_id: Option<String>, } #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde_with::skip_serializing_none] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RefundMethod { StoreCredit, OriginalPaymentInstrument, NewPaymentInstrument, } #[derive(Debug, Clone)] pub struct FraudCheckFulfillmentData { pub amount: i64, pub order_details: Option<Vec<Secret<serde_json::Value>>>, pub fulfillment_req: FrmFulfillmentRequest, } #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde_with::skip_serializing_none] #[serde(rename_all = "snake_case")] pub struct FrmFulfillmentRequest { ///unique payment_id for the transaction #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")] pub payment_id: common_utils::id_type::PaymentId, ///unique order_id for the order_details in the transaction #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")] pub order_id: String, ///denotes the status of the fulfillment... can be one of PARTIAL, COMPLETE, REPLACEMENT, CANCELED #[schema(value_type = Option<FulfillmentStatus>, example = "COMPLETE")] pub fulfillment_status: Option<FulfillmentStatus>, ///contains details of the fulfillment #[schema(value_type = Vec<Fulfillments>)] pub fulfillments: Vec<Fulfillments>, //name of the tracking Company #[schema(max_length = 255, example = "fedex")] pub tracking_company: Option<String>, //tracking ID of the product #[schema(example = r#"["track_8327446667", "track_8327446668"]"#)] pub tracking_numbers: Option<Vec<String>>, //tracking_url for tracking the product pub tracking_urls: Option<Vec<String>>, // The name of the Shipper. pub carrier: Option<String>, // Fulfillment method for the shipment. pub fulfillment_method: Option<String>, // Statuses to indicate shipment state. pub shipment_status: Option<String>, // The date and time items are ready to be shipped. pub shipped_at: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde_with::skip_serializing_none] #[serde(rename_all = "snake_case")] pub struct Fulfillments { ///shipment_id of the shipped items #[schema(max_length = 255, example = "ship_101")] pub shipment_id: String, ///products sent in the shipment #[schema(value_type = Option<Vec<Product>>)] pub products: Option<Vec<Product>>, ///destination address of the shipment #[schema(value_type = Destination)] pub destination: Destination, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(untagged)] #[serde_with::skip_serializing_none] #[serde(rename_all = "snake_case")] pub enum FulfillmentStatus { PARTIAL, COMPLETE, REPLACEMENT, CANCELED, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde_with::skip_serializing_none] #[serde(rename_all = "snake_case")] pub struct Product { pub item_name: String, pub item_quantity: i64, pub item_id: String, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde_with::skip_serializing_none] #[serde(rename_all = "snake_case")] pub struct Destination { pub full_name: Secret<String>, pub organization: Option<String>, pub email: Option<Email>, pub address: Address, } #[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)] #[serde_with::skip_serializing_none] #[serde(rename_all = "snake_case")] pub struct Address { pub street_address: Secret<String>, pub unit: Option<Secret<String>>, pub postal_code: Secret<String>, pub city: String, pub province_code: Secret<String>, pub country_code: common_enums::CountryAlpha2, } impl ApiEventMetric for FrmFulfillmentRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::FraudCheck) } }
crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
hyperswitch_domain_models::src::router_request_types::fraud_check
1,391
true
// File: crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs // Module: hyperswitch_domain_models::src::router_request_types::unified_authentication_service use api_models::payments::DeviceChannel; use common_enums::MerchantCategoryCode; use common_types::payments::MerchantCountryCode; use common_utils::types::MinorUnit; use masking::Secret; use crate::address::Address; #[derive(Clone, Debug)] pub struct UasPreAuthenticationRequestData { pub service_details: Option<CtpServiceDetails>, pub transaction_details: Option<TransactionDetails>, pub payment_details: Option<PaymentDetails>, pub authentication_info: Option<AuthenticationInfo>, pub merchant_details: Option<MerchantDetails>, pub billing_address: Option<Address>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, } #[derive(Debug, Clone)] pub struct MerchantDetails { pub merchant_id: Option<String>, pub merchant_name: Option<String>, pub merchant_category_code: Option<MerchantCategoryCode>, pub merchant_country_code: Option<MerchantCountryCode>, pub endpoint_prefix: Option<String>, pub three_ds_requestor_url: Option<String>, pub three_ds_requestor_id: Option<String>, pub three_ds_requestor_name: Option<String>, pub notification_url: Option<url::Url>, } #[derive(Clone, Debug, PartialEq, serde::Serialize)] pub struct AuthenticationInfo { pub authentication_type: Option<String>, pub authentication_reasons: Option<Vec<String>>, pub consent_received: bool, pub is_authenticated: bool, pub locale: Option<String>, pub supported_card_brands: Option<String>, pub encrypted_payload: Option<Secret<String>>, } #[derive(Clone, Debug)] pub struct UasAuthenticationRequestData { pub browser_details: Option<super::BrowserInformation>, pub transaction_details: TransactionDetails, pub pre_authentication_data: super::authentication::PreAuthenticationData, pub return_url: Option<String>, pub sdk_information: Option<api_models::payments::SdkInformation>, pub email: Option<common_utils::pii::Email>, pub threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator, pub webhook_url: String, } #[derive(Clone, Debug, serde::Serialize)] pub struct CtpServiceDetails { pub service_session_ids: Option<ServiceSessionIds>, pub payment_details: Option<PaymentDetails>, } #[derive(Debug, Clone, serde::Serialize)] pub struct PaymentDetails { pub pan: cards::CardNumber, pub digital_card_id: Option<String>, pub payment_data_type: Option<common_enums::PaymentMethodType>, pub encrypted_src_card_details: Option<String>, pub card_expiry_month: Secret<String>, pub card_expiry_year: Secret<String>, pub cardholder_name: Option<Secret<String>>, pub card_token_number: Option<Secret<String>>, pub account_type: Option<common_enums::PaymentMethodType>, pub card_cvc: Option<Secret<String>>, } #[derive(Clone, serde::Deserialize, Debug, serde::Serialize)] pub struct ServiceSessionIds { pub correlation_id: Option<String>, pub merchant_transaction_id: Option<String>, pub x_src_flow_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone)] pub struct TransactionDetails { pub amount: Option<MinorUnit>, pub currency: Option<common_enums::Currency>, pub device_channel: Option<DeviceChannel>, pub message_category: Option<super::authentication::MessageCategory>, } #[derive(Clone, Debug)] pub struct UasPostAuthenticationRequestData { pub threeds_server_transaction_id: Option<String>, } #[derive(Debug, Clone)] pub enum UasAuthenticationResponseData { PreAuthentication { authentication_details: PreAuthenticationDetails, }, Authentication { authentication_details: AuthenticationDetails, }, PostAuthentication { authentication_details: PostAuthenticationDetails, }, Confirmation {}, } #[derive(Debug, Clone, serde::Serialize)] pub struct PreAuthenticationDetails { pub threeds_server_transaction_id: Option<String>, pub maximum_supported_3ds_version: Option<common_utils::types::SemanticVersion>, pub connector_authentication_id: Option<String>, pub three_ds_method_data: Option<String>, pub three_ds_method_url: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub connector_metadata: Option<serde_json::Value>, pub directory_server_id: Option<String>, } #[derive(Debug, Clone)] pub struct AuthenticationDetails { pub authn_flow_type: super::authentication::AuthNFlowType, pub authentication_value: Option<Secret<String>>, pub trans_status: common_enums::TransactionStatus, pub connector_metadata: Option<serde_json::Value>, pub ds_trans_id: Option<String>, pub eci: Option<String>, pub challenge_code: Option<String>, pub challenge_cancel: Option<String>, pub challenge_code_reason: Option<String>, pub message_extension: Option<common_utils::pii::SecretSerdeValue>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct PostAuthenticationDetails { pub eci: Option<String>, pub token_details: Option<TokenDetails>, pub dynamic_data_details: Option<DynamicData>, pub trans_status: Option<common_enums::TransactionStatus>, pub challenge_cancel: Option<String>, pub challenge_code_reason: Option<String>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct TokenDetails { pub payment_token: cards::CardNumber, pub payment_account_reference: String, pub token_expiration_month: Secret<String>, pub token_expiration_year: Secret<String>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct DynamicData { pub dynamic_data_value: Option<Secret<String>>, pub dynamic_data_type: Option<String>, pub ds_trans_id: Option<String>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct UasConfirmationRequestData { pub x_src_flow_id: Option<String>, pub transaction_amount: MinorUnit, pub transaction_currency: common_enums::Currency, // Type of event associated with the checkout. Valid values are: - 01 - Authorise - 02 - Capture - 03 - Refund - 04 - Cancel - 05 - Fraud - 06 - Chargeback - 07 - Other pub checkout_event_type: Option<String>, pub checkout_event_status: Option<String>, pub confirmation_status: Option<String>, pub confirmation_reason: Option<String>, pub confirmation_timestamp: Option<String>, // Authorisation code associated with an approved transaction. pub network_authorization_code: Option<String>, // The unique authorisation related tracing value assigned by a Payment Network and provided in an authorisation response. Required only when checkoutEventType=01. If checkoutEventType=01 and the value of networkTransactionIdentifier is unknown, please pass UNAVLB pub network_transaction_identifier: Option<String>, pub correlation_id: Option<String>, pub merchant_transaction_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ThreeDsMetaData { pub merchant_category_code: Option<MerchantCategoryCode>, pub merchant_country_code: Option<MerchantCountryCode>, pub merchant_name: Option<String>, pub endpoint_prefix: Option<String>, pub three_ds_requestor_name: Option<String>, pub three_ds_requestor_id: Option<String>, pub merchant_configuration_id: Option<String>, }
crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
hyperswitch_domain_models::src::router_request_types::unified_authentication_service
1,609
true
// File: crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs // Module: hyperswitch_domain_models::src::router_request_types::revenue_recovery use common_enums::enums; use crate::connector_endpoints; #[derive(Debug, Clone)] pub struct BillingConnectorPaymentsSyncRequest { /// unique id for making billing connector psync call pub billing_connector_psync_id: String, /// connector params of the connector pub connector_params: connector_endpoints::ConnectorParams, } #[derive(Debug, Clone)] pub struct InvoiceRecordBackRequest { pub merchant_reference_id: common_utils::id_type::PaymentReferenceId, pub amount: common_utils::types::MinorUnit, pub currency: enums::Currency, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub attempt_status: common_enums::AttemptStatus, pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, pub connector_params: connector_endpoints::ConnectorParams, } #[derive(Debug, Clone)] pub struct BillingConnectorInvoiceSyncRequest { /// Invoice id pub billing_connector_invoice_id: String, /// connector params of the connector pub connector_params: connector_endpoints::ConnectorParams, }
crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs
hyperswitch_domain_models::src::router_request_types::revenue_recovery
264
true
// File: crates/hyperswitch_domain_models/src/router_request_types/authentication.rs // Module: hyperswitch_domain_models::src::router_request_types::authentication use common_utils::{ext_traits::OptionExt, pii::Email}; use error_stack::{Report, ResultExt}; use serde::{Deserialize, Serialize}; use crate::{ address, errors::api_error_response::ApiErrorResponse, payment_method_data::{Card, PaymentMethodData}, router_request_types::BrowserInformation, }; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ChallengeParams { pub acs_url: Option<url::Url>, pub challenge_request: Option<String>, pub challenge_request_key: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub three_dsserver_trans_id: Option<String>, pub acs_signed_content: Option<String>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub enum AuthNFlowType { Challenge(Box<ChallengeParams>), Frictionless, } impl AuthNFlowType { pub fn get_acs_url(&self) -> Option<String> { if let Self::Challenge(challenge_params) = self { challenge_params.acs_url.as_ref().map(ToString::to_string) } else { None } } pub fn get_challenge_request(&self) -> Option<String> { if let Self::Challenge(challenge_params) = self { challenge_params.challenge_request.clone() } else { None } } pub fn get_challenge_request_key(&self) -> Option<String> { if let Self::Challenge(challenge_params) = self { challenge_params.challenge_request_key.clone() } else { None } } pub fn get_acs_reference_number(&self) -> Option<String> { if let Self::Challenge(challenge_params) = self { challenge_params.acs_reference_number.clone() } else { None } } pub fn get_acs_trans_id(&self) -> Option<String> { if let Self::Challenge(challenge_params) = self { challenge_params.acs_trans_id.clone() } else { None } } pub fn get_acs_signed_content(&self) -> Option<String> { if let Self::Challenge(challenge_params) = self { challenge_params.acs_signed_content.clone() } else { None } } pub fn get_decoupled_authentication_type(&self) -> common_enums::DecoupledAuthenticationType { match self { Self::Challenge(_) => common_enums::DecoupledAuthenticationType::Challenge, Self::Frictionless => common_enums::DecoupledAuthenticationType::Frictionless, } } } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct MessageExtensionAttribute { pub id: String, pub name: String, pub criticality_indicator: bool, pub data: serde_json::Value, } #[derive(Clone, Default, Debug)] pub struct PreAuthNRequestData { // card data pub card: Card, } #[derive(Clone, Debug)] pub struct ConnectorAuthenticationRequestData { pub payment_method_data: PaymentMethodData, pub billing_address: address::Address, pub shipping_address: Option<address::Address>, pub browser_details: Option<BrowserInformation>, pub amount: Option<i64>, pub currency: Option<common_enums::Currency>, pub message_category: MessageCategory, pub device_channel: api_models::payments::DeviceChannel, pub pre_authentication_data: PreAuthenticationData, pub return_url: Option<String>, pub sdk_information: Option<api_models::payments::SdkInformation>, pub email: Option<Email>, pub threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator, pub three_ds_requestor_url: String, pub webhook_url: String, pub force_3ds_challenge: bool, } #[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)] pub enum MessageCategory { Payment, NonPayment, } #[derive(Clone, Debug)] pub struct ConnectorPostAuthenticationRequestData { pub threeds_server_transaction_id: String, } #[derive(Clone, Debug)] pub struct PreAuthenticationData { pub threeds_server_transaction_id: String, pub message_version: common_utils::types::SemanticVersion, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, pub acquirer_country_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, } impl TryFrom<&diesel_models::authentication::Authentication> for PreAuthenticationData { type Error = Report<ApiErrorResponse>; fn try_from( authentication: &diesel_models::authentication::Authentication, ) -> Result<Self, Self::Error> { let error_message = ApiErrorResponse::UnprocessableEntity { message: "Pre Authentication must be completed successfully before Authentication can be performed".to_string() }; let threeds_server_transaction_id = authentication .threeds_server_transaction_id .clone() .get_required_value("threeds_server_transaction_id") .change_context(error_message.clone())?; let message_version = authentication .message_version .clone() .get_required_value("message_version") .change_context(error_message)?; Ok(Self { threeds_server_transaction_id, message_version, acquirer_bin: authentication.acquirer_bin.clone(), acquirer_merchant_id: authentication.acquirer_merchant_id.clone(), connector_metadata: authentication.connector_metadata.clone(), acquirer_country_code: authentication.acquirer_country_code.clone(), }) } } #[derive(Clone, Default, Debug, Serialize, Deserialize)] pub struct ThreeDsMethodData { pub three_ds_method_data_submission: bool, pub three_ds_method_data: String, pub three_ds_method_url: Option<String>, } #[derive(Clone, Default, Debug, Serialize, Deserialize)] pub struct AcquirerDetails { pub acquirer_bin: String, pub acquirer_merchant_id: String, pub acquirer_country_code: Option<String>, } #[derive(Clone, Debug, Deserialize)] pub struct ExternalThreeDSConnectorMetadata { pub pull_mechanism_for_external_3ds_enabled: Option<bool>, } #[derive(Clone, Debug)] pub struct AuthenticationStore { pub cavv: Option<masking::Secret<String>>, pub authentication: diesel_models::authentication::Authentication, }
crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
hyperswitch_domain_models::src::router_request_types::authentication
1,390
true
// File: crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs // Module: hyperswitch_domain_models::src::router_response_types::subscriptions use common_enums::Currency; use common_utils::{id_type, types::MinorUnit}; use time::PrimitiveDateTime; #[derive(Debug, Clone)] pub struct SubscriptionCreateResponse { pub subscription_id: id_type::SubscriptionId, pub status: SubscriptionStatus, pub customer_id: id_type::CustomerId, pub currency_code: Currency, pub total_amount: MinorUnit, pub next_billing_at: Option<PrimitiveDateTime>, pub created_at: Option<PrimitiveDateTime>, pub invoice_details: Option<SubscriptionInvoiceData>, } #[derive(Debug, Clone, serde::Serialize)] pub struct SubscriptionInvoiceData { pub id: id_type::InvoiceId, pub total: MinorUnit, pub currency_code: Currency, pub status: Option<common_enums::connector_enums::InvoiceStatus>, pub billing_address: Option<api_models::payments::Address>, } #[derive(Debug, Clone, PartialEq, Eq, Copy)] pub enum SubscriptionStatus { Pending, Trial, Active, Paused, Unpaid, Onetime, Cancelled, Failed, Created, } impl From<SubscriptionStatus> for api_models::subscription::SubscriptionStatus { fn from(status: SubscriptionStatus) -> Self { match status { SubscriptionStatus::Pending => Self::Pending, SubscriptionStatus::Trial => Self::Trial, SubscriptionStatus::Active => Self::Active, SubscriptionStatus::Paused => Self::Paused, SubscriptionStatus::Unpaid => Self::Unpaid, SubscriptionStatus::Onetime => Self::Onetime, SubscriptionStatus::Cancelled => Self::Cancelled, SubscriptionStatus::Failed => Self::Failed, SubscriptionStatus::Created => Self::Created, } } } #[derive(Debug, Clone)] pub struct GetSubscriptionPlansResponse { pub list: Vec<SubscriptionPlans>, } #[derive(Debug, Clone)] pub struct SubscriptionPlans { pub subscription_provider_plan_id: String, pub name: String, pub description: Option<String>, } #[derive(Debug, Clone)] pub struct GetSubscriptionPlanPricesResponse { pub list: Vec<SubscriptionPlanPrices>, } #[derive(Debug, Clone)] pub struct SubscriptionPlanPrices { pub price_id: String, pub plan_id: Option<String>, pub amount: MinorUnit, pub currency: Currency, pub interval: PeriodUnit, pub interval_count: i64, pub trial_period: Option<i64>, pub trial_period_unit: Option<PeriodUnit>, } impl From<SubscriptionPlanPrices> for api_models::subscription::SubscriptionPlanPrices { fn from(item: SubscriptionPlanPrices) -> Self { Self { price_id: item.price_id, plan_id: item.plan_id, amount: item.amount, currency: item.currency, interval: item.interval.into(), interval_count: item.interval_count, trial_period: item.trial_period, trial_period_unit: item.trial_period_unit.map(Into::into), } } } #[derive(Debug, Clone)] pub enum PeriodUnit { Day, Week, Month, Year, } impl From<PeriodUnit> for api_models::subscription::PeriodUnit { fn from(unit: PeriodUnit) -> Self { match unit { PeriodUnit::Day => Self::Day, PeriodUnit::Week => Self::Week, PeriodUnit::Month => Self::Month, PeriodUnit::Year => Self::Year, } } } #[derive(Debug, Clone)] pub struct GetSubscriptionEstimateResponse { pub sub_total: MinorUnit, pub total: MinorUnit, pub credits_applied: Option<MinorUnit>, pub amount_paid: Option<MinorUnit>, pub amount_due: Option<MinorUnit>, pub currency: Currency, pub next_billing_at: Option<PrimitiveDateTime>, pub line_items: Vec<SubscriptionLineItem>, pub customer_id: Option<id_type::CustomerId>, } impl From<GetSubscriptionEstimateResponse> for api_models::subscription::EstimateSubscriptionResponse { fn from(value: GetSubscriptionEstimateResponse) -> Self { Self { amount: value.total, currency: value.currency, plan_id: None, item_price_id: None, coupon_code: None, customer_id: value.customer_id, line_items: value .line_items .into_iter() .map(api_models::subscription::SubscriptionLineItem::from) .collect(), } } } #[derive(Debug, Clone)] pub struct SubscriptionLineItem { pub item_id: String, pub item_type: String, pub description: String, pub amount: MinorUnit, pub currency: Currency, pub unit_amount: Option<MinorUnit>, pub quantity: i64, pub pricing_model: Option<String>, } impl From<SubscriptionLineItem> for api_models::subscription::SubscriptionLineItem { fn from(value: SubscriptionLineItem) -> Self { Self { item_id: value.item_id, description: value.description, item_type: value.item_type, amount: value.amount, currency: value.currency, quantity: value.quantity, } } }
crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs
hyperswitch_domain_models::src::router_response_types::subscriptions
1,128
true
// File: crates/hyperswitch_domain_models/src/router_response_types/fraud_check.rs // Module: hyperswitch_domain_models::src::router_response_types::fraud_check use serde::Serialize; use crate::router_response_types::ResponseId; #[derive(Debug, Clone, Serialize)] #[serde(untagged)] pub enum FraudCheckResponseData { TransactionResponse { resource_id: ResponseId, status: diesel_models::enums::FraudCheckStatus, connector_metadata: Option<serde_json::Value>, reason: Option<serde_json::Value>, score: Option<i32>, }, FulfillmentResponse { order_id: String, shipment_ids: Vec<String>, }, RecordReturnResponse { resource_id: ResponseId, connector_metadata: Option<serde_json::Value>, return_id: Option<String>, }, } impl common_utils::events::ApiEventMetric for FraudCheckResponseData { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::FraudCheck) } }
crates/hyperswitch_domain_models/src/router_response_types/fraud_check.rs
hyperswitch_domain_models::src::router_response_types::fraud_check
237
true
// File: crates/hyperswitch_domain_models/src/router_response_types/disputes.rs // Module: hyperswitch_domain_models::src::router_response_types::disputes #[derive(Default, Clone, Debug)] pub struct AcceptDisputeResponse { pub dispute_status: api_models::enums::DisputeStatus, pub connector_status: Option<String>, } #[derive(Default, Clone, Debug)] pub struct SubmitEvidenceResponse { pub dispute_status: api_models::enums::DisputeStatus, pub connector_status: Option<String>, } #[derive(Default, Debug, Clone)] pub struct DefendDisputeResponse { pub dispute_status: api_models::enums::DisputeStatus, pub connector_status: Option<String>, } pub struct FileInfo { pub file_data: Option<Vec<u8>>, pub provider_file_id: Option<String>, pub file_type: Option<String>, } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub struct DisputeSyncResponse { pub object_reference_id: api_models::webhooks::ObjectReferenceId, pub amount: common_utils::types::StringMinorUnit, pub currency: common_enums::enums::Currency, pub dispute_stage: common_enums::enums::DisputeStage, pub dispute_status: api_models::enums::DisputeStatus, pub connector_status: String, pub connector_dispute_id: String, pub connector_reason: Option<String>, pub connector_reason_code: Option<String>, pub challenge_required_by: Option<time::PrimitiveDateTime>, pub created_at: Option<time::PrimitiveDateTime>, pub updated_at: Option<time::PrimitiveDateTime>, } pub type FetchDisputesResponse = Vec<DisputeSyncResponse>;
crates/hyperswitch_domain_models/src/router_response_types/disputes.rs
hyperswitch_domain_models::src::router_response_types::disputes
361
true
// File: crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs // Module: hyperswitch_domain_models::src::router_response_types::revenue_recovery use common_utils::types::MinorUnit; use time::PrimitiveDateTime; #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct BillingConnectorPaymentsSyncResponse { /// transaction amount against invoice, accepted in minor unit. pub amount: MinorUnit, /// currency of the transaction pub currency: common_enums::enums::Currency, /// merchant reference id at billing connector. ex: invoice_id pub merchant_reference_id: common_utils::id_type::PaymentReferenceId, /// transaction id reference at payment connector pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// error code sent by billing connector. pub error_code: Option<String>, /// error message sent by billing connector. pub error_message: Option<String>, /// mandate token at payment processor end. pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. pub connector_customer_id: String, /// Payment gateway identifier id at billing processor. pub connector_account_reference_id: String, /// timestamp at which transaction has been created at billing connector pub transaction_created_at: Option<PrimitiveDateTime>, /// transaction status at billing connector equivalent to payment attempt status. pub status: common_enums::enums::AttemptStatus, /// payment method of payment attempt. pub payment_method_type: common_enums::enums::PaymentMethod, /// payment method sub type of the payment attempt. pub payment_method_sub_type: common_enums::enums::PaymentMethodType, /// stripe specific id used to validate duplicate attempts. pub charge_id: Option<String>, /// card information pub card_info: api_models::payments::AdditionalCardInfo, } #[derive(Debug, Clone)] pub struct InvoiceRecordBackResponse { pub merchant_reference_id: common_utils::id_type::PaymentReferenceId, } #[derive(Debug, Clone)] pub struct BillingConnectorInvoiceSyncResponse { /// transaction amount against invoice, accepted in minor unit. pub amount: MinorUnit, /// currency of the transaction pub currency: common_enums::enums::Currency, /// merchant reference id at billing connector. ex: invoice_id pub merchant_reference_id: common_utils::id_type::PaymentReferenceId, /// No of attempts made against an invoice pub retry_count: Option<u16>, /// Billing Address of the customer for Invoice pub billing_address: Option<api_models::payments::Address>, /// creation time of the invoice pub created_at: Option<PrimitiveDateTime>, /// Ending time of Invoice pub ends_at: Option<PrimitiveDateTime>, }
crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs
hyperswitch_domain_models::src::router_response_types::revenue_recovery
593
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/dispute.rs // Module: hyperswitch_domain_models::src::router_flow_types::dispute #[derive(Debug, Clone)] pub struct Accept; #[derive(Debug, Clone)] pub struct Evidence; #[derive(Debug, Clone)] pub struct Defend; #[derive(Debug, Clone)] pub struct Fetch; #[derive(Debug, Clone)] pub struct Dsync;
crates/hyperswitch_domain_models/src/router_flow_types/dispute.rs
hyperswitch_domain_models::src::router_flow_types::dispute
87
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/refunds.rs // Module: hyperswitch_domain_models::src::router_flow_types::refunds #[derive(Debug, Clone)] pub struct Execute; #[derive(Debug, Clone)] pub struct RSync;
crates/hyperswitch_domain_models/src/router_flow_types/refunds.rs
hyperswitch_domain_models::src::router_flow_types::refunds
56
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs // Module: hyperswitch_domain_models::src::router_flow_types::subscriptions use common_enums::connector_enums::InvoiceStatus; #[derive(Debug, Clone)] pub struct SubscriptionCreate; #[derive(Debug, Clone)] pub struct GetSubscriptionPlans; #[derive(Debug, Clone)] pub struct GetSubscriptionPlanPrices; #[derive(Debug, Clone)] pub struct GetSubscriptionEstimate; /// Generic structure for subscription MIT (Merchant Initiated Transaction) payment data #[derive(Debug, Clone)] pub struct SubscriptionMitPaymentData { pub invoice_id: common_utils::id_type::InvoiceId, pub amount_due: common_utils::types::MinorUnit, pub currency_code: common_enums::enums::Currency, pub status: Option<InvoiceStatus>, pub customer_id: common_utils::id_type::CustomerId, pub subscription_id: common_utils::id_type::SubscriptionId, pub first_invoice: bool, }
crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs
hyperswitch_domain_models::src::router_flow_types::subscriptions
207
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs // Module: hyperswitch_domain_models::src::router_flow_types::payouts #[derive(Debug, Clone)] pub struct PoCancel; #[derive(Debug, Clone)] pub struct PoCreate; #[derive(Debug, Clone)] pub struct PoEligibility; #[derive(Debug, Clone)] pub struct PoFulfill; #[derive(Debug, Clone)] pub struct PoQuote; #[derive(Debug, Clone)] pub struct PoRecipient; #[derive(Debug, Clone)] pub struct PoRecipientAccount; #[derive(Debug, Clone)] pub struct PoSync;
crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs
hyperswitch_domain_models::src::router_flow_types::payouts
129
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/fraud_check.rs // Module: hyperswitch_domain_models::src::router_flow_types::fraud_check #[derive(Debug, Clone)] pub struct Sale; #[derive(Debug, Clone)] pub struct Checkout; #[derive(Debug, Clone)] pub struct Transaction; #[derive(Debug, Clone)] pub struct Fulfillment; #[derive(Debug, Clone)] pub struct RecordReturn;
crates/hyperswitch_domain_models/src/router_flow_types/fraud_check.rs
hyperswitch_domain_models::src::router_flow_types::fraud_check
90
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/access_token_auth.rs // Module: hyperswitch_domain_models::src::router_flow_types::access_token_auth #[derive(Clone, Debug)] pub struct AccessTokenAuthentication; #[derive(Clone, Debug)] pub struct AccessTokenAuth;
crates/hyperswitch_domain_models/src/router_flow_types/access_token_auth.rs
hyperswitch_domain_models::src::router_flow_types::access_token_auth
59
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/payments.rs // Module: hyperswitch_domain_models::src::router_flow_types::payments // Core related api layer. #[derive(Debug, Clone)] pub struct Authorize; #[derive(Debug, Clone)] pub struct AuthorizeSessionToken; #[derive(Debug, Clone)] pub struct CompleteAuthorize; #[derive(Debug, Clone)] pub struct Approve; // Used in gift cards balance check #[derive(Debug, Clone)] pub struct Balance; #[derive(Debug, Clone)] pub struct InitPayment; #[derive(Debug, Clone)] pub struct Capture; #[derive(Debug, Clone)] pub struct PSync; #[derive(Debug, Clone)] pub struct Void; #[derive(Debug, Clone)] pub struct PostCaptureVoid; #[derive(Debug, Clone)] pub struct Reject; #[derive(Debug, Clone)] pub struct Session; #[derive(Debug, Clone)] pub struct PaymentMethodToken; #[derive(Debug, Clone)] pub struct CreateConnectorCustomer; #[derive(Debug, Clone)] pub struct SetupMandate; #[derive(Debug, Clone)] pub struct PreProcessing; #[derive(Debug, Clone)] pub struct IncrementalAuthorization; #[derive(Debug, Clone)] pub struct ExtendAuthorization; #[derive(Debug, Clone)] pub struct PostProcessing; #[derive(Debug, Clone)] pub struct CalculateTax; #[derive(Debug, Clone)] pub struct SdkSessionUpdate; #[derive(Debug, Clone)] pub struct PaymentCreateIntent; #[derive(Debug, Clone)] pub struct PaymentGetIntent; #[derive(Debug, Clone)] pub struct PaymentUpdateIntent; #[derive(Debug, Clone)] pub struct PostSessionTokens; #[derive(Debug, Clone)] pub struct RecordAttempt; #[derive(Debug, Clone)] pub struct UpdateMetadata; #[derive(Debug, Clone)] pub struct CreateOrder; #[derive(Debug, Clone)] pub struct PaymentGetListAttempts; #[derive(Debug, Clone)] pub struct ExternalVaultProxy; #[derive(Debug, Clone)] pub struct GiftCardBalanceCheck;
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
hyperswitch_domain_models::src::router_flow_types::payments
403
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rs // Module: hyperswitch_domain_models::src::router_flow_types::unified_authentication_service #[derive(Debug, Clone)] pub struct PreAuthenticate; #[derive(Debug, Clone)] pub struct PostAuthenticate; #[derive(Debug, Clone)] pub struct AuthenticationConfirmation; #[derive(Debug, Clone)] pub struct Authenticate;
crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rs
hyperswitch_domain_models::src::router_flow_types::unified_authentication_service
82
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/files.rs // Module: hyperswitch_domain_models::src::router_flow_types::files #[derive(Debug, Clone)] pub struct Retrieve; #[derive(Debug, Clone)] pub struct Upload;
crates/hyperswitch_domain_models/src/router_flow_types/files.rs
hyperswitch_domain_models::src::router_flow_types::files
53
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/mandate_revoke.rs // Module: hyperswitch_domain_models::src::router_flow_types::mandate_revoke #[derive(Clone, Debug)] pub struct MandateRevoke;
crates/hyperswitch_domain_models/src/router_flow_types/mandate_revoke.rs
hyperswitch_domain_models::src::router_flow_types::mandate_revoke
53
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/webhooks.rs // Module: hyperswitch_domain_models::src::router_flow_types::webhooks use serde::Serialize; #[derive(Clone, Debug)] pub struct VerifyWebhookSource; #[derive(Debug, Clone, Serialize)] pub struct ConnectorMandateDetails { pub connector_mandate_id: masking::Secret<String>, } #[derive(Debug, Clone, Serialize)] pub struct ConnectorNetworkTxnId(masking::Secret<String>); impl ConnectorNetworkTxnId { pub fn new(txn_id: masking::Secret<String>) -> Self { Self(txn_id) } pub fn get_id(&self) -> &masking::Secret<String> { &self.0 } }
crates/hyperswitch_domain_models/src/router_flow_types/webhooks.rs
hyperswitch_domain_models::src::router_flow_types::webhooks
162
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs // Module: hyperswitch_domain_models::src::router_flow_types::revenue_recovery #[derive(Debug, Clone)] pub struct BillingConnectorPaymentsSync; #[derive(Debug, Clone)] pub struct InvoiceRecordBack; #[derive(Debug, Clone)] pub struct BillingConnectorInvoiceSync;
crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs
hyperswitch_domain_models::src::router_flow_types::revenue_recovery
75
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs // Module: hyperswitch_domain_models::src::router_flow_types::authentication #[derive(Debug, Clone)] pub struct PreAuthentication; #[derive(Debug, Clone)] pub struct PreAuthenticationVersionCall; #[derive(Debug, Clone)] pub struct Authentication; #[derive(Debug, Clone)] pub struct PostAuthentication;
crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs
hyperswitch_domain_models::src::router_flow_types::authentication
78
true
// File: crates/hyperswitch_domain_models/src/router_flow_types/vault.rs // Module: hyperswitch_domain_models::src::router_flow_types::vault #[derive(Debug, Clone)] pub struct ExternalVaultInsertFlow; #[derive(Debug, Clone)] pub struct ExternalVaultRetrieveFlow; #[derive(Debug, Clone)] pub struct ExternalVaultDeleteFlow; #[derive(Debug, Clone)] pub struct ExternalVaultCreateFlow;
crates/hyperswitch_domain_models/src/router_flow_types/vault.rs
hyperswitch_domain_models::src::router_flow_types::vault
86
true
// File: crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs // Module: hyperswitch_domain_models::src::router_data_v2::flow_common_types use common_utils::{pii, types::MinorUnit}; use crate::{ payment_address::PaymentAddress, payment_method_data::ApplePayFlow, router_data::{ AccessToken, ConnectorResponseData, PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, }, }; #[derive(Debug, Clone)] pub struct PaymentFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub connector_customer: Option<String>, pub connector: String, pub payment_id: String, pub attempt_id: String, pub status: common_enums::AttemptStatus, pub payment_method: common_enums::PaymentMethod, pub description: Option<String>, pub address: PaymentAddress, pub auth_type: common_enums::AuthenticationType, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub amount_captured: Option<i64>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, pub access_token: Option<AccessToken>, pub session_token: Option<String>, pub reference_id: Option<String>, pub payment_method_token: Option<PaymentMethodToken>, pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>, pub preprocessing_id: Option<String>, /// This is the balance amount for gift cards or voucher pub payment_method_balance: Option<PaymentMethodBalance>, ///for switching between two different versions of the same connector pub connector_api_version: Option<String>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, pub test_mode: Option<bool>, pub connector_http_status_code: Option<u16>, pub external_latency: Option<u128>, /// Contains apple pay flow type simplified or manual pub apple_pay_flow: Option<ApplePayFlow>, /// This field is used to store various data regarding the response from connector pub connector_response: Option<ConnectorResponseData>, pub payment_method_status: Option<common_enums::PaymentMethodStatus>, } #[derive(Debug, Clone)] pub struct RefundFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub payment_id: String, pub attempt_id: String, pub status: common_enums::AttemptStatus, pub payment_method: common_enums::PaymentMethod, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub amount_captured: Option<i64>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, pub refund_id: String, } #[cfg(feature = "payouts")] #[derive(Debug, Clone)] pub struct PayoutFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub connector_customer: Option<String>, pub address: PaymentAddress, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub connector_wallets_details: Option<pii::SecretSerdeValue>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, pub payout_method_data: Option<api_models::payouts::PayoutMethodData>, pub quote_id: Option<String>, } #[cfg(feature = "frm")] #[derive(Debug, Clone)] pub struct FrmFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: String, pub attempt_id: String, pub payment_method: common_enums::enums::PaymentMethod, pub connector_request_reference_id: String, pub auth_type: common_enums::enums::AuthenticationType, pub connector_wallets_details: Option<pii::SecretSerdeValue>, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub amount_captured: Option<i64>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, } #[derive(Debug, Clone)] pub struct ExternalAuthenticationFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub address: PaymentAddress, } #[derive(Debug, Clone)] pub struct DisputesFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: String, pub attempt_id: String, pub payment_method: common_enums::enums::PaymentMethod, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub amount_captured: Option<i64>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, pub dispute_id: String, } #[derive(Debug, Clone)] pub struct MandateRevokeFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: common_utils::id_type::CustomerId, pub payment_id: Option<String>, } #[derive(Debug, Clone)] pub struct WebhookSourceVerifyData { pub merchant_id: common_utils::id_type::MerchantId, } #[derive(Debug, Clone)] pub struct AuthenticationTokenFlowData {} #[derive(Debug, Clone)] pub struct AccessTokenFlowData {} #[derive(Debug, Clone)] pub struct FilesFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: String, pub attempt_id: String, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub connector_request_reference_id: String, } #[derive(Debug, Clone)] pub struct InvoiceRecordBackData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct SubscriptionCustomerData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct SubscriptionCreateData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct GetSubscriptionPlansData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct GetSubscriptionPlanPricesData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct GetSubscriptionEstimateData { pub connector_meta_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct UasFlowData { pub authenticate_by: String, pub source_authentication_id: common_utils::id_type::AuthenticationId, } #[derive(Debug, Clone)] pub struct BillingConnectorPaymentsSyncFlowData; #[derive(Debug, Clone)] pub struct BillingConnectorInvoiceSyncFlowData; #[derive(Debug, Clone)] pub struct VaultConnectorFlowData { pub merchant_id: common_utils::id_type::MerchantId, } #[derive(Debug, Clone)] pub struct GiftCardBalanceCheckFlowData; #[derive(Debug, Clone)] pub struct ExternalVaultProxyFlowData { pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub connector_customer: Option<String>, pub payment_id: String, pub attempt_id: String, pub status: common_enums::AttemptStatus, pub payment_method: common_enums::PaymentMethod, pub description: Option<String>, pub address: PaymentAddress, pub auth_type: common_enums::AuthenticationType, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub amount_captured: Option<i64>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, pub access_token: Option<AccessToken>, pub session_token: Option<String>, pub reference_id: Option<String>, pub payment_method_token: Option<PaymentMethodToken>, pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>, pub preprocessing_id: Option<String>, /// This is the balance amount for gift cards or voucher pub payment_method_balance: Option<PaymentMethodBalance>, ///for switching between two different versions of the same connector pub connector_api_version: Option<String>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, pub test_mode: Option<bool>, pub connector_http_status_code: Option<u16>, pub external_latency: Option<u128>, /// Contains apple pay flow type simplified or manual pub apple_pay_flow: Option<ApplePayFlow>, /// This field is used to store various data regarding the response from connector pub connector_response: Option<ConnectorResponseData>, pub payment_method_status: Option<common_enums::PaymentMethodStatus>, }
crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
hyperswitch_domain_models::src::router_data_v2::flow_common_types
1,986
true
// File: crates/hyperswitch_domain_models/src/errors/api_error_response.rs // Module: hyperswitch_domain_models::src::errors::api_error_response use api_models::errors::types::Extra; use common_utils::errors::ErrorSwitch; use http::StatusCode; use crate::router_data; #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum ErrorType { InvalidRequestError, ObjectNotFound, RouterError, ProcessingError, BadGateway, ServerNotAvailable, DuplicateRequest, ValidationError, ConnectorError, LockTimeout, } // CE Connector Error Errors originating from connector's end // HE Hyperswitch Error Errors originating from Hyperswitch's end // IR Invalid Request Error Error caused due to invalid fields and values in API request // WE Webhook Error Errors related to Webhooks #[derive(Debug, Clone, router_derive::ApiError)] #[error(error_type_enum = ErrorType)] pub enum ApiErrorResponse { #[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "{code}: {message}", ignore = "status_code")] ExternalConnectorError { code: String, message: String, connector: String, status_code: u16, reason: Option<String>, }, #[error(error_type = ErrorType::ProcessingError, code = "CE_01", message = "Payment failed during authorization with connector. Retry payment")] PaymentAuthorizationFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_02", message = "Payment failed during authentication with connector. Retry payment")] PaymentAuthenticationFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_03", message = "Capture attempt failed while processing with connector")] PaymentCaptureFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_04", message = "The card data is invalid")] InvalidCardData { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_05", message = "The card has expired")] CardExpired { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_06", message = "Refund failed while processing with connector. Retry refund")] RefundFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_07", message = "Verification failed while processing with connector. Retry operation")] VerificationFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_08", message = "Dispute operation failed while processing with connector. Retry operation")] DisputeFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::LockTimeout, code = "HE_00", message = "Resource is busy. Please try again later.")] ResourceBusy, #[error(error_type = ErrorType::ServerNotAvailable, code = "HE_00", message = "Something went wrong")] InternalServerError, #[error(error_type = ErrorType::ServerNotAvailable, code= "HE_00", message = "{component} health check is failing with error: {message}")] HealthCheckError { component: &'static str, message: String, }, #[error(error_type = ErrorType::ValidationError, code = "HE_00", message = "Failed to convert currency to minor unit")] CurrencyConversionFailed, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate refund request. Refund already attempted with the refund ID")] DuplicateRefundRequest, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID")] DuplicateMandate, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant account with the specified details already exists in our records")] DuplicateMerchantAccount, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", 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 = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment method with the specified details already exists in our records")] DuplicatePaymentMethod, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment with the specified payment_id already exists in our records")] DuplicatePayment { payment_id: common_utils::id_type::PaymentId, }, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payout with the specified payout_id '{payout_id:?}' already exists in our records")] DuplicatePayout { payout_id: common_utils::id_type::PayoutId, }, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The config with the specified key already exists in our records")] DuplicateConfig, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Refund does not exist in our records")] RefundNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment Link does not exist in our records")] PaymentLinkNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Customer does not exist in our records")] CustomerNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Config key does not exist in our records.")] ConfigNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment does not exist in our records")] PaymentNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment method does not exist in our records")] PaymentMethodNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant account does not exist in our records")] MerchantAccountNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant connector account does not exist in our records")] MerchantConnectorAccountNotFound { id: String }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Business profile with the given id '{id}' does not exist in our records")] ProfileNotFound { id: String }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Profile acquirer with id '{profile_acquirer_id}' not found for profile '{profile_id}'.")] ProfileAcquirerNotFound { profile_acquirer_id: String, profile_id: String, }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Poll with the given id '{id}' does not exist in our records")] PollNotFound { id: String }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Resource ID does not exist in our records")] ResourceIdNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Mandate does not exist in our records")] MandateNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Authentication does not exist in our records")] AuthenticationNotFound { id: String }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Failed to update mandate")] MandateUpdateFailed, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "API Key does not exist in our records")] ApiKeyNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payout does not exist in our records")] PayoutNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Event does not exist in our records")] EventNotFound, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Invalid mandate id passed from connector")] MandateSerializationFailed, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Unable to parse the mandate identifier passed from connector")] MandateDeserializationFailed, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Return URL is not configured and not passed in payments request")] ReturnUrlUnavailable, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard")] RefundNotPossible { connector: String }, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Mandate Validation Failed" )] MandateValidationFailed { reason: String }, #[error(error_type= ErrorType::ValidationError, code = "HE_03", message = "The payment has not succeeded yet. Please pass a successful payment to initiate refund")] PaymentNotSucceeded, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified merchant connector account is disabled")] MerchantConnectorAccountDisabled, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "{code}: {message}")] PaymentBlockedError { code: u16, message: String, status: String, reason: String, }, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "File validation failed")] FileValidationFailed { reason: String }, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Dispute status validation failed")] DisputeStatusValidationFailed { reason: String }, #[error(error_type= ErrorType::ObjectNotFound, code = "HE_04", message = "Successful payment not found for the given payment id")] SuccessfulPaymentNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "The connector provided in the request is incorrect or not available")] IncorrectConnectorNameGiven, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Address does not exist in our records")] AddressNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Dispute does not exist in our records")] DisputeNotFound { dispute_id: String }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File does not exist in our records")] FileNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File not available")] FileNotAvailable, #[error(error_type = ErrorType::ProcessingError, code = "HE_05", message = "Missing tenant id")] MissingTenantId, #[error(error_type = ErrorType::ProcessingError, code = "HE_05", message = "Invalid tenant id: {tenant_id}")] InvalidTenant { tenant_id: String }, #[error(error_type = ErrorType::ValidationError, code = "HE_06", message = "Failed to convert amount to {amount_type} type")] AmountConversionFailed { amount_type: &'static str }, #[error(error_type = ErrorType::ServerNotAvailable, code = "IR_00", message = "{message:?}")] NotImplemented { message: NotImplementedMessage }, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_01", message = "API key not provided or invalid API key used" )] Unauthorized, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL")] InvalidRequestUrl, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_03", message = "The HTTP method is not applicable for this API")] InvalidHttpMethod, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_04", message = "Missing required param: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_05", message = "{field_name} contains invalid data. Expected format is {expected_format}" )] InvalidDataFormat { field_name: String, expected_format: String, }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_06", message = "{message}")] InvalidRequestData { message: String }, /// Typically used when a field has invalid value, or deserialization of the value contained in a field fails. #[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "Invalid value provided: {field_name}")] InvalidDataValue { field_name: &'static str }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret was not provided")] ClientSecretNotGiven, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret has expired")] ClientSecretExpired, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_09", message = "The client_secret provided does not match the client_secret associated with the Payment")] ClientSecretInvalid, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "Customer has active mandate/subsciption")] MandateActive, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_11", message = "Customer has already been redacted")] CustomerRedacted, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_12", message = "Reached maximum refund attempts")] MaximumRefundCount, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_13", message = "The refund amount exceeds the amount captured")] RefundAmountExceedsPaymentAmount, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_14", message = "This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}")] PaymentUnexpectedState { current_flow: String, field_name: String, current_value: String, states: String, }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_15", message = "Invalid Ephemeral Key for the customer")] InvalidEphemeralKey, /// Typically used when information involving multiple fields or previously provided information doesn't satisfy a condition. #[error(error_type = ErrorType::InvalidRequestError, code = "IR_16", message = "{message}")] PreconditionFailed { message: String }, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_17", message = "Access forbidden, invalid JWT token was used" )] InvalidJwtToken, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_18", message = "{message}", )] GenericUnauthorized { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")] NotSupported { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_20", message = "{flow} flow not supported by the {connector} connector")] FlowNotSupported { flow: String, connector: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_21", message = "Missing required params")] MissingRequiredFields { field_names: Vec<&'static str> }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_22", message = "Access forbidden. Not authorized to access this resource {resource}")] AccessForbidden { resource: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")] FileProviderNotSupported { message: String }, #[error( error_type = ErrorType::ProcessingError, code = "IR_24", message = "Invalid {wallet_name} wallet token" )] InvalidWalletToken { wallet_name: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")] PaymentMethodDeleteFailed, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_26", message = "Invalid Cookie" )] InvalidCookie, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_27", message = "Extended card info does not exist")] ExtendedCardInfoNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_28", message = "{message}")] CurrencyNotSupported { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_29", message = "{message}")] UnprocessableEntity { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_30", message = "Merchant connector account is configured with invalid {config}")] InvalidConnectorConfiguration { config: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_31", message = "Card with the provided iin does not exist")] InvalidCardIin, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_32", message = "The provided card IIN length is invalid, please provide an iin with 6 or 8 digits")] InvalidCardIinLength, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_33", message = "File not found / valid in the request")] MissingFile, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_34", message = "Dispute id not found in the request")] MissingDisputeId, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_35", message = "File purpose not found in the request or is invalid")] MissingFilePurpose, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_36", message = "File content type not found / valid")] MissingFileContentType, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_37", message = "{message}")] GenericNotFoundError { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_38", message = "{message}")] GenericDuplicateError { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_39", message = "required payment method is not configured or configured incorrectly for all configured connectors")] IncorrectPaymentMethodConfiguration, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_40", message = "{message}")] LinkConfigurationError { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_41", message = "Payout validation failed")] PayoutFailed { data: Option<serde_json::Value> }, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_42", message = "Cookies are not found in the request" )] CookieNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_43", message = "API does not support platform account operation")] PlatformAccountAuthNotSupported, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_44", message = "Invalid platform account operation")] InvalidPlatformOperation, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_45", message = "External vault failed during processing with connector")] ExternalVaultFailed, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_46", message = "Field {fields} doesn't match with the ones used during mandate creation")] MandatePaymentDataMismatch { fields: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_47", message = "Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}")] MaxFieldLengthViolated { connector: String, field_name: String, max_length: usize, received_length: usize, }, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")] WebhookAuthenticationFailed, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_02", message = "Bad request received in webhook")] WebhookBadRequest, #[error(error_type = ErrorType::RouterError, code = "WE_03", message = "There was some issue processing the webhook")] WebhookProcessingFailure, #[error(error_type = ErrorType::ObjectNotFound, code = "WE_04", message = "Webhook resource not found")] WebhookResourceNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Unable to process the webhook body")] WebhookUnprocessableEntity, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_06", message = "Merchant Secret set my merchant for webhook source verification is invalid")] WebhookInvalidMerchantSecret, #[error(error_type = ErrorType::ServerNotAvailable, code = "IE", message = "{reason} as data mismatched for {field_names}")] IntegrityCheckFailed { reason: String, field_names: String, connector_transaction_id: Option<String>, }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Tokenization record not found for the given token_id {id}")] TokenizationRecordNotFound { id: String }, #[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "Subscription operation: {operation} failed with connector")] SubscriptionError { operation: String }, } #[derive(Clone)] pub enum NotImplementedMessage { Reason(String), Default, } impl std::fmt::Debug for NotImplementedMessage { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Reason(message) => write!(fmt, "{message} is not implemented"), Self::Default => { write!( fmt, "This API is under development and will be made available soon." ) } } } } impl ::core::fmt::Display for ApiErrorResponse { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, r#"{{"error":{}}}"#, serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string()) ) } } impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponse { fn switch(&self) -> api_models::errors::types::ApiErrorResponse { use api_models::errors::types::{ApiError, ApiErrorResponse as AER}; match self { Self::ExternalConnectorError { code, message, connector, reason, status_code, } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.to_owned(), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)), Self::PaymentAuthorizationFailed { data } => { AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()}))) } Self::PaymentAuthenticationFailed { data } => { AER::BadRequest(ApiError::new("CE", 2, "Payment failed during authentication with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()}))) } Self::PaymentCaptureFailed { data } => { AER::BadRequest(ApiError::new("CE", 3, "Capture attempt failed while processing with connector", Some(Extra { data: data.clone(), ..Default::default()}))) } Self::InvalidCardData { data } => AER::BadRequest(ApiError::new("CE", 4, "The card data is invalid", Some(Extra { data: data.clone(), ..Default::default()}))), Self::CardExpired { data } => AER::BadRequest(ApiError::new("CE", 5, "The card has expired", Some(Extra { data: data.clone(), ..Default::default()}))), Self::RefundFailed { data } => AER::BadRequest(ApiError::new("CE", 6, "Refund failed while processing with connector. Retry refund", Some(Extra { data: data.clone(), ..Default::default()}))), Self::VerificationFailed { data } => { AER::BadRequest(ApiError::new("CE", 7, "Verification failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()}))) }, Self::DisputeFailed { data } => { AER::BadRequest(ApiError::new("CE", 8, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()}))) } Self::ResourceBusy => { AER::Unprocessable(ApiError::new("HE", 0, "There was an issue processing the webhook body", None)) } Self::CurrencyConversionFailed => { AER::Unprocessable(ApiError::new("HE", 0, "Failed to convert currency to minor unit", None)) } Self::InternalServerError => { AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None)) }, Self::HealthCheckError { message,component } => { AER::InternalServerError(ApiError::new("HE",0,format!("{component} health check failed with error: {message}"),None)) }, Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)), Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)), Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)), Self::DuplicateMerchantConnectorAccount { profile_id, connector_label: connector_name } => { AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_name}' already exists in our records"), None)) } Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)), Self::DuplicatePayment { payment_id } => { AER::BadRequest(ApiError::new("HE", 1, "The payment with the specified payment_id already exists in our records", Some(Extra {reason: Some(format!("{payment_id:?} already exists")), ..Default::default()}))) } Self::DuplicatePayout { payout_id } => { AER::BadRequest(ApiError::new("HE", 1, format!("The payout with the specified payout_id '{payout_id:?}' already exists in our records"), None)) } Self::DuplicateConfig => { AER::BadRequest(ApiError::new("HE", 1, "The config with the specified key already exists in our records", None)) } Self::RefundNotFound => { AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None)) } Self::PaymentLinkNotFound => { AER::NotFound(ApiError::new("HE", 2, "Payment Link does not exist in our records", None)) } Self::CustomerNotFound => { AER::NotFound(ApiError::new("HE", 2, "Customer does not exist in our records", None)) } Self::ConfigNotFound => { AER::NotFound(ApiError::new("HE", 2, "Config key does not exist in our records.", None)) }, Self::PaymentNotFound => { AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None)) } Self::PaymentMethodNotFound => { AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None)) } Self::MerchantAccountNotFound => { AER::NotFound(ApiError::new("HE", 2, "Merchant account does not exist in our records", None)) } Self::MerchantConnectorAccountNotFound {id } => { AER::NotFound(ApiError::new("HE", 2, "Merchant connector account does not exist in our records", Some(Extra {reason: Some(format!("{id} does not exist")), ..Default::default()}))) } Self::ProfileNotFound { id } => { AER::NotFound(ApiError::new("HE", 2, format!("Business profile with the given id {id} does not exist"), None)) } Self::ProfileAcquirerNotFound { profile_acquirer_id, profile_id } => { AER::NotFound(ApiError::new("HE", 2, format!("Profile acquirer with id '{profile_acquirer_id}' not found for profile '{profile_id}'."), None)) } Self::PollNotFound { .. } => { AER::NotFound(ApiError::new("HE", 2, "Poll does not exist in our records", None)) }, Self::ResourceIdNotFound => { AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None)) } Self::MandateNotFound => { AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None)) } Self::AuthenticationNotFound { .. } => { AER::NotFound(ApiError::new("HE", 2, "Authentication does not exist in our records", None)) }, Self::MandateUpdateFailed => { AER::InternalServerError(ApiError::new("HE", 2, "Mandate update failed", None)) }, Self::ApiKeyNotFound => { AER::NotFound(ApiError::new("HE", 2, "API Key does not exist in our records", None)) } Self::PayoutNotFound => { AER::NotFound(ApiError::new("HE", 2, "Payout does not exist in our records", None)) } Self::EventNotFound => { AER::NotFound(ApiError::new("HE", 2, "Event does not exist in our records", None)) } Self::MandateSerializationFailed | Self::MandateDeserializationFailed => { AER::InternalServerError(ApiError::new("HE", 3, "Something went wrong", None)) }, Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)), Self::RefundNotPossible { connector } => { AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None)) } Self::MandateValidationFailed { reason } => { AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.to_owned()), ..Default::default() }))) } Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)), Self::MerchantConnectorAccountDisabled => { AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None)) } Self::PaymentBlockedError { message, reason, .. } => AER::DomainError(ApiError::new("HE", 3, message, Some(Extra { reason: Some(reason.clone()), ..Default::default() }))), Self::FileValidationFailed { reason } => { AER::BadRequest(ApiError::new("HE", 3, format!("File validation failed {reason}"), None)) } Self::DisputeStatusValidationFailed { .. } => { AER::BadRequest(ApiError::new("HE", 3, "Dispute status validation failed", None)) } Self::SuccessfulPaymentNotFound => { AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None)) } Self::IncorrectConnectorNameGiven => { AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None)) } Self::AddressNotFound => { AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None)) }, Self::DisputeNotFound { .. } => { AER::NotFound(ApiError::new("HE", 4, "Dispute does not exist in our records", None)) }, Self::FileNotFound => { AER::NotFound(ApiError::new("HE", 4, "File does not exist in our records", None)) } Self::FileNotAvailable => { AER::NotFound(ApiError::new("HE", 4, "File not available", None)) } Self::MissingTenantId => { AER::InternalServerError(ApiError::new("HE", 5, "Missing Tenant ID in the request".to_string(), None)) } Self::InvalidTenant { tenant_id } => { AER::InternalServerError(ApiError::new("HE", 5, format!("Invalid Tenant {tenant_id}"), None)) } Self::AmountConversionFailed { amount_type } => { AER::InternalServerError(ApiError::new("HE", 6, format!("Failed to convert amount to {amount_type} type"), None)) } Self::NotImplemented { message } => { AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None)) } Self::Unauthorized => AER::Unauthorized(ApiError::new( "IR", 1, "API key not provided or invalid API key used", None )), Self::InvalidRequestUrl => { AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None)) } Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new( "IR", 3, "The HTTP method is not applicable for this API", None )), Self::MissingRequiredField { field_name } => AER::BadRequest( ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None), ), Self::InvalidDataFormat { field_name, expected_format, } => AER::Unprocessable(ApiError::new( "IR", 5, format!( "{field_name} contains invalid data. Expected format is {expected_format}" ), None )), Self::InvalidRequestData { message } => { AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None)) } Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new( "IR", 7, format!("Invalid value provided: {field_name}"), None )), Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new( "IR", 8, "client_secret was not provided", None )), Self::ClientSecretExpired => AER::BadRequest(ApiError::new( "IR", 8, "The provided client_secret has expired", None )), Self::ClientSecretInvalid => { AER::BadRequest(ApiError::new("IR", 9, "The client_secret provided does not match the client_secret associated with the Payment", None)) } Self::MandateActive => { AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None)) } Self::CustomerRedacted => { AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None)) } Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)), Self::RefundAmountExceedsPaymentAmount => { AER::BadRequest(ApiError::new("IR", 13, "The refund amount exceeds the amount captured", None)) } Self::PaymentUnexpectedState { current_flow, field_name, current_value, states, } => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)), Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)), Self::PreconditionFailed { message } => { AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None)) } Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)), Self::GenericUnauthorized { message } => { AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None)) }, Self::NotSupported { message } => { AER::BadRequest(ApiError::new("IR", 19, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()}))) }, Self::FlowNotSupported { flow, connector } => { AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message } Self::MissingRequiredFields { field_names } => AER::BadRequest( ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })), ), Self::AccessForbidden {resource} => { AER::ForbiddenCommonResource(ApiError::new("IR", 22, format!("Access forbidden. Not authorized to access this resource {resource}"), None)) }, Self::FileProviderNotSupported { message } => { AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None)) }, Self::InvalidWalletToken { wallet_name} => AER::Unprocessable(ApiError::new( "IR", 24, format!("Invalid {wallet_name} wallet token"), None )), Self::PaymentMethodDeleteFailed => { AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None)) } Self::InvalidCookie => { AER::BadRequest(ApiError::new("IR", 26, "Invalid Cookie", None)) } Self::ExtendedCardInfoNotFound => { AER::NotFound(ApiError::new("IR", 27, "Extended card info does not exist", None)) } Self::CurrencyNotSupported { message } => { AER::BadRequest(ApiError::new("IR", 28, message, None)) } Self::UnprocessableEntity {message} => AER::Unprocessable(ApiError::new("IR", 29, message.to_string(), None)), Self::InvalidConnectorConfiguration {config} => { AER::BadRequest(ApiError::new("IR", 30, format!("Merchant connector account is configured with invalid {config}"), None)) } Self::InvalidCardIin => AER::BadRequest(ApiError::new("IR", 31, "The provided card IIN does not exist", None)), Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("IR", 32, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)), Self::MissingFile => { AER::BadRequest(ApiError::new("IR", 33, "File not found in the request", None)) } Self::MissingDisputeId => { AER::BadRequest(ApiError::new("IR", 34, "Dispute id not found in the request", None)) } Self::MissingFilePurpose => { AER::BadRequest(ApiError::new("IR", 35, "File purpose not found in the request or is invalid", None)) } Self::MissingFileContentType => { AER::BadRequest(ApiError::new("IR", 36, "File content type not found", None)) } Self::GenericNotFoundError { message } => { AER::NotFound(ApiError::new("IR", 37, message, None)) }, Self::GenericDuplicateError { message } => { AER::BadRequest(ApiError::new("IR", 38, message, None)) } Self::IncorrectPaymentMethodConfiguration => { AER::BadRequest(ApiError::new("IR", 39, "No eligible connector was found for the current payment method configuration", None)) } Self::LinkConfigurationError { message } => { AER::BadRequest(ApiError::new("IR", 40, message, None)) }, Self::PayoutFailed { data } => { AER::BadRequest(ApiError::new("IR", 41, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()}))) }, Self::CookieNotFound => { AER::Unauthorized(ApiError::new("IR", 42, "Cookies are not found in the request", None)) }, Self::ExternalVaultFailed => { AER::BadRequest(ApiError::new("IR", 45, "External Vault failed while processing with connector.", None)) }, Self::MandatePaymentDataMismatch { fields} => { AER::BadRequest(ApiError::new("IR", 46, format!("Field {fields} doesn't match with the ones used during mandate creation"), Some(Extra {fields: Some(fields.to_owned()), ..Default::default()}))) //FIXME: error message } Self::MaxFieldLengthViolated { connector, field_name, max_length, received_length} => { AER::BadRequest(ApiError::new("IR", 47, format!("Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}"), Some(Extra {connector: Some(connector.to_string()), ..Default::default()}))) } Self::WebhookAuthenticationFailed => { AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None)) } Self::WebhookBadRequest => { AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None)) } Self::WebhookProcessingFailure => { AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None)) }, Self::WebhookResourceNotFound => { AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None)) } Self::WebhookUnprocessableEntity => { AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None)) }, Self::WebhookInvalidMerchantSecret => { AER::BadRequest(ApiError::new("WE", 6, "Merchant Secret set for webhook source verification is invalid", None)) } Self::IntegrityCheckFailed { reason, field_names, connector_transaction_id } => AER::InternalServerError(ApiError::new( "IE", 0, format!("{reason} as data mismatched for {field_names}"), Some(Extra { connector_transaction_id: connector_transaction_id.to_owned(), ..Default::default() }) )), Self::PlatformAccountAuthNotSupported => { AER::BadRequest(ApiError::new("IR", 43, "API does not support platform operation", None)) } Self::InvalidPlatformOperation => { AER::Unauthorized(ApiError::new("IR", 44, "Invalid platform account operation", None)) } Self::TokenizationRecordNotFound{ id } => { AER::NotFound(ApiError::new("HE", 2, format!("Tokenization record not found for the given token_id '{id}' "), None)) } Self::SubscriptionError { operation } => { AER::BadRequest(ApiError::new("CE", 9, format!("Subscription operation: {operation} failed with connector"), None)) } } } } impl actix_web::ResponseError for ApiErrorResponse { fn status_code(&self) -> StatusCode { ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).status_code() } fn error_response(&self) -> actix_web::HttpResponse { ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).error_response() } } impl From<ApiErrorResponse> for router_data::ErrorResponse { fn from(error: ApiErrorResponse) -> Self { Self { code: error.error_code(), message: error.error_message(), reason: None, status_code: match error { ApiErrorResponse::ExternalConnectorError { status_code, .. } => status_code, _ => 500, }, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, } } }
crates/hyperswitch_domain_models/src/errors/api_error_response.rs
hyperswitch_domain_models::src::errors::api_error_response
10,494
true
// File: crates/hyperswitch_domain_models/src/payouts/payouts.rs // Module: hyperswitch_domain_models::src::payouts::payouts use common_enums as storage_enums; use common_utils::{id_type, pii, types::MinorUnit}; use serde::{Deserialize, Serialize}; use storage_enums::MerchantStorageScheme; use time::PrimitiveDateTime; use super::payout_attempt::PayoutAttempt; #[cfg(feature = "olap")] use super::PayoutFetchConstraints; #[async_trait::async_trait] pub trait PayoutsInterface { type Error; async fn insert_payout( &self, _payout: PayoutsNew, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, Self::Error>; async fn find_payout_by_merchant_id_payout_id( &self, _merchant_id: &id_type::MerchantId, _payout_id: &id_type::PayoutId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, Self::Error>; async fn update_payout( &self, _this: &Payouts, _payout: PayoutsUpdate, _payout_attempt: &PayoutAttempt, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, Self::Error>; async fn find_optional_payout_by_merchant_id_payout_id( &self, _merchant_id: &id_type::MerchantId, _payout_id: &id_type::PayoutId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Option<Payouts>, Self::Error>; #[cfg(feature = "olap")] async fn filter_payouts_by_constraints( &self, _merchant_id: &id_type::MerchantId, _filters: &PayoutFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, Self::Error>; #[cfg(feature = "olap")] async fn filter_payouts_and_attempts( &self, _merchant_id: &id_type::MerchantId, _filters: &PayoutFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result< Vec<( Payouts, PayoutAttempt, Option<diesel_models::Customer>, Option<diesel_models::Address>, )>, Self::Error, >; #[cfg(feature = "olap")] async fn filter_payouts_by_time_range_constraints( &self, _merchant_id: &id_type::MerchantId, _time_range: &common_utils::types::TimeRange, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, Self::Error>; #[cfg(feature = "olap")] #[allow(clippy::too_many_arguments)] async fn get_total_count_of_filtered_payouts( &self, _merchant_id: &id_type::MerchantId, _active_payout_ids: &[id_type::PayoutId], _connector: Option<Vec<api_models::enums::PayoutConnectors>>, _currency: Option<Vec<storage_enums::Currency>>, _status: Option<Vec<storage_enums::PayoutStatus>>, _payout_method: Option<Vec<storage_enums::PayoutType>>, ) -> error_stack::Result<i64, Self::Error>; #[cfg(feature = "olap")] async fn filter_active_payout_ids_by_constraints( &self, _merchant_id: &id_type::MerchantId, _constraints: &PayoutFetchConstraints, ) -> error_stack::Result<Vec<id_type::PayoutId>, Self::Error>; } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Payouts { pub payout_id: id_type::PayoutId, pub merchant_id: id_type::MerchantId, pub customer_id: Option<id_type::CustomerId>, pub address_id: Option<String>, pub payout_type: Option<storage_enums::PayoutType>, pub payout_method_id: Option<String>, pub amount: MinorUnit, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub description: Option<String>, pub recurring: bool, pub auto_fulfill: bool, pub return_url: Option<String>, pub entity_type: storage_enums::PayoutEntityType, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub attempt_count: i16, pub profile_id: id_type::ProfileId, pub status: storage_enums::PayoutStatus, pub confirm: Option<bool>, pub payout_link_id: Option<String>, pub client_secret: Option<String>, pub priority: Option<storage_enums::PayoutSendPriority>, } #[derive(Clone, Debug, Eq, PartialEq)] pub struct PayoutsNew { pub payout_id: id_type::PayoutId, pub merchant_id: id_type::MerchantId, pub customer_id: Option<id_type::CustomerId>, pub address_id: Option<String>, pub payout_type: Option<storage_enums::PayoutType>, pub payout_method_id: Option<String>, pub amount: MinorUnit, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub description: Option<String>, pub recurring: bool, pub auto_fulfill: bool, pub return_url: Option<String>, pub entity_type: storage_enums::PayoutEntityType, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub attempt_count: i16, pub profile_id: id_type::ProfileId, pub status: storage_enums::PayoutStatus, pub confirm: Option<bool>, pub payout_link_id: Option<String>, pub client_secret: Option<String>, pub priority: Option<storage_enums::PayoutSendPriority>, } #[derive(Debug, Serialize, Deserialize)] pub enum PayoutsUpdate { Update { amount: MinorUnit, destination_currency: storage_enums::Currency, source_currency: storage_enums::Currency, description: Option<String>, recurring: bool, auto_fulfill: bool, return_url: Option<String>, entity_type: storage_enums::PayoutEntityType, metadata: Option<pii::SecretSerdeValue>, profile_id: Option<id_type::ProfileId>, status: Option<storage_enums::PayoutStatus>, confirm: Option<bool>, payout_type: Option<storage_enums::PayoutType>, address_id: Option<String>, customer_id: Option<id_type::CustomerId>, }, PayoutMethodIdUpdate { payout_method_id: String, }, RecurringUpdate { recurring: bool, }, AttemptCountUpdate { attempt_count: i16, }, StatusUpdate { status: storage_enums::PayoutStatus, }, } #[derive(Clone, Debug, Default)] pub struct PayoutsUpdateInternal { pub amount: Option<MinorUnit>, pub destination_currency: Option<storage_enums::Currency>, pub source_currency: Option<storage_enums::Currency>, pub description: Option<String>, pub recurring: Option<bool>, pub auto_fulfill: Option<bool>, pub return_url: Option<String>, pub entity_type: Option<storage_enums::PayoutEntityType>, pub metadata: Option<pii::SecretSerdeValue>, pub payout_method_id: Option<String>, pub profile_id: Option<id_type::ProfileId>, pub status: Option<storage_enums::PayoutStatus>, pub attempt_count: Option<i16>, pub confirm: Option<bool>, pub payout_type: Option<common_enums::PayoutType>, pub address_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, } impl From<PayoutsUpdate> for PayoutsUpdateInternal { fn from(payout_update: PayoutsUpdate) -> Self { match payout_update { PayoutsUpdate::Update { amount, destination_currency, source_currency, description, recurring, auto_fulfill, return_url, entity_type, metadata, profile_id, status, confirm, payout_type, address_id, customer_id, } => Self { amount: Some(amount), destination_currency: Some(destination_currency), source_currency: Some(source_currency), description, recurring: Some(recurring), auto_fulfill: Some(auto_fulfill), return_url, entity_type: Some(entity_type), metadata, profile_id, status, confirm, payout_type, address_id, customer_id, ..Default::default() }, PayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } => Self { payout_method_id: Some(payout_method_id), ..Default::default() }, PayoutsUpdate::RecurringUpdate { recurring } => Self { recurring: Some(recurring), ..Default::default() }, PayoutsUpdate::AttemptCountUpdate { attempt_count } => Self { attempt_count: Some(attempt_count), ..Default::default() }, PayoutsUpdate::StatusUpdate { status } => Self { status: Some(status), ..Default::default() }, } } }
crates/hyperswitch_domain_models/src/payouts/payouts.rs
hyperswitch_domain_models::src::payouts::payouts
2,084
true
// File: crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs // Module: hyperswitch_domain_models::src::payouts::payout_attempt use api_models::enums::PayoutConnectors; use common_enums as storage_enums; use common_utils::{ id_type, payout_method_utils, pii, types::{UnifiedCode, UnifiedMessage}, }; use serde::{Deserialize, Serialize}; use storage_enums::MerchantStorageScheme; use time::PrimitiveDateTime; use super::payouts::Payouts; #[async_trait::async_trait] pub trait PayoutAttemptInterface { type Error; async fn insert_payout_attempt( &self, _payout_attempt: PayoutAttemptNew, _payouts: &Payouts, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, Self::Error>; async fn update_payout_attempt( &self, _this: &PayoutAttempt, _payout_attempt_update: PayoutAttemptUpdate, _payouts: &Payouts, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, Self::Error>; async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, _merchant_id: &id_type::MerchantId, _payout_attempt_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, Self::Error>; async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, _merchant_id: &id_type::MerchantId, _connector_payout_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, Self::Error>; async fn find_payout_attempt_by_merchant_id_merchant_order_reference_id( &self, _merchant_id: &id_type::MerchantId, _merchant_order_reference_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, Self::Error>; async fn get_filters_for_payouts( &self, _payout: &[Payouts], _merchant_id: &id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutListFilters, Self::Error>; } #[derive(Clone, Debug, Eq, PartialEq)] pub struct PayoutListFilters { pub connector: Vec<PayoutConnectors>, pub currency: Vec<storage_enums::Currency>, pub status: Vec<storage_enums::PayoutStatus>, pub payout_method: Vec<storage_enums::PayoutType>, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct PayoutAttempt { pub payout_attempt_id: String, pub payout_id: id_type::PayoutId, pub customer_id: Option<id_type::CustomerId>, pub merchant_id: id_type::MerchantId, pub address_id: Option<String>, pub connector: Option<String>, pub connector_payout_id: Option<String>, pub payout_token: Option<String>, pub status: storage_enums::PayoutStatus, pub is_eligible: Option<bool>, pub error_message: Option<String>, pub error_code: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, pub profile_id: id_type::ProfileId, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub routing_info: Option<serde_json::Value>, pub unified_code: Option<UnifiedCode>, pub unified_message: Option<UnifiedMessage>, pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, pub merchant_order_reference_id: Option<String>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } #[derive(Clone, Debug, PartialEq)] pub struct PayoutAttemptNew { pub payout_attempt_id: String, pub payout_id: id_type::PayoutId, pub customer_id: Option<id_type::CustomerId>, pub merchant_id: id_type::MerchantId, pub address_id: Option<String>, pub connector: Option<String>, pub connector_payout_id: Option<String>, pub payout_token: Option<String>, pub status: storage_enums::PayoutStatus, pub is_eligible: Option<bool>, pub error_message: Option<String>, pub error_code: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub profile_id: id_type::ProfileId, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub routing_info: Option<serde_json::Value>, pub unified_code: Option<UnifiedCode>, pub unified_message: Option<UnifiedMessage>, pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, pub merchant_order_reference_id: Option<String>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub enum PayoutAttemptUpdate { StatusUpdate { connector_payout_id: Option<String>, status: storage_enums::PayoutStatus, error_message: Option<String>, error_code: Option<String>, is_eligible: Option<bool>, unified_code: Option<UnifiedCode>, unified_message: Option<UnifiedMessage>, payout_connector_metadata: Option<pii::SecretSerdeValue>, }, PayoutTokenUpdate { payout_token: String, }, BusinessUpdate { business_country: Option<storage_enums::CountryAlpha2>, business_label: Option<String>, address_id: Option<String>, customer_id: Option<id_type::CustomerId>, }, UpdateRouting { connector: String, routing_info: Option<serde_json::Value>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, }, AdditionalPayoutMethodDataUpdate { additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, }, } #[derive(Clone, Debug, Default)] pub struct PayoutAttemptUpdateInternal { pub payout_token: Option<String>, pub connector_payout_id: Option<String>, pub status: Option<storage_enums::PayoutStatus>, pub error_message: Option<String>, pub error_code: Option<String>, pub is_eligible: Option<bool>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub connector: Option<String>, pub routing_info: Option<serde_json::Value>, pub address_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub unified_code: Option<UnifiedCode>, pub unified_message: Option<UnifiedMessage>, pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal { fn from(payout_update: PayoutAttemptUpdate) -> Self { match payout_update { PayoutAttemptUpdate::PayoutTokenUpdate { payout_token } => Self { payout_token: Some(payout_token), ..Default::default() }, PayoutAttemptUpdate::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, } => Self { connector_payout_id, status: Some(status), error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, ..Default::default() }, PayoutAttemptUpdate::BusinessUpdate { business_country, business_label, address_id, customer_id, } => Self { business_country, business_label, address_id, customer_id, ..Default::default() }, PayoutAttemptUpdate::UpdateRouting { connector, routing_info, merchant_connector_id, } => Self { connector: Some(connector), routing_info, merchant_connector_id, ..Default::default() }, PayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, } => Self { additional_payout_method_data, ..Default::default() }, } } }
crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
hyperswitch_domain_models::src::payouts::payout_attempt
1,918
true
// File: crates/hyperswitch_connectors/src/types.rs // Module: hyperswitch_connectors::src::types #[cfg(feature = "v2")] use hyperswitch_domain_models::router_data_v2::RouterDataV2; #[cfg(feature = "payouts")] use hyperswitch_domain_models::types::{PayoutsData, PayoutsResponseData}; use hyperswitch_domain_models::{ router_data::{AccessToken, RouterData}, router_flow_types::{ authentication::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, }, Accept, AccessTokenAuth, Authorize, Capture, CreateOrder, Defend, Dsync, Evidence, Fetch, PSync, PostProcessing, PreProcessing, Retrieve, Session, Upload, Void, }, router_request_types::{ authentication::{ ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, PreAuthNRequestData, }, AcceptDisputeRequestData, AccessTokenRequestData, CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPostProcessingData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, RetrieveFileRequestData, SubmitEvidenceRequestData, UploadFileRequestData, }, router_response_types::{ AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, UploadFileResponse, }, }; #[cfg(feature = "frm")] use hyperswitch_domain_models::{ router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, }, router_response_types::fraud_check::FraudCheckResponseData, }; use hyperswitch_interfaces::api::ConnectorIntegration; pub(crate) type PaymentsSyncResponseRouterData<R> = ResponseRouterData<PSync, R, PaymentsSyncData, PaymentsResponseData>; pub(crate) type PaymentsResponseRouterData<R> = ResponseRouterData<Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>; pub(crate) type PaymentsCaptureResponseRouterData<R> = ResponseRouterData<Capture, R, PaymentsCaptureData, PaymentsResponseData>; pub(crate) type RefundsResponseRouterData<F, R> = ResponseRouterData<F, R, RefundsData, RefundsResponseData>; pub(crate) type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; pub(crate) type PaymentsCancelResponseRouterData<R> = ResponseRouterData<Void, R, PaymentsCancelData, PaymentsResponseData>; pub(crate) type PaymentsPreprocessingResponseRouterData<R> = ResponseRouterData<PreProcessing, R, PaymentsPreProcessingData, PaymentsResponseData>; pub(crate) type PaymentsSessionResponseRouterData<R> = ResponseRouterData<Session, R, PaymentsSessionData, PaymentsResponseData>; pub(crate) type CreateOrderResponseRouterData<R> = ResponseRouterData<CreateOrder, R, CreateOrderRequestData, PaymentsResponseData>; pub(crate) type AcceptDisputeRouterData = RouterData<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>; pub(crate) type SubmitEvidenceRouterData = RouterData<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>; pub(crate) type UploadFileRouterData = RouterData<Upload, UploadFileRequestData, UploadFileResponse>; pub(crate) type DefendDisputeRouterData = RouterData<Defend, DefendDisputeRequestData, DefendDisputeResponse>; pub(crate) type FetchDisputeRouterData = RouterData<Fetch, FetchDisputesRequestData, FetchDisputesResponse>; pub(crate) type DisputeSyncRouterData = RouterData<Dsync, DisputeSyncData, DisputeSyncResponse>; #[cfg(feature = "payouts")] pub(crate) type PayoutsResponseRouterData<F, R> = ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>; // TODO: Remove `ResponseRouterData` from router crate after all the related type aliases are moved to this crate. pub(crate) struct ResponseRouterData<Flow, R, Request, Response> { pub(crate) response: R, pub(crate) data: RouterData<Flow, Request, Response>, pub(crate) http_code: u16, } #[cfg(feature = "frm")] pub(crate) type FrmFulfillmentRouterData = RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>; #[cfg(feature = "frm")] pub(crate) type FrmCheckoutType = dyn ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData>; #[cfg(feature = "frm")] pub(crate) type FrmTransactionType = dyn ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData>; #[cfg(feature = "frm")] pub(crate) type FrmTransactionRouterData = RouterData<Transaction, FraudCheckTransactionData, FraudCheckResponseData>; #[cfg(feature = "frm")] pub(crate) type FrmFulfillmentType = dyn ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>; #[cfg(feature = "frm")] pub(crate) type FrmCheckoutRouterData = RouterData<Checkout, FraudCheckCheckoutData, FraudCheckResponseData>; #[cfg(feature = "v2")] pub(crate) struct ResponseRouterDataV2<Flow, R, ResourceCommonData, Request, Response> { pub response: R, pub data: RouterDataV2<Flow, ResourceCommonData, Request, Response>, #[allow(dead_code)] // Used for metadata passing but this is not read pub http_code: u16, } pub(crate) type PreAuthNRouterData = RouterData<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData>; pub(crate) type PreAuthNVersionCallRouterData = RouterData<PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData>; pub(crate) type ConnectorAuthenticationRouterData = RouterData<Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData>; pub(crate) type ConnectorPostAuthenticationRouterData = RouterData< PostAuthentication, ConnectorPostAuthenticationRequestData, AuthenticationResponseData, >; pub(crate) type ConnectorAuthenticationType = dyn ConnectorIntegration< Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData, >; pub(crate) type ConnectorPostAuthenticationType = dyn ConnectorIntegration< PostAuthentication, ConnectorPostAuthenticationRequestData, AuthenticationResponseData, >; pub(crate) type ConnectorPreAuthenticationType = dyn ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData>; pub(crate) type ConnectorPreAuthenticationVersionCallType = dyn ConnectorIntegration< PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData, >; pub(crate) type PaymentsPostProcessingRouterData = RouterData<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; #[cfg(feature = "frm")] pub(crate) type FrmSaleRouterData = RouterData<Sale, FraudCheckSaleData, FraudCheckResponseData>; #[cfg(feature = "frm")] pub(crate) type FrmRecordReturnRouterData = RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>; #[cfg(feature = "frm")] pub(crate) type FrmRecordReturnType = dyn ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>; #[cfg(feature = "frm")] pub(crate) type FrmSaleType = dyn ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData>; pub(crate) type RetrieveFileRouterData = RouterData<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>; #[cfg(feature = "payouts")] pub(crate) trait PayoutIndividualDetailsExt { type Error; fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error>; } #[cfg(feature = "payouts")] impl PayoutIndividualDetailsExt for api_models::payouts::PayoutIndividualDetails { type Error = error_stack::Report<hyperswitch_interfaces::errors::ConnectorError>; fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error> { self.external_account_account_holder_type .clone() .ok_or_else(crate::utils::missing_field_err( "external_account_account_holder_type", )) } }
crates/hyperswitch_connectors/src/types.rs
hyperswitch_connectors::src::types
1,817
true
// File: crates/hyperswitch_connectors/src/default_implementations.rs // Module: hyperswitch_connectors::src::default_implementations #[cfg(feature = "dummy_connector")] use common_enums::{CallConnectorAction, PaymentAction}; // impl api::PaymentIncrementalAuthorization for Helcim {} // impl api::ConnectorCustomer for Helcim {} // impl api::PaymentsPreProcessing for Helcim {} // impl api::PaymentReject for Helcim {} // impl api::PaymentApprove for Helcim {} use common_utils::errors::CustomResult; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::router_flow_types::{ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, }; #[cfg(feature = "dummy_connector")] use hyperswitch_domain_models::router_request_types::authentication::{ ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, PreAuthNRequestData, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::router_request_types::revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::router_response_types::revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, }; use hyperswitch_domain_models::{ router_data::AccessTokenAuthenticationResponse, router_flow_types::{ authentication::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, }, dispute::{Accept, Defend, Dsync, Evidence, Fetch}, files::{Retrieve, Upload}, mandate_revoke::MandateRevoke, payments::{ Approve, AuthorizeSessionToken, CalculateTax, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, ExtendAuthorization, GiftCardBalanceCheck, IncrementalAuthorization, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, UpdateMetadata, }, subscriptions::{GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans}, webhooks::VerifyWebhookSource, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, ExternalVaultProxy, ExternalVaultRetrieveFlow, InvoiceRecordBack, PostAuthenticate, PreAuthenticate, SubscriptionCreate as SubscriptionCreateFlow, }, router_request_types::{ authentication, revenue_recovery::InvoiceRecordBackRequest, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, ExternalVaultProxyPaymentsData, FetchDisputesRequestData, GiftCardBalanceCheckRequestData, MandateRevokeRequestData, PaymentsApproveData, PaymentsAuthenticateData, PaymentsCancelPostCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SubmitEvidenceRequestData, UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ revenue_recovery::InvoiceRecordBackResponse, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, TaxCalculationResponseData, UploadFileResponse, VaultResponseData, VerifyWebhookSourceResponseData, }, }; #[cfg(feature = "frm")] use hyperswitch_domain_models::{ router_flow_types::fraud_check::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, }, router_response_types::fraud_check::FraudCheckResponseData, }; #[cfg(feature = "payouts")] use hyperswitch_domain_models::{ router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, }, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; #[cfg(feature = "frm")] use hyperswitch_interfaces::api::fraud_check::{ FraudCheck, FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale, FraudCheckTransaction, }; #[cfg(feature = "payouts")] use hyperswitch_interfaces::api::payouts::{ PayoutCancel, PayoutCreate, PayoutEligibility, PayoutFulfill, PayoutQuote, PayoutRecipient, PayoutRecipientAccount, PayoutSync, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_interfaces::api::revenue_recovery as recovery_traits; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_interfaces::api::revenue_recovery::{ BillingConnectorInvoiceSyncIntegration, BillingConnectorPaymentsSyncIntegration, }; #[cfg(feature = "dummy_connector")] use hyperswitch_interfaces::api::ConnectorVerifyWebhookSource; use hyperswitch_interfaces::{ api::{ self, authentication::{ ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication, ConnectorPreAuthenticationVersionCall, ExternalAuthentication, }, disputes::{ AcceptDispute, DefendDispute, Dispute, DisputeSync, FetchDisputes, SubmitEvidence, }, files::{FileUpload, RetrieveFile, UploadFile}, payments::{ ConnectorCustomer, ExternalVaultProxyPaymentsCreateV1, PaymentApprove, PaymentAuthorizeSessionToken, PaymentExtendAuthorization, PaymentIncrementalAuthorization, PaymentPostCaptureVoid, PaymentPostSessionTokens, PaymentReject, PaymentSessionUpdate, PaymentUpdateMetadata, PaymentsAuthenticate, PaymentsCompleteAuthorize, PaymentsCreateOrder, PaymentsGiftCardBalanceCheck, PaymentsPostAuthenticate, PaymentsPostProcessing, PaymentsPreAuthenticate, PaymentsPreProcessing, TaxCalculation, }, revenue_recovery::RevenueRecovery, subscriptions::{ GetSubscriptionEstimateFlow, GetSubscriptionPlanPricesFlow, GetSubscriptionPlansFlow, SubscriptionCreate, SubscriptionRecordBackFlow, Subscriptions, }, vault::{ ExternalVault, ExternalVaultCreate, ExternalVaultDelete, ExternalVaultInsert, ExternalVaultRetrieve, }, ConnectorAuthenticationToken, ConnectorIntegration, ConnectorMandateRevoke, ConnectorRedirectResponse, ConnectorTransactionId, UasAuthentication, UasAuthenticationConfirmation, UasPostAuthentication, UasPreAuthentication, UnifiedAuthenticationService, }, errors::ConnectorError, }; macro_rules! default_imp_for_authorize_session_token { ($($path:ident::$connector:ident),*) => { $( impl PaymentAuthorizeSessionToken for $path::$connector {} impl ConnectorIntegration< AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData > for $path::$connector {} )* }; } default_imp_for_authorize_session_token!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::UnifiedAuthenticationService, connectors::Volt, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_calculate_tax { ($($path:ident::$connector:ident),*) => { $( impl TaxCalculation for $path::$connector {} impl ConnectorIntegration< CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData, > for $path::$connector {} )* }; } default_imp_for_calculate_tax!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Paybox, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nuvei, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Volt, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_session_update { ($($path:ident::$connector:ident),*) => { $( impl PaymentSessionUpdate for $path::$connector {} impl ConnectorIntegration< SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_session_update!( connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stripe, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::UnifiedAuthenticationService, connectors::Fiuu, connectors::Flexiti, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::Powertranz, connectors::Prophetpay, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::Deutschebank, connectors::Volt, connectors::CtpMastercard ); macro_rules! default_imp_for_post_session_tokens { ($($path:ident::$connector:ident),*) => { $( impl PaymentPostSessionTokens for $path::$connector {} impl ConnectorIntegration< PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_post_session_tokens!( connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Billwerk, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Square, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Fiuu, connectors::Flexiti, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Powertranz, connectors::Prophetpay, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Deutschebank, connectors::Volt, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_create_order { ($($path:ident::$connector:ident),*) => { $( impl PaymentsCreateOrder for $path::$connector {} impl ConnectorIntegration< CreateOrder, CreateOrderRequestData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_create_order!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Billwerk, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Rapyd, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Square, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Fiuu, connectors::Flexiti, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Worldpayvantiv, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Powertranz, connectors::Prophetpay, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Deutschebank, connectors::Vgs, connectors::Volt, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_update_metadata { ($($path:ident::$connector:ident),*) => { $( impl PaymentUpdateMetadata for $path::$connector {} impl ConnectorIntegration< UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_update_metadata!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Billwerk, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Paypal, connectors::Paysafe, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Square, connectors::Stax, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Nmi, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Payone, connectors::Fiuu, connectors::Flexiti, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Powertranz, connectors::Prophetpay, connectors::Riskified, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Deutschebank, connectors::Vgs, connectors::Volt, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_cancel_post_capture { ($($path:ident::$connector:ident),*) => { $( impl PaymentPostCaptureVoid for $path::$connector {} impl ConnectorIntegration< PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_cancel_post_capture!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Billwerk, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Paypal, connectors::Paysafe, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Square, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nmi, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Payone, connectors::Fiuu, connectors::Flexiti, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Powertranz, connectors::Prophetpay, connectors::Riskified, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Deutschebank, connectors::Vgs, connectors::Volt, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); use crate::connectors; macro_rules! default_imp_for_complete_authorize { ($($path:ident::$connector:ident),*) => { $( impl PaymentsCompleteAuthorize for $path::$connector {} impl ConnectorIntegration< CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_complete_authorize!( connectors::Silverflow, connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Boku, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Datatrans, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Payone, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Riskified, connectors::Santander, connectors::Sift, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Worldline, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_incremental_authorization { ($($path:ident::$connector:ident),*) => { $( impl PaymentIncrementalAuthorization for $path::$connector {} impl ConnectorIntegration< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_incremental_authorization!( connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wellsfargopayout, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_extend_authorization { ($($path:ident::$connector:ident),*) => { $( impl PaymentExtendAuthorization for $path::$connector {} impl ConnectorIntegration< ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_extend_authorization!( connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Billwerk, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Paysafe, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Square, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Nmi, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Payone, connectors::Fiuu, connectors::Flexiti, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Powertranz, connectors::Prophetpay, connectors::Riskified, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Deutschebank, connectors::Vgs, connectors::Volt, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_create_customer { ($($path:ident::$connector:ident),*) => { $( impl ConnectorCustomer for $path::$connector {} impl ConnectorIntegration< CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_create_customer!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Ebanx, connectors::Elavon, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payme, connectors::Payload, connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_connector_redirect_response { ($($path:ident::$connector:ident),*) => { $( impl ConnectorRedirectResponse for $path::$connector { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, _action: common_enums::enums::PaymentAction ) -> CustomResult<common_enums::enums::CallConnectorAction, ConnectorError> { Ok(common_enums::enums::CallConnectorAction::Trigger) } } )* }; } default_imp_for_connector_redirect_response!( connectors::Paysafe, connectors::Trustpayments, connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Boku, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nordea, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payone, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Worldline, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Volt, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_pre_authenticate_steps{ ($($path:ident::$connector:ident),*)=> { $( impl PaymentsPreAuthenticate for $path::$connector {} impl ConnectorIntegration< PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_pre_authenticate_steps!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Boku, connectors::Braintree, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Signifyd, connectors::Silverflow, connectors::Square, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Vgs, connectors::Volt, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_authenticate_steps{ ($($path:ident::$connector:ident),*)=> { $( impl PaymentsAuthenticate for $path::$connector {} impl ConnectorIntegration< Authenticate, PaymentsAuthenticateData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_authenticate_steps!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Boku, connectors::Braintree, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Signifyd, connectors::Silverflow, connectors::Square, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Vgs, connectors::Volt, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_post_authenticate_steps{ ($($path:ident::$connector:ident),*)=> { $( impl PaymentsPostAuthenticate for $path::$connector {} impl ConnectorIntegration< PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_post_authenticate_steps!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Boku, connectors::Braintree, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Signifyd, connectors::Silverflow, connectors::Square, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Vgs, connectors::Volt, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_pre_processing_steps{ ($($path:ident::$connector:ident),*)=> { $( impl PaymentsPreProcessing for $path::$connector {} impl ConnectorIntegration< PreProcessing, PaymentsPreProcessingData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_pre_processing_steps!( connectors::Trustpayments, connectors::Silverflow, connectors::Vgs, connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Billwerk, connectors::Bitpay, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nomupay, connectors::Noon, connectors::Novalnet, connectors::Nexinets, connectors::Opayo, connectors::Opennode, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payone, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Riskified, connectors::Santander, connectors::Sift, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_post_processing_steps{ ($($path:ident::$connector:ident),*)=> { $( impl PaymentsPostProcessing for $path::$connector {} impl ConnectorIntegration< PostProcessing, PaymentsPostProcessingData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_post_processing_steps!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_approve { ($($path:ident::$connector:ident),*) => { $( impl PaymentApprove for $path::$connector {} impl ConnectorIntegration< Approve, PaymentsApproveData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_approve!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nmi, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payone, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_reject { ($($path:ident::$connector:ident),*) => { $( impl PaymentReject for $path::$connector {} impl ConnectorIntegration< Reject, PaymentsRejectData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_reject!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payone, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_webhook_source_verification { ($($path:ident::$connector:ident),*) => { $( impl api::ConnectorVerifyWebhookSource for $path::$connector {} impl ConnectorIntegration< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, > for $path::$connector {} )* }; } default_imp_for_webhook_source_verification!( connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Ebanx, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_accept_dispute { ($($path:ident::$connector:ident),*) => { $( impl Dispute for $path::$connector {} impl AcceptDispute for $path::$connector {} impl ConnectorIntegration< Accept, AcceptDisputeRequestData, AcceptDisputeResponse, > for $path::$connector {} )* }; } default_imp_for_accept_dispute!( connectors::Vgs, connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_submit_evidence { ($($path:ident::$connector:ident),*) => { $( impl SubmitEvidence for $path::$connector {} impl ConnectorIntegration< Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse, > for $path::$connector {} )* }; } default_imp_for_submit_evidence!( connectors::Vgs, connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Payone, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_defend_dispute { ($($path:ident::$connector:ident),*) => { $( impl DefendDispute for $path::$connector {} impl ConnectorIntegration< Defend, DefendDisputeRequestData, DefendDisputeResponse, > for $path::$connector {} )* }; } default_imp_for_defend_dispute!( connectors::Vgs, connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Helcim, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_fetch_disputes { ($($path:ident::$connector:ident),*) => { $( impl FetchDisputes for $path::$connector {} impl ConnectorIntegration< Fetch, FetchDisputesRequestData, FetchDisputesResponse, > for $path::$connector {} )* }; } default_imp_for_fetch_disputes!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Blackhawknetwork, connectors::Calida, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, connectors::Braintree, connectors::Breadpay, connectors::Boku, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Forte, connectors::Flexiti, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, connectors::Loonio, connectors::Katapult, connectors::Helcim, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Payu, connectors::Paytm, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_dispute_sync { ($($path:ident::$connector:ident),*) => { $( impl DisputeSync for $path::$connector {} impl ConnectorIntegration< Dsync, DisputeSyncData, DisputeSyncResponse, > for $path::$connector {} )* }; } default_imp_for_dispute_sync!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Breadpay, connectors::Boku, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Forte, connectors::Flexiti, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, connectors::Loonio, connectors::Katapult, connectors::Helcim, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Payu, connectors::Paytm, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Multisafepay, connectors::Mpgs, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_file_upload { ($($path:ident::$connector:ident),*) => { $( impl FileUpload for $path::$connector {} impl UploadFile for $path::$connector {} impl ConnectorIntegration< Upload, UploadFileRequestData, UploadFileResponse, > for $path::$connector {} impl RetrieveFile for $path::$connector {} impl ConnectorIntegration< Retrieve, RetrieveFileRequestData, RetrieveFileResponse, > for $path::$connector {} )* }; } default_imp_for_file_upload!( connectors::Vgs, connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_payouts { ($($path:ident::$connector:ident),*) => { $( impl api::Payouts for $path::$connector {} )* }; } default_imp_for_payouts!( connectors::Paysafe, connectors::Affirm, connectors::Vgs, connectors::Aci, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Cryptopay, connectors::Datatrans, connectors::Coinbase, connectors::Coingate, connectors::Custombilling, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Nexinets, connectors::Nexixpay, connectors::Nordea, connectors::Opayo, connectors::Opennode, connectors::Paybox, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Square, connectors::Stax, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Volt, connectors::Worldline, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_create { ($($path:ident::$connector:ident),*) => { $( impl PayoutCreate for $path::$connector {} impl ConnectorIntegration< PoCreate, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_create!( connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nordea, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_retrieve { ($($path:ident::$connector:ident),*) => { $( impl PayoutSync for $path::$connector {} impl ConnectorIntegration< PoSync, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_retrieve!( connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Payone, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_eligibility { ($($path:ident::$connector:ident),*) => { $( impl PayoutEligibility for $path::$connector {} impl ConnectorIntegration< PoEligibility, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_eligibility!( connectors::Vgs, connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payone, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_fulfill { ($($path:ident::$connector:ident),*) => { $( impl PayoutFulfill for $path::$connector {} impl ConnectorIntegration< PoFulfill, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_fulfill!( connectors::Paysafe, connectors::Affirm, connectors::Vgs, connectors::Aci, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Netcetera, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nmi, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_cancel { ($($path:ident::$connector:ident),*) => { $( impl PayoutCancel for $path::$connector {} impl ConnectorIntegration< PoCancel, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_cancel!( connectors::Vgs, connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payone, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_quote { ($($path:ident::$connector:ident),*) => { $( impl PayoutQuote for $path::$connector {} impl ConnectorIntegration< PoQuote, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_quote!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payone, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_recipient { ($($path:ident::$connector:ident),*) => { $( impl PayoutRecipient for $path::$connector {} impl ConnectorIntegration< PoRecipient, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_recipient!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_recipient_account { ($($path:ident::$connector:ident),*) => { $( impl PayoutRecipientAccount for $path::$connector {} impl ConnectorIntegration< PoRecipientAccount, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_payouts_recipient_account!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_sale { ($($path:ident::$connector:ident),*) => { $( impl FraudCheckSale for $path::$connector {} impl ConnectorIntegration< Sale, FraudCheckSaleData, FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "frm")] default_imp_for_frm_sale!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nomupay, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_checkout { ($($path:ident::$connector:ident),*) => { $( impl FraudCheckCheckout for $path::$connector {} impl ConnectorIntegration< Checkout, FraudCheckCheckoutData, FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "frm")] default_imp_for_frm_checkout!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_transaction { ($($path:ident::$connector:ident),*) => { $( impl FraudCheckTransaction for $path::$connector {} impl ConnectorIntegration< Transaction, FraudCheckTransactionData, FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "frm")] default_imp_for_frm_transaction!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_fulfillment { ($($path:ident::$connector:ident),*) => { $( impl FraudCheckFulfillment for $path::$connector {} impl ConnectorIntegration< Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "frm")] default_imp_for_frm_fulfillment!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_record_return { ($($path:ident::$connector:ident),*) => { $( impl FraudCheckRecordReturn for $path::$connector {} impl ConnectorIntegration< RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "frm")] default_imp_for_frm_record_return!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stripe, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_revoking_mandates { ($($path:ident::$connector:ident),*) => { $( impl ConnectorMandateRevoke for $path::$connector {} impl ConnectorIntegration< MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData, > for $path::$connector {} )* }; } default_imp_for_revoking_mandates!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); macro_rules! default_imp_for_uas_pre_authentication { ($($path:ident::$connector:ident),*) => { $( impl UnifiedAuthenticationService for $path::$connector {} impl UasPreAuthentication for $path::$connector {} impl ConnectorIntegration< PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData > for $path::$connector {} )* }; } default_imp_for_uas_pre_authentication!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stripe, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_uas_post_authentication { ($($path:ident::$connector:ident),*) => { $( impl UasPostAuthentication for $path::$connector {} impl ConnectorIntegration< PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData > for $path::$connector {} )* }; } default_imp_for_uas_post_authentication!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, connectors::Plaid, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stripe, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_uas_authentication_confirmation { ($($path:ident::$connector:ident),*) => { $( impl UasAuthenticationConfirmation for $path::$connector {} impl ConnectorIntegration< AuthenticationConfirmation, UasConfirmationRequestData, UasAuthenticationResponseData > for $path::$connector {} )* }; } default_imp_for_uas_authentication_confirmation!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Paypal, connectors::Paysafe, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_connector_request_id { ($($path:ident::$connector:ident),*) => { $( impl ConnectorTransactionId for $path::$connector {} )* }; } default_imp_for_connector_request_id!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Amazonpay, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Nordea, connectors::Novalnet, connectors::Noon, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "frm")] macro_rules! default_imp_for_fraud_check { ($($path:ident::$connector:ident),*) => { $( impl FraudCheck for $path::$connector {} )* }; } #[cfg(feature = "frm")] default_imp_for_fraud_check!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Nordea, connectors::Novalnet, connectors::Noon, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Paypal, connectors::Paysafe, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Opennode, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_connector_authentication { ($($path:ident::$connector:ident),*) => { $( impl ExternalAuthentication for $path::$connector {} impl ConnectorAuthentication for $path::$connector {} impl ConnectorPreAuthentication for $path::$connector {} impl ConnectorPreAuthenticationVersionCall for $path::$connector {} impl ConnectorPostAuthentication for $path::$connector {} impl ConnectorIntegration< Authentication, authentication::ConnectorAuthenticationRequestData, AuthenticationResponseData, > for $path::$connector {} impl ConnectorIntegration< PreAuthentication, authentication::PreAuthNRequestData, AuthenticationResponseData, > for $path::$connector {} impl ConnectorIntegration< PreAuthenticationVersionCall, authentication::PreAuthNRequestData, AuthenticationResponseData, > for $path::$connector {} impl ConnectorIntegration< PostAuthentication, authentication::ConnectorPostAuthenticationRequestData, AuthenticationResponseData, > for $path::$connector {} )* }; } default_imp_for_connector_authentication!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Payone, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_uas_authentication { ($($path:ident::$connector:ident),*) => { $( impl UasAuthentication for $path::$connector {} impl ConnectorIntegration< Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData > for $path::$connector {} )* }; } default_imp_for_uas_authentication!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Payeezy, connectors::Payload, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Noon, connectors::Opayo, connectors::Opennode, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::Wise, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_revenue_recovery { ($($path:ident::$connector:ident),*) => { $( impl RevenueRecovery for $path::$connector {} )* }; } default_imp_for_revenue_recovery!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_subscriptions { ($($path:ident::$connector:ident),*) => { $( impl Subscriptions for $path::$connector {} impl GetSubscriptionPlansFlow for $path::$connector {} impl SubscriptionRecordBackFlow for $path::$connector {} impl SubscriptionCreate for $path::$connector {} impl ConnectorIntegration< GetSubscriptionPlans, GetSubscriptionPlansRequest, GetSubscriptionPlansResponse > for $path::$connector {} impl ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> for $path::$connector {} impl GetSubscriptionPlanPricesFlow for $path::$connector {} impl ConnectorIntegration< GetSubscriptionPlanPrices, GetSubscriptionPlanPricesRequest, GetSubscriptionPlanPricesResponse > for $path::$connector {} impl ConnectorIntegration< SubscriptionCreateFlow, SubscriptionCreateRequest, SubscriptionCreateResponse, > for $path::$connector {} impl GetSubscriptionEstimateFlow for $path::$connector {} impl ConnectorIntegration< GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse > for $path::$connector {} )* }; } default_imp_for_subscriptions!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(all(feature = "v2", feature = "revenue_recovery"))] macro_rules! default_imp_for_billing_connector_payment_sync { ($($path:ident::$connector:ident),*) => { $( impl recovery_traits::BillingConnectorPaymentsSyncIntegration for $path::$connector {} impl ConnectorIntegration< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse > for $path::$connector {} )* }; } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] default_imp_for_billing_connector_payment_sync!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stripe, connectors::Stax, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(all(feature = "v2", feature = "revenue_recovery"))] macro_rules! default_imp_for_revenue_recovery_record_back { ($($path:ident::$connector:ident),*) => { $( impl recovery_traits::RevenueRecoveryRecordBack for $path::$connector {} )* }; } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] default_imp_for_revenue_recovery_record_back!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stripe, connectors::Stax, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(all(feature = "v2", feature = "revenue_recovery"))] macro_rules! default_imp_for_billing_connector_invoice_sync { ($($path:ident::$connector:ident),*) => { $( impl recovery_traits::BillingConnectorInvoiceSyncIntegration for $path::$connector {} impl ConnectorIntegration< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse > for $path::$connector {} )* }; } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] default_imp_for_billing_connector_invoice_sync!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Elavon, connectors::Ebanx, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Nmi, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Signifyd, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Threedsecureio, connectors::Taxjar, connectors::Tesouro, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Vgs, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_external_vault { ($($path:ident::$connector:ident),*) => { $( impl ExternalVault for $path::$connector {} )* }; } default_imp_for_external_vault!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Barclaycard, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Signifyd, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_external_vault_insert { ($($path:ident::$connector:ident),*) => { $( impl ExternalVaultInsert for $path::$connector {} impl ConnectorIntegration< ExternalVaultInsertFlow, VaultRequestData, VaultResponseData, > for $path::$connector {} )* }; } default_imp_for_external_vault_insert!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Barclaycard, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Signifyd, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_gift_card_balance_check { ($($path:ident::$connector:ident),*) => { $( impl PaymentsGiftCardBalanceCheck for $path::$connector {} impl ConnectorIntegration< GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, > for $path::$connector {} )* }; } default_imp_for_gift_card_balance_check!( connectors::Aci, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Boku, connectors::Braintree, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Paysafe, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Signifyd, connectors::Silverflow, connectors::Square, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Vgs, connectors::Volt, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_external_vault_retrieve { ($($path:ident::$connector:ident),*) => { $( impl ExternalVaultRetrieve for $path::$connector {} impl ConnectorIntegration< ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData, > for $path::$connector {} )* }; } default_imp_for_external_vault_retrieve!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Barclaycard, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Signifyd, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_external_vault_delete { ($($path:ident::$connector:ident),*) => { $( impl ExternalVaultDelete for $path::$connector {} impl ConnectorIntegration< ExternalVaultDeleteFlow, VaultRequestData, VaultResponseData, > for $path::$connector {} )* }; } default_imp_for_external_vault_delete!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Barclaycard, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Signifyd, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Vgs, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_external_vault_create { ($($path:ident::$connector:ident),*) => { $( impl ExternalVaultCreate for $path::$connector {} impl ConnectorIntegration< ExternalVaultCreateFlow, VaultRequestData, VaultResponseData, > for $path::$connector {} )* }; } default_imp_for_external_vault_create!( connectors::Hyperwallet, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Barclaycard, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Signifyd, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Vgs, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_connector_authentication_token { ($($path:ident::$connector:ident),*) => { $( impl ConnectorAuthenticationToken for $path::$connector {} impl ConnectorIntegration< AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, > for $path::$connector {} )* }; } default_imp_for_connector_authentication_token!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Barclaycard, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Billwerk, connectors::Bitpay, connectors::Calida, connectors::Bluesnap, connectors::Blackhawknetwork, connectors::Boku, connectors::Braintree, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Juspaythreedsserver, connectors::Jpmorgan, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mpgs, connectors::Netcetera, connectors::Nomupay, connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Sift, connectors::Signifyd, connectors::Shift4, connectors::Silverflow, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Vgs, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_external_vault_proxy_payments_create { ($($path:ident::$connector:ident),*) => { $( impl ExternalVaultProxyPaymentsCreateV1 for $path::$connector {} impl ConnectorIntegration< ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_external_vault_proxy_payments_create!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Breadpay, connectors::Boku, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Vgs, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentsCompleteAuthorize for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorVerifyWebhookSource for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorCustomer for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorRedirectResponse for connectors::DummyConnector<T> { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, _action: PaymentAction, ) -> CustomResult<CallConnectorAction, ConnectorError> { Ok(CallConnectorAction::Trigger) } } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorTransactionId for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> Dispute for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> AcceptDispute for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> FileUpload for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> UploadFile for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> RetrieveFile for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> SubmitEvidence for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> DefendDispute for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> FetchDisputes for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Fetch, FetchDisputesRequestData, FetchDisputesResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> DisputeSync for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Dsync, DisputeSyncData, DisputeSyncResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentsGiftCardBalanceCheck for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentsPreProcessing for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentsPostProcessing for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::Payouts for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutCreate for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutSync for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutEligibility for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutFulfill for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutCancel for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutQuote for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutRecipient for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutRecipientAccount for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentApprove for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Approve, PaymentsApproveData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentReject for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Reject, PaymentsRejectData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> FraudCheck for connectors::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> FraudCheckSale for connectors::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> for connectors::DummyConnector<T> { } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> FraudCheckCheckout for connectors::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> for connectors::DummyConnector<T> { } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> FraudCheckTransaction for connectors::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData> for connectors::DummyConnector<T> { } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> FraudCheckFulfillment for connectors::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> for connectors::DummyConnector<T> { } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> FraudCheckRecordReturn for connectors::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentIncrementalAuthorization for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorMandateRevoke for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorPreAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorPreAuthenticationVersionCall for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorPostAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< PostAuthentication, ConnectorPostAuthenticationRequestData, AuthenticationResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentAuthorizeSessionToken for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> TaxCalculation for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentSessionUpdate for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentPostSessionTokens for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentsCreateOrder for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<CreateOrder, CreateOrderRequestData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentUpdateMetadata for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentPostCaptureVoid for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentExtendAuthorization for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> UasPreAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> UnifiedAuthenticationService for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> UasPostAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> UasAuthenticationConfirmation for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< AuthenticationConfirmation, UasConfirmationRequestData, UasAuthenticationResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> UasAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> RevenueRecovery for connectors::DummyConnector<T> {} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::revenue_recovery::BillingConnectorPaymentsSyncIntegration for connectors::DummyConnector<T> { } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, > for connectors::DummyConnector<T> { } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::revenue_recovery::RevenueRecoveryRecordBack for connectors::DummyConnector<T> { } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> for connectors::DummyConnector<T> { } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> BillingConnectorInvoiceSyncIntegration for connectors::DummyConnector<T> {} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalVault for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalVaultInsert for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalVaultRetrieve for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalVaultDelete for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<ExternalVaultDeleteFlow, VaultRequestData, VaultResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalVaultCreate for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData, VaultResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorAuthenticationToken for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalVaultProxyPaymentsCreateV1 for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> Subscriptions for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> GetSubscriptionPlanPricesFlow for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< GetSubscriptionPlanPrices, GetSubscriptionPlanPricesRequest, GetSubscriptionPlanPricesResponse, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> GetSubscriptionPlansFlow for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> SubscriptionRecordBackFlow for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< GetSubscriptionPlans, GetSubscriptionPlansRequest, GetSubscriptionPlansResponse, > for connectors::DummyConnector<T> { } #[cfg(all(feature = "dummy_connector", feature = "v1"))] impl<const T: u8> ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> SubscriptionCreate for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< SubscriptionCreateFlow, SubscriptionCreateRequest, SubscriptionCreateResponse, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> GetSubscriptionEstimateFlow for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse, > for connectors::DummyConnector<T> { }
crates/hyperswitch_connectors/src/default_implementations.rs
hyperswitch_connectors::src::default_implementations
64,700
true
// File: crates/hyperswitch_connectors/src/constants.rs // Module: hyperswitch_connectors::src::constants /// Header Constants pub(crate) mod headers { pub(crate) const ACCEPT: &str = "Accept"; pub(crate) const API_KEY: &str = "API-KEY"; pub(crate) const APIKEY: &str = "apikey"; pub(crate) const API_TOKEN: &str = "Api-Token"; pub(crate) const AUTHORIZATION: &str = "Authorization"; pub(crate) const CONTENT_TYPE: &str = "Content-Type"; pub(crate) const DATE: &str = "Date"; pub(crate) const IDEMPOTENCY_KEY: &str = "Idempotency-Key"; pub(crate) const MESSAGE_SIGNATURE: &str = "Message-Signature"; pub(crate) const MERCHANT_ID: &str = "Merchant-ID"; pub(crate) const MERCHANTID: &str = "MerchantID"; pub(crate) const MERCHANT_TOKEN: &str = "MerchantToken"; pub(crate) const REQUEST_ID: &str = "request-id"; pub(crate) const NONCE: &str = "nonce"; pub(crate) const TIMESTAMP: &str = "Timestamp"; pub(crate) const TOKEN: &str = "token"; pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version"; pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key"; pub(crate) const X_CC_VERSION: &str = "X-CC-Version"; pub(crate) const X_DATE: &str = "X-Date"; pub(crate) const X_LOGIN: &str = "X-Login"; pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key"; pub(crate) const X_TRANS_KEY: &str = "X-Trans-Key"; pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue"; pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate"; pub(crate) const X_VERSION: &str = "X-Version"; pub(crate) const X_API_KEY: &str = "X-Api-Key"; pub(crate) const CORRELATION_ID: &str = "Correlation-Id"; pub(crate) const WP_API_VERSION: &str = "WP-Api-Version"; pub(crate) const STRIPE_COMPATIBLE_CONNECT_ACCOUNT: &str = "Stripe-Account"; pub(crate) const SOURCE: &str = "Source"; pub(crate) const USER_AGENT: &str = "User-Agent"; pub(crate) const KEY: &str = "key"; pub(crate) const X_SIGNATURE: &str = "X-Signature"; pub(crate) const SOAP_ACTION: &str = "SOAPAction"; pub(crate) const X_PROFILE_ID: &str = "X-Profile-Id"; } /// Unsupported response type error message pub const UNSUPPORTED_ERROR_MESSAGE: &str = "Unsupported response type"; /// Error message for Authentication Error from the connector pub const CONNECTOR_UNAUTHORIZED_ERROR: &str = "Authentication Error from the connector"; /// Error message when Refund request has been voided. pub const REFUND_VOIDED: &str = "Refund request has been voided."; pub const LOW_BALANCE_ERROR_MESSAGE: &str = "Insufficient balance in the payment method"; pub const DUIT_NOW_BRAND_COLOR: &str = "#ED2E67"; pub const DUIT_NOW_BRAND_TEXT: &str = "MALAYSIA NATIONAL QR"; pub(crate) const CANNOT_CONTINUE_AUTH: &str = "Cannot continue with Authorization due to failed Liability Shift."; #[cfg(feature = "payouts")] pub(crate) const DEFAULT_NOTIFICATION_SCRIPT_LANGUAGE: &str = "en-US"; pub(crate) const PLAN_ITEM_TYPE: &str = "plan";
crates/hyperswitch_connectors/src/constants.rs
hyperswitch_connectors::src::constants
829
true
// File: crates/hyperswitch_connectors/src/connectors.rs // Module: hyperswitch_connectors::src::connectors pub mod aci; pub mod adyen; pub mod adyenplatform; pub mod affirm; pub mod airwallex; pub mod amazonpay; pub mod archipel; pub mod authipay; pub mod authorizedotnet; pub mod bambora; pub mod bamboraapac; pub mod bankofamerica; pub mod barclaycard; pub mod billwerk; pub mod bitpay; pub mod blackhawknetwork; pub mod bluesnap; pub mod boku; pub mod braintree; pub mod breadpay; pub mod calida; pub mod cashtocode; pub mod celero; pub mod chargebee; pub mod checkbook; pub mod checkout; pub mod coinbase; pub mod coingate; pub mod cryptopay; pub mod ctp_mastercard; pub mod custombilling; pub mod cybersource; pub mod datatrans; pub mod deutschebank; pub mod digitalvirgo; pub mod dlocal; #[cfg(feature = "dummy_connector")] pub mod dummyconnector; pub mod dwolla; pub mod ebanx; pub mod elavon; pub mod facilitapay; pub mod finix; pub mod fiserv; pub mod fiservemea; pub mod fiuu; pub mod flexiti; pub mod forte; pub mod getnet; pub mod gigadat; pub mod globalpay; pub mod globepay; pub mod gocardless; pub mod gpayments; pub mod helcim; pub mod hipay; pub mod hyperswitch_vault; pub mod hyperwallet; pub mod iatapay; pub mod inespay; pub mod itaubank; pub mod jpmorgan; pub mod juspaythreedsserver; pub mod katapult; pub mod klarna; pub mod loonio; pub mod mifinity; pub mod mollie; pub mod moneris; pub mod mpgs; pub mod multisafepay; pub mod netcetera; pub mod nexinets; pub mod nexixpay; pub mod nmi; pub mod nomupay; pub mod noon; pub mod nordea; pub mod novalnet; pub mod nuvei; pub mod opayo; pub mod opennode; pub mod paybox; pub mod payeezy; pub mod payload; pub mod payme; pub mod payone; pub mod paypal; pub mod paysafe; pub mod paystack; pub mod paytm; pub mod payu; pub mod peachpayments; pub mod phonepe; pub mod placetopay; pub mod plaid; pub mod powertranz; pub mod prophetpay; pub mod rapyd; pub mod razorpay; pub mod recurly; pub mod redsys; pub mod riskified; pub mod santander; pub mod shift4; pub mod sift; pub mod signifyd; pub mod silverflow; pub mod square; pub mod stax; pub mod stripe; pub mod stripebilling; pub mod taxjar; pub mod tesouro; pub mod threedsecureio; pub mod thunes; pub mod tokenex; pub mod tokenio; pub mod trustpay; pub mod trustpayments; pub mod tsys; pub mod unified_authentication_service; pub mod vgs; pub mod volt; pub mod wellsfargo; pub mod wellsfargopayout; pub mod wise; pub mod worldline; pub mod worldpay; pub mod worldpayvantiv; pub mod worldpayxml; pub mod xendit; pub mod zen; pub mod zsl; #[cfg(feature = "dummy_connector")] pub use self::dummyconnector::DummyConnector; pub use self::{ aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, affirm::Affirm, airwallex::Airwallex, amazonpay::Amazonpay, archipel::Archipel, authipay::Authipay, authorizedotnet::Authorizedotnet, bambora::Bambora, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica, barclaycard::Barclaycard, billwerk::Billwerk, bitpay::Bitpay, blackhawknetwork::Blackhawknetwork, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, breadpay::Breadpay, calida::Calida, cashtocode::Cashtocode, celero::Celero, chargebee::Chargebee, checkbook::Checkbook, checkout::Checkout, coinbase::Coinbase, coingate::Coingate, cryptopay::Cryptopay, ctp_mastercard::CtpMastercard, custombilling::Custombilling, cybersource::Cybersource, datatrans::Datatrans, deutschebank::Deutschebank, digitalvirgo::Digitalvirgo, dlocal::Dlocal, dwolla::Dwolla, ebanx::Ebanx, elavon::Elavon, facilitapay::Facilitapay, finix::Finix, fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu, flexiti::Flexiti, forte::Forte, getnet::Getnet, gigadat::Gigadat, globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, gpayments::Gpayments, helcim::Helcim, hipay::Hipay, hyperswitch_vault::HyperswitchVault, hyperwallet::Hyperwallet, iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, juspaythreedsserver::Juspaythreedsserver, katapult::Katapult, klarna::Klarna, loonio::Loonio, mifinity::Mifinity, mollie::Mollie, moneris::Moneris, mpgs::Mpgs, multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nexixpay::Nexixpay, nmi::Nmi, nomupay::Nomupay, noon::Noon, nordea::Nordea, novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payload::Payload, payme::Payme, payone::Payone, paypal::Paypal, paysafe::Paysafe, paystack::Paystack, paytm::Paytm, payu::Payu, peachpayments::Peachpayments, phonepe::Phonepe, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, santander::Santander, shift4::Shift4, sift::Sift, signifyd::Signifyd, silverflow::Silverflow, square::Square, stax::Stax, stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, tesouro::Tesouro, threedsecureio::Threedsecureio, thunes::Thunes, tokenex::Tokenex, tokenio::Tokenio, trustpay::Trustpay, trustpayments::Trustpayments, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, vgs::Vgs, volt::Volt, wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldline::Worldline, worldpay::Worldpay, worldpayvantiv::Worldpayvantiv, worldpayxml::Worldpayxml, xendit::Xendit, zen::Zen, zsl::Zsl, };
crates/hyperswitch_connectors/src/connectors.rs
hyperswitch_connectors::src::connectors
1,742
true
// File: crates/hyperswitch_connectors/src/lib.rs // Module: hyperswitch_connectors::src::lib //! Hyperswitch connectors pub mod connectors; pub mod constants; pub mod default_implementations; pub mod default_implementations_v2; pub mod metrics; pub mod types; pub mod utils;
crates/hyperswitch_connectors/src/lib.rs
hyperswitch_connectors::src::lib
68
true
// File: crates/hyperswitch_connectors/src/metrics.rs // Module: hyperswitch_connectors::src::metrics //! Metrics interface use router_env::{counter_metric, global_meter}; global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(CONNECTOR_RESPONSE_DESERIALIZATION_FAILURE, GLOBAL_METER);
crates/hyperswitch_connectors/src/metrics.rs
hyperswitch_connectors::src::metrics
69
true
// File: crates/hyperswitch_connectors/src/default_implementations_v2.rs // Module: hyperswitch_connectors::src::default_implementations_v2 use hyperswitch_domain_models::{ router_data::{AccessToken, AccessTokenAuthenticationResponse}, router_data_v2::{ flow_common_types::{ BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, DisputesFlowData, GiftCardBalanceCheckFlowData, InvoiceRecordBackData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, WebhookSourceVerifyData, }, AccessTokenFlowData, AuthenticationTokenFlowData, ExternalAuthenticationFlowData, FilesFlowData, VaultConnectorFlowData, }, router_flow_types::{ authentication::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, }, dispute::{Accept, Defend, Dsync, Evidence, Fetch}, files::{Retrieve, Upload}, mandate_revoke::MandateRevoke, payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, ExtendAuthorization, ExternalVaultProxy, GiftCardBalanceCheck, IncrementalAuthorization, PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, refunds::{Execute, RSync}, revenue_recovery::{ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack, }, webhooks::VerifyWebhookSource, AccessTokenAuth, AccessTokenAuthentication, ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, ExternalVaultRetrieveFlow, }, router_request_types::{ authentication, revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, ExternalVaultProxyPaymentsData, FetchDisputesRequestData, GiftCardBalanceCheckRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, SubmitEvidenceRequestData, UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, TaxCalculationResponseData, UploadFileResponse, VaultResponseData, VerifyWebhookSourceResponseData, }, }; #[cfg(feature = "frm")] use hyperswitch_domain_models::{ router_data_v2::FrmFlowData, router_flow_types::fraud_check::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, }, router_response_types::fraud_check::FraudCheckResponseData, }; #[cfg(feature = "payouts")] use hyperswitch_domain_models::{ router_data_v2::PayoutFlowData, router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, }, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; #[cfg(feature = "frm")] use hyperswitch_interfaces::api::fraud_check_v2::{ FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2, FraudCheckTransactionV2, FraudCheckV2, }; #[cfg(feature = "payouts")] use hyperswitch_interfaces::api::payouts_v2::{ PayoutCancelV2, PayoutCreateV2, PayoutEligibilityV2, PayoutFulfillV2, PayoutQuoteV2, PayoutRecipientAccountV2, PayoutRecipientV2, PayoutSyncV2, }; use hyperswitch_interfaces::{ api::{ authentication_v2::{ ConnectorAuthenticationV2, ConnectorPostAuthenticationV2, ConnectorPreAuthenticationV2, ConnectorPreAuthenticationVersionCallV2, ExternalAuthenticationV2, }, disputes_v2::{ AcceptDisputeV2, DefendDisputeV2, DisputeSyncV2, DisputeV2, FetchDisputesV2, SubmitEvidenceV2, }, files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2}, payments_v2::{ ConnectorCustomerV2, ExternalVaultProxyPaymentsCreate, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, PaymentAuthorizeV2, PaymentCaptureV2, PaymentCreateOrderV2, PaymentExtendAuthorizationV2, PaymentIncrementalAuthorizationV2, PaymentPostCaptureVoidV2, PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentUpdateMetadataV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2, PaymentsGiftCardBalanceCheckV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2, }, refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2}, revenue_recovery_v2::{ BillingConnectorInvoiceSyncIntegrationV2, BillingConnectorPaymentsSyncIntegrationV2, RevenueRecoveryRecordBackV2, RevenueRecoveryV2, }, vault_v2::{ ExternalVaultCreateV2, ExternalVaultDeleteV2, ExternalVaultInsertV2, ExternalVaultRetrieveV2, ExternalVaultV2, }, ConnectorAccessTokenV2, ConnectorAuthenticationTokenV2, ConnectorMandateRevokeV2, ConnectorVerifyWebhookSourceV2, }, connector_integration_v2::ConnectorIntegrationV2, }; use crate::connectors; macro_rules! default_imp_for_new_connector_integration_payment { ($($path:ident::$connector:ident),*) => { $( impl PaymentV2 for $path::$connector{} impl PaymentAuthorizeV2 for $path::$connector{} impl PaymentAuthorizeSessionTokenV2 for $path::$connector{} impl PaymentSyncV2 for $path::$connector{} impl PaymentVoidV2 for $path::$connector{} impl PaymentPostCaptureVoidV2 for $path::$connector{} impl PaymentApproveV2 for $path::$connector{} impl PaymentRejectV2 for $path::$connector{} impl PaymentCaptureV2 for $path::$connector{} impl PaymentSessionV2 for $path::$connector{} impl MandateSetupV2 for $path::$connector{} impl PaymentIncrementalAuthorizationV2 for $path::$connector{} impl PaymentExtendAuthorizationV2 for $path::$connector{} impl PaymentsCompleteAuthorizeV2 for $path::$connector{} impl PaymentTokenV2 for $path::$connector{} impl ConnectorCustomerV2 for $path::$connector{} impl PaymentsPreProcessingV2 for $path::$connector{} impl PaymentsGiftCardBalanceCheckV2 for $path::$connector{} impl PaymentsPostProcessingV2 for $path::$connector{} impl TaxCalculationV2 for $path::$connector{} impl PaymentSessionUpdateV2 for $path::$connector{} impl PaymentPostSessionTokensV2 for $path::$connector{} impl PaymentUpdateMetadataV2 for $path::$connector{} impl PaymentCreateOrderV2 for $path::$connector{} impl ExternalVaultV2 for $path::$connector{} impl ConnectorIntegrationV2<Authorize,PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData> for $path::$connector{} impl ConnectorIntegrationV2<PSync,PaymentFlowData, PaymentsSyncData, PaymentsResponseData> for $path::$connector{} impl ConnectorIntegrationV2<Void, PaymentFlowData, PaymentsCancelData, PaymentsResponseData> for $path::$connector{} impl ConnectorIntegrationV2<PostCaptureVoid, PaymentFlowData, PaymentsCancelPostCaptureData, PaymentsResponseData> for $path::$connector{} impl ConnectorIntegrationV2<Approve,PaymentFlowData, PaymentsApproveData, PaymentsResponseData> for $path::$connector{} impl ConnectorIntegrationV2<Reject,PaymentFlowData, PaymentsRejectData, PaymentsResponseData> for $path::$connector{} impl ConnectorIntegrationV2<Capture,PaymentFlowData, PaymentsCaptureData, PaymentsResponseData> for $path::$connector{} impl ConnectorIntegrationV2<Session,PaymentFlowData, PaymentsSessionData, PaymentsResponseData> for $path::$connector{} impl ConnectorIntegrationV2<SetupMandate,PaymentFlowData, SetupMandateRequestData, PaymentsResponseData> for $path::$connector{} impl ConnectorIntegrationV2< IncrementalAuthorization, PaymentFlowData, PaymentsIncrementalAuthorizationData, PaymentsResponseData, > for $path::$connector{} impl ConnectorIntegrationV2< ExtendAuthorization, PaymentFlowData, PaymentsExtendAuthorizationData, PaymentsResponseData, > for $path::$connector{} impl ConnectorIntegrationV2< CompleteAuthorize, PaymentFlowData, CompleteAuthorizeData, PaymentsResponseData, > for $path::$connector{} impl ConnectorIntegrationV2< PaymentMethodToken, PaymentFlowData, PaymentMethodTokenizationData, PaymentsResponseData, > for $path::$connector{} impl ConnectorIntegrationV2< CreateConnectorCustomer, PaymentFlowData, ConnectorCustomerData, PaymentsResponseData, > for $path::$connector{} impl ConnectorIntegrationV2< PreProcessing, PaymentFlowData, PaymentsPreProcessingData, PaymentsResponseData, > for $path::$connector{} impl ConnectorIntegrationV2< GiftCardBalanceCheck, GiftCardBalanceCheckFlowData, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, > for $path::$connector{} impl ConnectorIntegrationV2< PostProcessing, PaymentFlowData, PaymentsPostProcessingData, PaymentsResponseData, > for $path::$connector{} impl ConnectorIntegrationV2< AuthorizeSessionToken, PaymentFlowData, AuthorizeSessionTokenData, PaymentsResponseData > for $path::$connector{} impl ConnectorIntegrationV2< CalculateTax, PaymentFlowData, PaymentsTaxCalculationData, TaxCalculationResponseData, > for $path::$connector{} impl ConnectorIntegrationV2< SdkSessionUpdate, PaymentFlowData, SdkPaymentsSessionUpdateData, PaymentsResponseData, > for $path::$connector{} impl ConnectorIntegrationV2< PostSessionTokens, PaymentFlowData, PaymentsPostSessionTokensData, PaymentsResponseData, > for $path::$connector{} impl ConnectorIntegrationV2< UpdateMetadata, PaymentFlowData, PaymentsUpdateMetadataData, PaymentsResponseData, > for $path::$connector{} impl ConnectorIntegrationV2<CreateOrder, PaymentFlowData, CreateOrderRequestData, PaymentsResponseData> for $path::$connector{} )* }; } default_imp_for_new_connector_integration_payment!( connectors::Vgs, connectors::Airwallex, connectors::Amazonpay, connectors::Adyenplatform, connectors::Affirm, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_refund { ($($path:ident::$connector:ident),*) => { $( impl RefundV2 for $path::$connector{} impl RefundExecuteV2 for $path::$connector{} impl RefundSyncV2 for $path::$connector{} impl ConnectorIntegrationV2<Execute, RefundFlowData, RefundsData, RefundsResponseData> for $path::$connector{} impl ConnectorIntegrationV2<RSync, RefundFlowData, RefundsData, RefundsResponseData> for $path::$connector{} )* }; } default_imp_for_new_connector_integration_refund!( connectors::Hyperwallet, connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_connector_authentication_token { ($($path:ident::$connector:ident),*) => { $( impl ConnectorAuthenticationTokenV2 for $path::$connector{} impl ConnectorIntegrationV2<AccessTokenAuthentication, AuthenticationTokenFlowData, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse,> for $path::$connector{} )* }; } default_imp_for_new_connector_integration_connector_authentication_token!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Bluesnap, connectors::Boku, connectors::Braintree, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Payu, connectors::Peachpayments, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_connector_access_token { ($($path:ident::$connector:ident),*) => { $( impl ConnectorAccessTokenV2 for $path::$connector{} impl ConnectorIntegrationV2<AccessTokenAuth, AccessTokenFlowData, AccessTokenRequestData, AccessToken> for $path::$connector{} )* }; } default_imp_for_new_connector_integration_connector_access_token!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_accept_dispute { ($($path:ident::$connector:ident),*) => { $( impl DisputeV2 for $path::$connector {} impl AcceptDisputeV2 for $path::$connector {} impl ConnectorIntegrationV2< Accept, DisputesFlowData, AcceptDisputeRequestData, AcceptDisputeResponse, > for $path::$connector {} )* }; } default_imp_for_new_connector_integration_accept_dispute!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_fetch_disputes { ($($path:ident::$connector:ident),*) => { $( impl FetchDisputesV2 for $path::$connector {} impl ConnectorIntegrationV2< Fetch, DisputesFlowData, FetchDisputesRequestData, FetchDisputesResponse, > for $path::$connector {} )* }; } default_imp_for_new_connector_integration_fetch_disputes!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Boku, connectors::Braintree, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Plaid, connectors::Placetopay, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Signifyd, connectors::Silverflow, connectors::Square, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Vgs, connectors::Volt, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_dispute_sync { ($($path:ident::$connector:ident),*) => { $( impl DisputeSyncV2 for $path::$connector {} impl ConnectorIntegrationV2< Dsync, DisputesFlowData, DisputeSyncData, DisputeSyncResponse, > for $path::$connector {} )* }; } default_imp_for_new_connector_integration_dispute_sync!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Boku, connectors::Braintree, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Plaid, connectors::Placetopay, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Signifyd, connectors::Silverflow, connectors::Square, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Vgs, connectors::Volt, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_defend_dispute { ($($path:ident::$connector:ident),*) => { $( impl DefendDisputeV2 for $path::$connector {} impl ConnectorIntegrationV2< Defend, DisputesFlowData, DefendDisputeRequestData, DefendDisputeResponse, > for $path::$connector {} )* }; } default_imp_for_new_connector_integration_defend_dispute!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_submit_evidence { ($($path:ident::$connector:ident),*) => { $( impl SubmitEvidenceV2 for $path::$connector {} impl ConnectorIntegrationV2< Evidence, DisputesFlowData, SubmitEvidenceRequestData, SubmitEvidenceResponse, > for $path::$connector {} )* }; } default_imp_for_new_connector_integration_submit_evidence!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, connectors::Calida, connectors::Blackhawknetwork, connectors::Braintree, connectors::Breadpay, connectors::Boku, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, connectors::Loonio, connectors::Katapult, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Payu, connectors::Peachpayments, connectors::Paytm, connectors::Placetopay, connectors::Plaid, connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_file_upload { ($($path:ident::$connector:ident),*) => { $( impl FileUploadV2 for $path::$connector {} impl UploadFileV2 for $path::$connector {} impl ConnectorIntegrationV2< Upload, FilesFlowData, UploadFileRequestData, UploadFileResponse, > for $path::$connector {} impl RetrieveFileV2 for $path::$connector {} impl ConnectorIntegrationV2< Retrieve, FilesFlowData, RetrieveFileRequestData, RetrieveFileResponse, > for $path::$connector {} )* }; } default_imp_for_new_connector_integration_file_upload!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_new_connector_integration_payouts_create { ($($path:ident::$connector:ident),*) => { $( impl PayoutCreateV2 for $path::$connector {} impl ConnectorIntegrationV2< PoCreate, PayoutFlowData, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_new_connector_integration_payouts_create!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Nmi, connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_new_connector_integration_payouts_eligibility { ($($path:ident::$connector:ident),*) => { $( impl PayoutEligibilityV2 for $path::$connector {} impl ConnectorIntegrationV2< PoEligibility, PayoutFlowData, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_new_connector_integration_payouts_fulfill { ($($path:ident::$connector:ident),*) => { $( impl PayoutFulfillV2 for $path::$connector {} impl ConnectorIntegrationV2< PoFulfill, PayoutFlowData, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_new_connector_integration_payouts_cancel { ($($path:ident::$connector:ident),*) => { $( impl PayoutCancelV2 for $path::$connector {} impl ConnectorIntegrationV2< PoCancel, PayoutFlowData, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_new_connector_integration_payouts_cancel!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_new_connector_integration_payouts_quote { ($($path:ident::$connector:ident),*) => { $( impl PayoutQuoteV2 for $path::$connector {} impl ConnectorIntegrationV2< PoQuote, PayoutFlowData, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_new_connector_integration_payouts_quote!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_new_connector_integration_payouts_recipient { ($($path:ident::$connector:ident),*) => { $( impl PayoutRecipientV2 for $path::$connector {} impl ConnectorIntegrationV2< PoRecipient, PayoutFlowData, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_new_connector_integration_payouts_recipient!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_new_connector_integration_payouts_sync { ($($path:ident::$connector:ident),*) => { $( impl PayoutSyncV2 for $path::$connector {} impl ConnectorIntegrationV2< PoSync, PayoutFlowData, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_new_connector_integration_payouts_sync!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account { ($($path:ident::$connector:ident),*) => { $( impl PayoutRecipientAccountV2 for $path::$connector {} impl ConnectorIntegrationV2< PoRecipientAccount, PayoutFlowData, PayoutsData, PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_webhook_source_verification { ($($path:ident::$connector:ident),*) => { $( impl ConnectorVerifyWebhookSourceV2 for $path::$connector {} impl ConnectorIntegrationV2< VerifyWebhookSource, WebhookSourceVerifyData, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, > for $path::$connector {} )* }; } default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "frm")] macro_rules! default_imp_for_new_connector_integration_frm_sale { ($($path:ident::$connector:ident),*) => { $( impl FraudCheckSaleV2 for $path::$connector {} impl ConnectorIntegrationV2< Sale, FrmFlowData, FraudCheckSaleData, FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "frm")] default_imp_for_new_connector_integration_frm_sale!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "frm")] macro_rules! default_imp_for_new_connector_integration_frm_checkout { ($($path:ident::$connector:ident),*) => { $( impl FraudCheckCheckoutV2 for $path::$connector {} impl ConnectorIntegrationV2< Checkout, FrmFlowData, FraudCheckCheckoutData, FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "frm")] default_imp_for_new_connector_integration_frm_checkout!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "frm")] macro_rules! default_imp_for_new_connector_integration_frm_transaction { ($($path:ident::$connector:ident),*) => { $( impl FraudCheckTransactionV2 for $path::$connector {} impl ConnectorIntegrationV2< Transaction, FrmFlowData, FraudCheckTransactionData, FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "frm")] default_imp_for_new_connector_integration_frm_transaction!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "frm")] macro_rules! default_imp_for_new_connector_integration_frm_fulfillment { ($($path:ident::$connector:ident),*) => { $( impl FraudCheckFulfillmentV2 for $path::$connector {} impl ConnectorIntegrationV2< Fulfillment, FrmFlowData, FraudCheckFulfillmentData, FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "frm")] default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "frm")] macro_rules! default_imp_for_new_connector_integration_frm_record_return { ($($path:ident::$connector:ident),*) => { $( impl FraudCheckRecordReturnV2 for $path::$connector {} impl ConnectorIntegrationV2< RecordReturn, FrmFlowData, FraudCheckRecordReturnData, FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "frm")] default_imp_for_new_connector_integration_frm_record_return!( connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_revoking_mandates { ($($path:ident::$connector:ident),*) => { $( impl ConnectorMandateRevokeV2 for $path::$connector {} impl ConnectorIntegrationV2< MandateRevoke, MandateRevokeFlowData, MandateRevokeRequestData, MandateRevokeResponseData, > for $path::$connector {} )* }; } default_imp_for_new_connector_integration_revoking_mandates!( connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); #[cfg(feature = "frm")] macro_rules! default_imp_for_new_connector_integration_frm { ($($path:ident::$connector:ident),*) => { $( impl FraudCheckV2 for $path::$connector {} )* }; } #[cfg(feature = "frm")] default_imp_for_new_connector_integration_frm!( connectors::Loonio, connectors::Gigadat, connectors::Affirm, connectors::Paytm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Bambora, connectors::Bamboraapac, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Checkbook, connectors::Coinbase, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Inespay, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Mpgs, connectors::Mollie, connectors::Multisafepay, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Nomupay, connectors::Nordea, connectors::Novalnet, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payone, connectors::Paysafe, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Vgs, connectors::Volt, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_connector_authentication { ($($path:ident::$connector:ident),*) => { $( impl ExternalAuthenticationV2 for $path::$connector {} impl ConnectorAuthenticationV2 for $path::$connector {} impl ConnectorPreAuthenticationV2 for $path::$connector {} impl ConnectorPreAuthenticationVersionCallV2 for $path::$connector {} impl ConnectorPostAuthenticationV2 for $path::$connector {} impl ConnectorIntegrationV2< Authentication, ExternalAuthenticationFlowData, authentication::ConnectorAuthenticationRequestData, AuthenticationResponseData, > for $path::$connector {} impl ConnectorIntegrationV2< PreAuthentication, ExternalAuthenticationFlowData, authentication::PreAuthNRequestData, AuthenticationResponseData, > for $path::$connector {} impl ConnectorIntegrationV2< PreAuthenticationVersionCall, ExternalAuthenticationFlowData, authentication::PreAuthNRequestData, AuthenticationResponseData, > for $path::$connector {} impl ConnectorIntegrationV2< PostAuthentication, ExternalAuthenticationFlowData, authentication::ConnectorPostAuthenticationRequestData, AuthenticationResponseData, > for $path::$connector {} )* }; } default_imp_for_new_connector_integration_connector_authentication!( connectors::Loonio, connectors::Gigadat, connectors::Affirm, connectors::Paytm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Bambora, connectors::Bamboraapac, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Checkbook, connectors::Coinbase, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Inespay, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Mpgs, connectors::Mollie, connectors::Multisafepay, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nomupay, connectors::Nordea, connectors::Novalnet, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Paysafe, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Vgs, connectors::Volt, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_revenue_recovery { ($($path:ident::$connector:ident),*) => { $( impl RevenueRecoveryV2 for $path::$connector {} impl BillingConnectorPaymentsSyncIntegrationV2 for $path::$connector {} impl RevenueRecoveryRecordBackV2 for $path::$connector {} impl BillingConnectorInvoiceSyncIntegrationV2 for $path::$connector {} impl ConnectorIntegrationV2< InvoiceRecordBack, InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse, > for $path::$connector {} impl ConnectorIntegrationV2< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncFlowData, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, > for $path::$connector {} impl ConnectorIntegrationV2< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncFlowData, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, > for $path::$connector {} )* }; } default_imp_for_new_connector_integration_revenue_recovery!( connectors::Loonio, connectors::Gigadat, connectors::Affirm, connectors::Paytm, connectors::Airwallex, connectors::Amazonpay, connectors::Authipay, connectors::Bambora, connectors::Bamboraapac, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Checkbook, connectors::Coinbase, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Inespay, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Mpgs, connectors::Mollie, connectors::Multisafepay, connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, connectors::Nomupay, connectors::Nordea, connectors::Novalnet, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payone, connectors::Paysafe, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Stripe, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Vgs, connectors::Volt, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_external_vault { ($($path:ident::$connector:ident),*) => { $( impl ExternalVaultInsertV2 for $path::$connector {} impl ExternalVaultRetrieveV2 for $path::$connector {} impl ExternalVaultDeleteV2 for $path::$connector {} impl ExternalVaultCreateV2 for $path::$connector {} impl ConnectorIntegrationV2< ExternalVaultInsertFlow, VaultConnectorFlowData, VaultRequestData, VaultResponseData, > for $path::$connector {} impl ConnectorIntegrationV2< ExternalVaultRetrieveFlow, VaultConnectorFlowData, VaultRequestData, VaultResponseData, > for $path::$connector {} impl ConnectorIntegrationV2< ExternalVaultDeleteFlow, VaultConnectorFlowData, VaultRequestData, VaultResponseData, > for $path::$connector {} impl ConnectorIntegrationV2< ExternalVaultCreateFlow, VaultConnectorFlowData, VaultRequestData, VaultResponseData, > for $path::$connector {} )* }; } default_imp_for_new_connector_integration_external_vault!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Barclaycard, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Boku, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, connectors::Noon, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Nmi, connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Vgs, connectors::Volt, connectors::Worldline, connectors::Wise, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_new_connector_integration_external_vault_proxy { ($($path:ident::$connector:ident),*) => { $( impl ExternalVaultProxyPaymentsCreate for $path::$connector {} impl ConnectorIntegrationV2< ExternalVaultProxy, PaymentFlowData, ExternalVaultProxyPaymentsData, PaymentsResponseData> for $path::$connector {} )* }; } default_imp_for_new_connector_integration_external_vault_proxy!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Calida, connectors::Bluesnap, connectors::Braintree, connectors::Breadpay, connectors::Boku, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Vgs, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard );
crates/hyperswitch_connectors/src/default_implementations_v2.rs
hyperswitch_connectors::src::default_implementations_v2
32,060
true
// File: crates/hyperswitch_connectors/src/utils.rs // Module: hyperswitch_connectors::src::utils use std::{ collections::{HashMap, HashSet}, marker::PhantomData, str::FromStr, sync::LazyLock, }; use api_models::payments; #[cfg(feature = "payouts")] use api_models::payouts::PayoutVendorAccountDetails; use base64::Engine; use common_enums::{ enums, enums::{ AlbaniaStatesAbbreviation, AndorraStatesAbbreviation, AttemptStatus, AustraliaStatesAbbreviation, AustriaStatesAbbreviation, BelarusStatesAbbreviation, BelgiumStatesAbbreviation, BosniaAndHerzegovinaStatesAbbreviation, BrazilStatesAbbreviation, BulgariaStatesAbbreviation, CanadaStatesAbbreviation, CroatiaStatesAbbreviation, CzechRepublicStatesAbbreviation, DenmarkStatesAbbreviation, FinlandStatesAbbreviation, FranceStatesAbbreviation, FutureUsage, GermanyStatesAbbreviation, GreeceStatesAbbreviation, HungaryStatesAbbreviation, IcelandStatesAbbreviation, IndiaStatesAbbreviation, IrelandStatesAbbreviation, ItalyStatesAbbreviation, JapanStatesAbbreviation, LatviaStatesAbbreviation, LiechtensteinStatesAbbreviation, LithuaniaStatesAbbreviation, LuxembourgStatesAbbreviation, MaltaStatesAbbreviation, MoldovaStatesAbbreviation, MonacoStatesAbbreviation, MontenegroStatesAbbreviation, NetherlandsStatesAbbreviation, NewZealandStatesAbbreviation, NorthMacedoniaStatesAbbreviation, NorwayStatesAbbreviation, PhilippinesStatesAbbreviation, PolandStatesAbbreviation, PortugalStatesAbbreviation, RomaniaStatesAbbreviation, RussiaStatesAbbreviation, SanMarinoStatesAbbreviation, SerbiaStatesAbbreviation, SingaporeStatesAbbreviation, SlovakiaStatesAbbreviation, SloveniaStatesAbbreviation, SpainStatesAbbreviation, SwedenStatesAbbreviation, SwitzerlandStatesAbbreviation, ThailandStatesAbbreviation, UkraineStatesAbbreviation, UnitedKingdomStatesAbbreviation, UsStatesAbbreviation, }, }; use common_utils::{ consts::BASE64_ENGINE, errors::{CustomResult, ParsingError, ReportSwitchExt}, ext_traits::{OptionExt, StringExt, ValueExt}, id_type, pii::{self, Email, IpAddress}, types::{AmountConvertor, MinorUnit}, }; use error_stack::{report, ResultExt}; #[cfg(feature = "frm")] use hyperswitch_domain_models::router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, }; use hyperswitch_domain_models::{ address::{Address, AddressDetails, PhoneDetails}, mandates, network_tokenization::NetworkTokenNumber, payment_method_data::{ self, Card, CardDetailsForNetworkTransactionId, GooglePayPaymentMethodInfo, PaymentMethodData, }, router_data::{ ErrorResponse, L2L3Data, PaymentMethodToken, RecurringMandatePaymentData, RouterData as ConnectorRouterData, }, router_request_types::{ AuthenticationData, AuthoriseIntegrityObject, BrowserInformation, CaptureIntegrityObject, CompleteAuthorizeData, ConnectorCustomerData, ExternalVaultProxyPaymentsData, MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsSyncData, RefundIntegrityObject, RefundsData, ResponseId, SetupMandateRequestData, SyncIntegrityObject, }, router_response_types::{CaptureSyncResponse, PaymentsResponseData}, types::{OrderDetailsWithAmount, SetupMandateRouterData}, }; use hyperswitch_interfaces::{api, consts, errors, types::Response}; use image::{DynamicImage, ImageBuffer, ImageFormat, Luma, Rgba}; use masking::{ExposeInterface, PeekInterface, Secret}; use quick_xml::{ events::{BytesDecl, BytesText, Event}, Writer, }; use rand::Rng; use regex::Regex; use router_env::logger; use serde::{Deserialize, Serialize}; use serde_json::Value; use time::PrimitiveDateTime; use unicode_normalization::UnicodeNormalization; #[cfg(feature = "frm")] use crate::types::FrmTransactionRouterData; use crate::{constants::UNSUPPORTED_ERROR_MESSAGE, types::RefreshTokenRouterData}; type Error = error_stack::Report<errors::ConnectorError>; pub(crate) fn construct_not_supported_error_report( capture_method: enums::CaptureMethod, connector_name: &'static str, ) -> error_stack::Report<errors::ConnectorError> { errors::ConnectorError::NotSupported { message: capture_method.to_string(), connector: connector_name, } .into() } pub(crate) fn to_currency_base_unit_with_zero_decimal_check( amount: i64, currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { currency .to_currency_base_unit_with_zero_decimal_check(amount) .change_context(errors::ConnectorError::RequestEncodingFailed) } pub(crate) fn get_timestamp_in_milliseconds(datetime: &PrimitiveDateTime) -> i64 { let utc_datetime = datetime.assume_utc(); utc_datetime.unix_timestamp() * 1000 } pub(crate) fn get_amount_as_string( currency_unit: &api::CurrencyUnit, amount: i64, currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { let amount = match currency_unit { api::CurrencyUnit::Minor => amount.to_string(), api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?, }; Ok(amount) } pub(crate) fn base64_decode(data: String) -> Result<Vec<u8>, Error> { BASE64_ENGINE .decode(data) .change_context(errors::ConnectorError::ResponseDeserializationFailed) } pub(crate) fn to_currency_base_unit( amount: i64, currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { currency .to_currency_base_unit(amount) .change_context(errors::ConnectorError::ParsingFailed) } pub trait ConnectorErrorTypeMapping { fn get_connector_error_type( &self, _error_code: String, _error_message: String, ) -> ConnectorErrorType { ConnectorErrorType::UnknownError } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct ErrorCodeAndMessage { pub error_code: String, pub error_message: String, } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] //Priority of connector_error_type pub enum ConnectorErrorType { UserError = 2, BusinessError = 3, TechnicalError = 4, UnknownError = 1, } pub(crate) fn get_error_code_error_message_based_on_priority( connector: impl ConnectorErrorTypeMapping, error_list: Vec<ErrorCodeAndMessage>, ) -> Option<ErrorCodeAndMessage> { let error_type_list = error_list .iter() .map(|error| { connector .get_connector_error_type(error.error_code.clone(), error.error_message.clone()) }) .collect::<Vec<ConnectorErrorType>>(); let mut error_zip_list = error_list .iter() .zip(error_type_list.iter()) .collect::<Vec<(&ErrorCodeAndMessage, &ConnectorErrorType)>>(); error_zip_list.sort_by_key(|&(_, error_type)| error_type); error_zip_list .first() .map(|&(error_code_message, _)| error_code_message) .cloned() } pub trait MultipleCaptureSyncResponse { fn get_connector_capture_id(&self) -> String; fn get_capture_attempt_status(&self) -> AttemptStatus; fn is_capture_response(&self) -> bool; fn get_connector_reference_id(&self) -> Option<String> { None } fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>>; } pub(crate) fn construct_captures_response_hashmap<T>( capture_sync_response_list: Vec<T>, ) -> CustomResult<HashMap<String, CaptureSyncResponse>, errors::ConnectorError> where T: MultipleCaptureSyncResponse, { let mut hashmap = HashMap::new(); for capture_sync_response in capture_sync_response_list { let connector_capture_id = capture_sync_response.get_connector_capture_id(); if capture_sync_response.is_capture_response() { hashmap.insert( connector_capture_id.clone(), CaptureSyncResponse::Success { resource_id: ResponseId::ConnectorTransactionId(connector_capture_id), status: capture_sync_response.get_capture_attempt_status(), connector_response_reference_id: capture_sync_response .get_connector_reference_id(), amount: capture_sync_response .get_amount_captured() .change_context(errors::ConnectorError::AmountConversionFailed) .attach_printable( "failed to convert back captured response amount to minor unit", )?, }, ); } } Ok(hashmap) } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayWalletData { #[serde(rename = "type")] pub pm_type: String, pub description: String, pub info: GooglePayPaymentMethodInfo, pub tokenization_data: common_types::payments::GpayTokenizationData, } #[derive(Debug, Serialize)] pub struct CardMandateInfo { pub card_exp_month: Secret<String>, pub card_exp_year: Secret<String>, } impl TryFrom<payment_method_data::GooglePayWalletData> for GooglePayWalletData { type Error = common_utils::errors::ValidationError; fn try_from(data: payment_method_data::GooglePayWalletData) -> Result<Self, Self::Error> { let tokenization_data = match data.tokenization_data { common_types::payments::GpayTokenizationData::Encrypted(encrypted_data) => { common_types::payments::GpayTokenizationData::Encrypted( common_types::payments::GpayEcryptedTokenizationData { token_type: encrypted_data.token_type, token: encrypted_data.token, }, ) } common_types::payments::GpayTokenizationData::Decrypted(_) => { return Err(common_utils::errors::ValidationError::InvalidValue { message: "Expected encrypted tokenization data, got decrypted".to_string(), }); } }; Ok(Self { pm_type: data.pm_type, description: data.description, info: GooglePayPaymentMethodInfo { card_network: data.info.card_network, card_details: data.info.card_details, assurance_details: data.info.assurance_details, card_funding_source: data.info.card_funding_source, }, tokenization_data, }) } } pub(crate) fn get_amount_as_f64( currency_unit: &api::CurrencyUnit, amount: i64, currency: enums::Currency, ) -> Result<f64, error_stack::Report<errors::ConnectorError>> { let amount = match currency_unit { api::CurrencyUnit::Base => to_currency_base_unit_asf64(amount, currency)?, api::CurrencyUnit::Minor => u32::try_from(amount) .change_context(errors::ConnectorError::ParsingFailed)? .into(), }; Ok(amount) } pub(crate) fn to_currency_base_unit_asf64( amount: i64, currency: enums::Currency, ) -> Result<f64, error_stack::Report<errors::ConnectorError>> { currency .to_currency_base_unit_asf64(amount) .change_context(errors::ConnectorError::ParsingFailed) } pub(crate) fn to_connector_meta_from_secret<T>( connector_meta: Option<Secret<Value>>, ) -> Result<T, Error> where T: serde::de::DeserializeOwned, { let connector_meta_secret = connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?; let json = connector_meta_secret.expose(); json.parse_value(std::any::type_name::<T>()).switch() } pub(crate) fn is_manual_capture(capture_method: Option<enums::CaptureMethod>) -> bool { capture_method == Some(enums::CaptureMethod::Manual) || capture_method == Some(enums::CaptureMethod::ManualMultiple) } pub(crate) fn generate_random_bytes(length: usize) -> Vec<u8> { // returns random bytes of length n let mut rng = rand::thread_rng(); (0..length).map(|_| Rng::gen(&mut rng)).collect() } pub(crate) fn missing_field_err( message: &'static str, ) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> { Box::new(move || { errors::ConnectorError::MissingRequiredField { field_name: message, } .into() }) } pub(crate) fn handle_json_response_deserialization_failure( res: Response, connector: &'static str, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { crate::metrics::CONNECTOR_RESPONSE_DESERIALIZATION_FAILURE .add(1, router_env::metric_attributes!(("connector", connector))); let response_data = String::from_utf8(res.response.to_vec()) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; // check for whether the response is in json format match serde_json::from_str::<Value>(&response_data) { // in case of unexpected response but in json format Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?, // in case of unexpected response but in html or string format Err(error_msg) => { logger::error!(deserialization_error=?error_msg); logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data); Ok(ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), message: UNSUPPORTED_ERROR_MESSAGE.to_string(), reason: Some(response_data), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } } pub(crate) fn construct_not_implemented_error_report( capture_method: enums::CaptureMethod, connector_name: &str, ) -> error_stack::Report<errors::ConnectorError> { errors::ConnectorError::NotImplemented(format!("{capture_method} for {connector_name}")).into() } pub(crate) const SELECTED_PAYMENT_METHOD: &str = "Selected payment method"; pub(crate) fn get_unimplemented_payment_method_error_message(connector: &str) -> String { format!("{SELECTED_PAYMENT_METHOD} through {connector}") } pub(crate) fn to_connector_meta<T>(connector_meta: Option<Value>) -> Result<T, Error> where T: serde::de::DeserializeOwned, { let json = connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?; json.parse_value(std::any::type_name::<T>()).switch() } #[cfg(feature = "payouts")] pub(crate) fn to_payout_connector_meta<T>(connector_meta: Option<Value>) -> Result<T, Error> where T: serde::de::DeserializeOwned, { let json = connector_meta.ok_or_else(missing_field_err("payout_connector_meta_data"))?; json.parse_value(std::any::type_name::<T>()).switch() } pub(crate) fn convert_amount<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: MinorUnit, currency: enums::Currency, ) -> Result<T, error_stack::Report<errors::ConnectorError>> { amount_convertor .convert(amount, currency) .change_context(errors::ConnectorError::AmountConversionFailed) } pub(crate) fn validate_currency( request_currency: enums::Currency, merchant_config_currency: Option<enums::Currency>, ) -> Result<(), errors::ConnectorError> { let merchant_config_currency = merchant_config_currency.ok_or(errors::ConnectorError::NoConnectorMetaData)?; if request_currency != merchant_config_currency { Err(errors::ConnectorError::NotSupported { message: format!( "currency {request_currency} is not supported for this merchant account", ), connector: "Braintree", })? } Ok(()) } pub(crate) fn convert_back_amount_to_minor_units<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: T, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> { amount_convertor .convert_back(amount, currency) .change_context(errors::ConnectorError::AmountConversionFailed) } pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool { match status { AttemptStatus::AuthenticationFailed | AttemptStatus::AuthorizationFailed | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::Failure | AttemptStatus::Expired => true, AttemptStatus::Started | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationPending | AttemptStatus::AuthenticationSuccessful | AttemptStatus::Authorized | AttemptStatus::Charged | AttemptStatus::Authorizing | AttemptStatus::CodInitiated | AttemptStatus::Voided | AttemptStatus::VoidedPostCharge | AttemptStatus::VoidInitiated | AttemptStatus::CaptureInitiated | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::Unresolved | AttemptStatus::Pending | AttemptStatus::PaymentMethodAwaited | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending | AttemptStatus::IntegrityFailure | AttemptStatus::PartiallyAuthorized => false, } } pub fn is_refund_failure(status: enums::RefundStatus) -> bool { match status { common_enums::RefundStatus::Failure | common_enums::RefundStatus::TransactionFailure => { true } common_enums::RefundStatus::ManualReview | common_enums::RefundStatus::Pending | common_enums::RefundStatus::Success => false, } } // TODO: Make all traits as `pub(crate) trait` once all connectors are moved. pub trait RouterData { fn get_billing(&self) -> Result<&Address, Error>; fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error>; fn get_billing_phone(&self) -> Result<&PhoneDetails, Error>; fn get_description(&self) -> Result<String, Error>; fn get_billing_address(&self) -> Result<&AddressDetails, Error>; fn get_shipping_address(&self) -> Result<&AddressDetails, Error>; fn get_shipping_address_with_phone_number(&self) -> Result<&Address, Error>; fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error>; fn get_session_token(&self) -> Result<String, Error>; fn get_billing_first_name(&self) -> Result<Secret<String>, Error>; fn get_billing_full_name(&self) -> Result<Secret<String>, Error>; fn get_billing_last_name(&self) -> Result<Secret<String>, Error>; fn get_billing_line1(&self) -> Result<Secret<String>, Error>; fn get_billing_line2(&self) -> Result<Secret<String>, Error>; fn get_billing_zip(&self) -> Result<Secret<String>, Error>; fn get_billing_state(&self) -> Result<Secret<String>, Error>; fn get_billing_state_code(&self) -> Result<Secret<String>, Error>; fn get_billing_city(&self) -> Result<String, Error>; fn get_billing_email(&self) -> Result<Email, Error>; fn get_billing_phone_number(&self) -> Result<Secret<String>, Error>; fn to_connector_meta<T>(&self) -> Result<T, Error> where T: serde::de::DeserializeOwned; fn is_three_ds(&self) -> bool; fn get_payment_method_token(&self) -> Result<PaymentMethodToken, Error>; fn get_customer_id(&self) -> Result<id_type::CustomerId, Error>; fn get_optional_customer_id(&self) -> Option<id_type::CustomerId>; fn get_connector_customer_id(&self) -> Result<String, Error>; fn get_preprocessing_id(&self) -> Result<String, Error>; fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error>; #[cfg(feature = "payouts")] fn get_payout_method_data(&self) -> Result<api_models::payouts::PayoutMethodData, Error>; #[cfg(feature = "payouts")] fn get_quote_id(&self) -> Result<String, Error>; fn get_optional_billing(&self) -> Option<&Address>; fn get_optional_shipping(&self) -> Option<&Address>; fn get_optional_shipping_line1(&self) -> Option<Secret<String>>; fn get_optional_shipping_line2(&self) -> Option<Secret<String>>; fn get_optional_shipping_line3(&self) -> Option<Secret<String>>; fn get_optional_shipping_city(&self) -> Option<String>; fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2>; fn get_optional_shipping_zip(&self) -> Option<Secret<String>>; fn get_optional_shipping_state(&self) -> Option<Secret<String>>; fn get_optional_shipping_first_name(&self) -> Option<Secret<String>>; fn get_optional_shipping_last_name(&self) -> Option<Secret<String>>; fn get_optional_shipping_full_name(&self) -> Option<Secret<String>>; fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>>; fn get_optional_shipping_phone_number_without_country_code(&self) -> Option<Secret<String>>; fn get_optional_shipping_email(&self) -> Option<Email>; fn get_required_shipping_full_name(&self) -> Result<Secret<String>, Error>; fn get_required_shipping_line1(&self) -> Result<Secret<String>, Error>; fn get_required_shipping_city(&self) -> Result<String, Error>; fn get_required_shipping_state(&self) -> Result<Secret<String>, Error>; fn get_required_shipping_zip(&self) -> Result<Secret<String>, Error>; fn get_required_shipping_phone_number(&self) -> Result<Secret<String>, Error>; fn get_optional_billing_full_name(&self) -> Option<Secret<String>>; fn get_optional_billing_line1(&self) -> Option<Secret<String>>; fn get_optional_billing_line3(&self) -> Option<Secret<String>>; fn get_optional_billing_line2(&self) -> Option<Secret<String>>; fn get_optional_billing_city(&self) -> Option<String>; fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2>; fn get_optional_billing_zip(&self) -> Option<Secret<String>>; fn get_optional_billing_state(&self) -> Option<Secret<String>>; fn get_optional_billing_state_code(&self) -> Option<Secret<String>>; fn get_optional_billing_state_2_digit(&self) -> Option<Secret<String>>; fn get_optional_billing_first_name(&self) -> Option<Secret<String>>; fn get_optional_billing_last_name(&self) -> Option<Secret<String>>; fn get_optional_billing_phone_number(&self) -> Option<Secret<String>>; fn get_optional_billing_email(&self) -> Option<Email>; fn get_optional_l2_l3_data(&self) -> Option<Box<L2L3Data>>; } impl<Flow, Request, Response> RouterData for hyperswitch_domain_models::router_data::RouterData<Flow, Request, Response> { fn get_billing(&self) -> Result<&Address, Error> { self.address .get_payment_method_billing() .ok_or_else(missing_field_err("billing")) } fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error> { self.address .get_payment_method_billing() .and_then(|a| a.address.as_ref()) .and_then(|ad| ad.country) .ok_or_else(missing_field_err( "payment_method_data.billing.address.country", )) } fn get_billing_phone(&self) -> Result<&PhoneDetails, Error> { self.address .get_payment_method_billing() .and_then(|a| a.phone.as_ref()) .ok_or_else(missing_field_err("billing.phone")) } fn get_optional_billing(&self) -> Option<&Address> { self.address.get_payment_method_billing() } fn get_optional_shipping(&self) -> Option<&Address> { self.address.get_shipping() } fn get_optional_shipping_first_name(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.first_name) }) } fn get_optional_shipping_last_name(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.last_name) }) } fn get_optional_shipping_full_name(&self) -> Option<Secret<String>> { self.get_optional_shipping() .and_then(|shipping_details| shipping_details.address.as_ref()) .and_then(|shipping_address| shipping_address.get_optional_full_name()) } fn get_optional_shipping_line1(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.line1) }) } fn get_optional_shipping_line2(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.line2) }) } fn get_optional_shipping_line3(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.line3) }) } fn get_optional_shipping_city(&self) -> Option<String> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.city) }) } fn get_optional_shipping_state(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.state) }) } fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.country) }) } fn get_optional_shipping_zip(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.zip) }) } fn get_optional_shipping_email(&self) -> Option<Email> { self.address .get_shipping() .and_then(|shipping_address| shipping_address.clone().email) } fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>> { self.address .get_shipping() .and_then(|shipping_address| shipping_address.clone().phone) .and_then(|phone_details| phone_details.get_number_with_country_code().ok()) } fn get_optional_shipping_phone_number_without_country_code(&self) -> Option<Secret<String>> { self.address .get_shipping() .and_then(|shipping_address| shipping_address.clone().phone) .and_then(|phone_details| phone_details.get_number().ok()) } fn get_description(&self) -> Result<String, Error> { self.description .clone() .ok_or_else(missing_field_err("description")) } fn get_billing_address(&self) -> Result<&AddressDetails, Error> { self.address .get_payment_method_billing() .as_ref() .and_then(|a| a.address.as_ref()) .ok_or_else(missing_field_err("billing.address")) } fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error> { self.connector_meta_data .clone() .ok_or_else(missing_field_err("connector_meta_data")) } fn get_session_token(&self) -> Result<String, Error> { self.session_token .clone() .ok_or_else(missing_field_err("session_token")) } fn get_billing_first_name(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.first_name.clone()) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.first_name", )) } fn get_billing_full_name(&self) -> Result<Secret<String>, Error> { self.get_optional_billing() .and_then(|billing_details| billing_details.address.as_ref()) .and_then(|billing_address| billing_address.get_optional_full_name()) .ok_or_else(missing_field_err( "payment_method_data.billing.address.first_name", )) } fn get_billing_last_name(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.last_name.clone()) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.last_name", )) } fn get_billing_line1(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.line1.clone()) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.line1", )) } fn get_billing_line2(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.line2.clone()) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.line2", )) } fn get_billing_zip(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.zip.clone()) }) .ok_or_else(missing_field_err("payment_method_data.billing.address.zip")) } fn get_billing_state(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.state.clone()) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.state", )) } fn get_billing_state_code(&self) -> Result<Secret<String>, Error> { let country = self.get_billing_country()?; let state = self.get_billing_state()?; match country { api_models::enums::CountryAlpha2::US => Ok(Secret::new( UsStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::CA => Ok(Secret::new( CanadaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), _ => Ok(state.clone()), } } fn get_billing_city(&self) -> Result<String, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.city) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.city", )) } fn get_billing_email(&self) -> Result<Email, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| billing_address.email.clone()) .ok_or_else(missing_field_err("payment_method_data.billing.email")) } fn get_billing_phone_number(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| billing_address.clone().phone) .map(|phone_details| phone_details.get_number_with_country_code()) .transpose()? .ok_or_else(missing_field_err("payment_method_data.billing.phone")) } fn get_optional_billing_line1(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.line1) }) } fn get_optional_billing_line2(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.line2) }) } fn get_optional_billing_line3(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.line3) }) } fn get_optional_billing_city(&self) -> Option<String> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.city) }) } fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.country) }) } fn get_optional_billing_zip(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.zip) }) } fn get_optional_billing_state(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.state) }) } fn get_optional_billing_state_2_digit(&self) -> Option<Secret<String>> { self.get_optional_billing_state().and_then(|state| { if state.clone().expose().len() != 2 { None } else { Some(state) } }) } fn get_optional_billing_state_code(&self) -> Option<Secret<String>> { self.get_billing_state_code().ok() } fn get_optional_billing_first_name(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.first_name) }) } fn get_optional_billing_last_name(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.last_name) }) } fn get_optional_billing_phone_number(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .phone .and_then(|phone_data| phone_data.number) }) } fn get_optional_billing_email(&self) -> Option<Email> { self.address .get_payment_method_billing() .and_then(|billing_address| billing_address.clone().email) } fn to_connector_meta<T>(&self) -> Result<T, Error> where T: serde::de::DeserializeOwned, { self.get_connector_meta()? .parse_value(std::any::type_name::<T>()) .change_context(errors::ConnectorError::NoConnectorMetaData) } fn is_three_ds(&self) -> bool { matches!(self.auth_type, enums::AuthenticationType::ThreeDs) } fn get_shipping_address(&self) -> Result<&AddressDetails, Error> { self.address .get_shipping() .and_then(|a| a.address.as_ref()) .ok_or_else(missing_field_err("shipping.address")) } fn get_shipping_address_with_phone_number(&self) -> Result<&Address, Error> { self.address .get_shipping() .ok_or_else(missing_field_err("shipping")) } fn get_payment_method_token(&self) -> Result<PaymentMethodToken, Error> { self.payment_method_token .clone() .ok_or_else(missing_field_err("payment_method_token")) } fn get_customer_id(&self) -> Result<id_type::CustomerId, Error> { self.customer_id .to_owned() .ok_or_else(missing_field_err("customer_id")) } fn get_connector_customer_id(&self) -> Result<String, Error> { self.connector_customer .to_owned() .ok_or_else(missing_field_err("connector_customer_id")) } fn get_preprocessing_id(&self) -> Result<String, Error> { self.preprocessing_id .to_owned() .ok_or_else(missing_field_err("preprocessing_id")) } fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error> { self.recurring_mandate_payment_data .to_owned() .ok_or_else(missing_field_err("recurring_mandate_payment_data")) } fn get_optional_billing_full_name(&self) -> Option<Secret<String>> { self.get_optional_billing() .and_then(|billing_details| billing_details.address.as_ref()) .and_then(|billing_address| billing_address.get_optional_full_name()) } fn get_required_shipping_full_name(&self) -> Result<Secret<String>, Error> { self.get_optional_shipping_full_name() .ok_or_else(missing_field_err( "shipping.address.first_name or shipping.address.last_name", )) } fn get_required_shipping_line1(&self) -> Result<Secret<String>, Error> { self.get_optional_shipping_line1() .ok_or_else(missing_field_err("shipping.address.line1")) } fn get_required_shipping_city(&self) -> Result<String, Error> { self.get_optional_shipping_city() .ok_or_else(missing_field_err("shipping.address.city")) } fn get_required_shipping_state(&self) -> Result<Secret<String>, Error> { self.get_optional_shipping_state() .ok_or_else(missing_field_err("shipping.address.state")) } fn get_required_shipping_zip(&self) -> Result<Secret<String>, Error> { self.get_optional_shipping_zip() .ok_or_else(missing_field_err("shipping.address.zip")) } fn get_required_shipping_phone_number(&self) -> Result<Secret<String>, Error> { self.get_optional_shipping_phone_number_without_country_code() .ok_or_else(missing_field_err("shipping.phone.number")) } #[cfg(feature = "payouts")] fn get_payout_method_data(&self) -> Result<api_models::payouts::PayoutMethodData, Error> { self.payout_method_data .to_owned() .ok_or_else(missing_field_err("payout_method_data")) } #[cfg(feature = "payouts")] fn get_quote_id(&self) -> Result<String, Error> { self.quote_id .to_owned() .ok_or_else(missing_field_err("quote_id")) } fn get_optional_l2_l3_data(&self) -> Option<Box<L2L3Data>> { self.l2_l3_data.clone() } fn get_optional_customer_id(&self) -> Option<id_type::CustomerId> { self.customer_id.clone() } } pub trait AccessTokenRequestInfo { fn get_request_id(&self) -> Result<Secret<String>, Error>; } impl AccessTokenRequestInfo for RefreshTokenRouterData { fn get_request_id(&self) -> Result<Secret<String>, Error> { self.request .id .clone() .ok_or_else(missing_field_err("request.id")) } } #[derive(Debug, Copy, Clone, strum::Display, Eq, Hash, PartialEq)] pub enum CardIssuer { AmericanExpress, Master, Maestro, Visa, Discover, DinersClub, JCB, CarteBlanche, CartesBancaires, UnionPay, } pub trait CardData { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>; fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>; fn get_card_issuer(&self) -> Result<CardIssuer, Error>; fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError>; fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String>; fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String>; fn get_expiry_year_4_digit(&self) -> Secret<String>; fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError>; fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError>; fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error>; fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error>; fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error>; fn get_cardholder_name(&self) -> Result<Secret<String>, Error>; } impl CardData for Card { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.card_exp_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let exp_month = self .card_exp_month .peek() .to_string() .parse::<u8>() .map_err(|_| errors::ConnectorError::InvalidDataFormat { field_name: "payment_method_data.card.card_exp_month", })?; let month = ::cards::CardExpirationMonth::try_from(exp_month).map_err(|_| { errors::ConnectorError::InvalidDataFormat { field_name: "payment_method_data.card.card_exp_month", } })?; Ok(Secret::new(month.two_digits())) } fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.card_number.peek()) } fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?; Ok(Secret::new(format!( "{}{}{}", self.card_exp_month.peek(), delimiter, year.peek() ))) } fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", year.peek(), delimiter, self.card_exp_month.peek() )) } fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", self.card_exp_month.peek(), delimiter, year.peek() )) } fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.card_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.card_exp_month.clone().expose(); Ok(Secret::new(format!("{year}{month}"))) } fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.card_exp_month.clone().expose(); Ok(Secret::new(format!("{month}{year}"))) } fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { self.card_exp_month .peek() .clone() .parse::<i8>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { self.card_exp_year .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> { self.get_expiry_year_4_digit() .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_cardholder_name(&self) -> Result<Secret<String>, Error> { self.card_holder_name .clone() .ok_or_else(missing_field_err("card.card_holder_name")) } } impl CardData for CardDetailsForNetworkTransactionId { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.card_exp_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let exp_month = self .card_exp_month .peek() .to_string() .parse::<u8>() .map_err(|_| errors::ConnectorError::InvalidDataFormat { field_name: "payment_method_data.card.card_exp_month", })?; let month = ::cards::CardExpirationMonth::try_from(exp_month).map_err(|_| { errors::ConnectorError::InvalidDataFormat { field_name: "payment_method_data.card.card_exp_month", } })?; Ok(Secret::new(month.two_digits())) } fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.card_number.peek()) } fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?; Ok(Secret::new(format!( "{}{}{}", self.card_exp_month.peek(), delimiter, year.peek() ))) } fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", year.peek(), delimiter, self.card_exp_month.peek() )) } fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", self.card_exp_month.peek(), delimiter, year.peek() )) } fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.card_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.card_exp_month.clone().expose(); Ok(Secret::new(format!("{year}{month}"))) } fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.card_exp_month.clone().expose(); Ok(Secret::new(format!("{month}{year}"))) } fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { self.card_exp_month .peek() .clone() .parse::<i8>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { self.card_exp_year .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> { self.get_expiry_year_4_digit() .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_cardholder_name(&self) -> Result<Secret<String>, Error> { self.card_holder_name .clone() .ok_or_else(missing_field_err("card.card_holder_name")) } } #[cfg(feature = "payouts")] impl CardData for api_models::payouts::ApplePayDecrypt { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.expiry_month.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let exp_month = self .expiry_month .peek() .to_string() .parse::<u8>() .map_err(|_| errors::ConnectorError::InvalidDataFormat { field_name: "payout_method_data.apple_pay_decrypt.expiry_month", })?; let month = ::cards::CardExpirationMonth::try_from(exp_month).map_err(|_| { errors::ConnectorError::InvalidDataFormat { field_name: "payout_method_data.apple_pay_decrypt.expiry_month", } })?; Ok(Secret::new(month.two_digits())) } fn get_card_issuer(&self) -> Result<CardIssuer, Error> { Err(errors::ConnectorError::ParsingFailed) .attach_printable("get_card_issuer is not supported for Applepay Decrypted Payout") } fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?; Ok(Secret::new(format!( "{}{}{}", self.expiry_month.peek(), delimiter, year.peek() ))) } fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", year.peek(), delimiter, self.expiry_month.peek() )) } fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", self.expiry_month.peek(), delimiter, year.peek() )) } fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.expiry_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.expiry_month.clone().expose(); Ok(Secret::new(format!("{year}{month}"))) } fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.expiry_month.clone().expose(); Ok(Secret::new(format!("{month}{year}"))) } fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { self.expiry_month .peek() .clone() .parse::<i8>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { self.expiry_year .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> { self.get_expiry_year_4_digit() .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_cardholder_name(&self) -> Result<Secret<String>, Error> { self.card_holder_name .clone() .ok_or_else(missing_field_err("card.card_holder_name")) } } #[track_caller] fn get_card_issuer(card_number: &str) -> Result<CardIssuer, Error> { for (k, v) in CARD_REGEX.iter() { let regex: Regex = v .clone() .change_context(errors::ConnectorError::RequestEncodingFailed)?; if regex.is_match(card_number) { return Ok(*k); } } Err(error_stack::Report::new( errors::ConnectorError::NotImplemented("Card Type".into()), )) } static CARD_REGEX: LazyLock<HashMap<CardIssuer, Result<Regex, regex::Error>>> = LazyLock::new( || { let mut map = HashMap::new(); // Reference: https://gist.github.com/michaelkeevildown/9096cd3aac9029c4e6e05588448a8841 // [#379]: Determine card issuer from card BIN number map.insert(CardIssuer::Master, Regex::new(r"^5[1-5][0-9]{14}$")); map.insert(CardIssuer::AmericanExpress, Regex::new(r"^3[47][0-9]{13}$")); map.insert(CardIssuer::Visa, Regex::new(r"^4[0-9]{12}(?:[0-9]{3})?$")); map.insert(CardIssuer::Discover, Regex::new(r"^65[0-9]{14}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$")); map.insert( CardIssuer::Maestro, Regex::new(r"^(5018|5020|5038|5893|6304|6759|6761|6762|6763)[0-9]{8,15}$"), ); map.insert( CardIssuer::DinersClub, Regex::new(r"^3(?:0[0-5][0-9]{11}|[68][0-9][0-9]{11,13})$"), ); map.insert( CardIssuer::JCB, Regex::new(r"^(3(?:088|096|112|158|337|5(?:2[89]|[3-8][0-9]))\d{12})$"), ); map.insert(CardIssuer::CarteBlanche, Regex::new(r"^389[0-9]{11}$")); map.insert(CardIssuer::UnionPay, Regex::new(r"^(62[0-9]{14,17})$")); map }, ); pub trait AddressDetailsData { fn get_first_name(&self) -> Result<&Secret<String>, Error>; fn get_last_name(&self) -> Result<&Secret<String>, Error>; fn get_full_name(&self) -> Result<Secret<String>, Error>; fn get_line1(&self) -> Result<&Secret<String>, Error>; fn get_city(&self) -> Result<&String, Error>; fn get_line2(&self) -> Result<&Secret<String>, Error>; fn get_state(&self) -> Result<&Secret<String>, Error>; fn get_zip(&self) -> Result<&Secret<String>, Error>; fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error>; fn get_combined_address_line(&self) -> Result<Secret<String>, Error>; fn to_state_code(&self) -> Result<Secret<String>, Error>; fn to_state_code_as_optional(&self) -> Result<Option<Secret<String>>, Error>; fn get_optional_city(&self) -> Option<String>; fn get_optional_line1(&self) -> Option<Secret<String>>; fn get_optional_line2(&self) -> Option<Secret<String>>; fn get_optional_line3(&self) -> Option<Secret<String>>; fn get_optional_first_name(&self) -> Option<Secret<String>>; fn get_optional_last_name(&self) -> Option<Secret<String>>; fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2>; fn get_optional_zip(&self) -> Option<Secret<String>>; fn get_optional_state(&self) -> Option<Secret<String>>; } impl AddressDetailsData for AddressDetails { fn get_first_name(&self) -> Result<&Secret<String>, Error> { self.first_name .as_ref() .ok_or_else(missing_field_err("address.first_name")) } fn get_last_name(&self) -> Result<&Secret<String>, Error> { self.last_name .as_ref() .ok_or_else(missing_field_err("address.last_name")) } fn get_full_name(&self) -> Result<Secret<String>, Error> { let first_name = self.get_first_name()?.peek().to_owned(); let last_name = self .get_last_name() .ok() .cloned() .unwrap_or(Secret::new("".to_string())); let last_name = last_name.peek(); let full_name = format!("{first_name} {last_name}").trim().to_string(); Ok(Secret::new(full_name)) } fn get_line1(&self) -> Result<&Secret<String>, Error> { self.line1 .as_ref() .ok_or_else(missing_field_err("address.line1")) } fn get_city(&self) -> Result<&String, Error> { self.city .as_ref() .ok_or_else(missing_field_err("address.city")) } fn get_state(&self) -> Result<&Secret<String>, Error> { self.state .as_ref() .ok_or_else(missing_field_err("address.state")) } fn get_line2(&self) -> Result<&Secret<String>, Error> { self.line2 .as_ref() .ok_or_else(missing_field_err("address.line2")) } fn get_zip(&self) -> Result<&Secret<String>, Error> { self.zip .as_ref() .ok_or_else(missing_field_err("address.zip")) } fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error> { self.country .as_ref() .ok_or_else(missing_field_err("address.country")) } fn get_combined_address_line(&self) -> Result<Secret<String>, Error> { Ok(Secret::new(format!( "{},{}", self.get_line1()?.peek(), self.get_line2()?.peek() ))) } fn to_state_code(&self) -> Result<Secret<String>, Error> { let country = self.get_country()?; let state = self.get_state()?; match country { api_models::enums::CountryAlpha2::US => Ok(Secret::new( UsStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::CA => Ok(Secret::new( CanadaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::AL => Ok(Secret::new( AlbaniaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::AD => Ok(Secret::new( AndorraStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::AT => Ok(Secret::new( AustriaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::BY => Ok(Secret::new( BelarusStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::BA => Ok(Secret::new( BosniaAndHerzegovinaStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::BG => Ok(Secret::new( BulgariaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::HR => Ok(Secret::new( CroatiaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::CZ => Ok(Secret::new( CzechRepublicStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::DK => Ok(Secret::new( DenmarkStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::FI => Ok(Secret::new( FinlandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::FR => Ok(Secret::new( FranceStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::DE => Ok(Secret::new( GermanyStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::GR => Ok(Secret::new( GreeceStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::HU => Ok(Secret::new( HungaryStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::IS => Ok(Secret::new( IcelandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::IE => Ok(Secret::new( IrelandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::LV => Ok(Secret::new( LatviaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::IT => Ok(Secret::new( ItalyStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::JP => Ok(Secret::new( JapanStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::LI => Ok(Secret::new( LiechtensteinStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::LT => Ok(Secret::new( LithuaniaStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::MT => Ok(Secret::new( MaltaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::MD => Ok(Secret::new( MoldovaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::MC => Ok(Secret::new( MonacoStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::ME => Ok(Secret::new( MontenegroStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::NL => Ok(Secret::new( NetherlandsStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::NZ => Ok(Secret::new( NewZealandStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::MK => Ok(Secret::new( NorthMacedoniaStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::NO => Ok(Secret::new( NorwayStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::PL => Ok(Secret::new( PolandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::PT => Ok(Secret::new( PortugalStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::ES => Ok(Secret::new( SpainStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::CH => Ok(Secret::new( SwitzerlandStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::GB => Ok(Secret::new( UnitedKingdomStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::BR => Ok(Secret::new( BrazilStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::AU => Ok(Secret::new( AustraliaStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::SG => Ok(Secret::new( SingaporeStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::TH => Ok(Secret::new( ThailandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), api_models::enums::CountryAlpha2::PH => Ok(Secret::new( PhilippinesStatesAbbreviation::foreign_try_from(state.peek().to_string())? .to_string(), )), api_models::enums::CountryAlpha2::IN => Ok(Secret::new( IndiaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(), )), _ => Ok(state.clone()), } } fn to_state_code_as_optional(&self) -> Result<Option<Secret<String>>, Error> { self.state .as_ref() .map(|state| { if state.peek().len() == 2 { Ok(state.to_owned()) } else { self.to_state_code() } }) .transpose() } fn get_optional_city(&self) -> Option<String> { self.city.clone() } fn get_optional_line1(&self) -> Option<Secret<String>> { self.line1.clone() } fn get_optional_line2(&self) -> Option<Secret<String>> { self.line2.clone() } fn get_optional_first_name(&self) -> Option<Secret<String>> { self.first_name.clone() } fn get_optional_last_name(&self) -> Option<Secret<String>> { self.last_name.clone() } fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2> { self.country } fn get_optional_line3(&self) -> Option<Secret<String>> { self.line3.clone() } fn get_optional_zip(&self) -> Option<Secret<String>> { self.zip.clone() } fn get_optional_state(&self) -> Option<Secret<String>> { self.state.clone() } } pub trait AdditionalCardInfo { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>; } impl AdditionalCardInfo for payments::AdditionalCardInfo { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.card_exp_year .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "card_exp_year", })?; let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } } pub trait PhoneDetailsData { fn get_number(&self) -> Result<Secret<String>, Error>; fn get_country_code(&self) -> Result<String, Error>; fn get_number_with_country_code(&self) -> Result<Secret<String>, Error>; fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error>; fn extract_country_code(&self) -> Result<String, Error>; } impl PhoneDetailsData for PhoneDetails { fn get_country_code(&self) -> Result<String, Error> { self.country_code .clone() .ok_or_else(missing_field_err("billing.phone.country_code")) } fn extract_country_code(&self) -> Result<String, Error> { self.get_country_code() .map(|cc| cc.trim_start_matches('+').to_string()) } fn get_number(&self) -> Result<Secret<String>, Error> { self.number .clone() .ok_or_else(missing_field_err("billing.phone.number")) } fn get_number_with_country_code(&self) -> Result<Secret<String>, Error> { let number = self.get_number()?; let country_code = self.get_country_code()?; Ok(Secret::new(format!("{}{}", country_code, number.peek()))) } fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error> { let number = self.get_number()?; let country_code = self.get_country_code()?; let number_without_plus = country_code.trim_start_matches('+'); Ok(Secret::new(format!( "{}#{}", number_without_plus, number.peek() ))) } } #[cfg(feature = "payouts")] pub trait PayoutFulfillRequestData { fn get_connector_payout_id(&self) -> Result<String, Error>; fn get_connector_transfer_method_id(&self) -> Result<String, Error>; } #[cfg(feature = "payouts")] impl PayoutFulfillRequestData for hyperswitch_domain_models::router_request_types::PayoutsData { fn get_connector_payout_id(&self) -> Result<String, Error> { self.connector_payout_id .clone() .ok_or_else(missing_field_err("connector_payout_id")) } fn get_connector_transfer_method_id(&self) -> Result<String, Error> { self.connector_transfer_method_id .clone() .ok_or_else(missing_field_err("connector_transfer_method_id")) } } pub trait CustomerData { fn get_email(&self) -> Result<Email, Error>; fn is_mandate_payment(&self) -> bool; } impl CustomerData for ConnectorCustomerData { fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn is_mandate_payment(&self) -> bool { // We only need to check if the customer acceptance or setup mandate details are present and if the setup future usage is OffSession. // mandate_reference_id is not needed here as we do not need to check for existing mandates. self.customer_acceptance.is_some() && self.setup_future_usage == Some(FutureUsage::OffSession) } } pub trait PaymentsAuthorizeRequestData { fn get_optional_language_from_browser_info(&self) -> Option<String>; fn is_auto_capture(&self) -> Result<bool, Error>; fn get_email(&self) -> Result<Email, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; fn get_card(&self) -> Result<Card, Error>; fn connector_mandate_id(&self) -> Option<String>; fn is_mandate_payment(&self) -> bool; fn is_customer_initiated_mandate_payment(&self) -> bool; fn get_webhook_url(&self) -> Result<String, Error>; fn get_router_return_url(&self) -> Result<String, Error>; fn is_wallet(&self) -> bool; fn is_card(&self) -> bool; fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>; fn get_connector_mandate_id(&self) -> Result<String, Error>; fn get_connector_mandate_data(&self) -> Option<payments::ConnectorMandateReferenceId>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>>; fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error>; fn get_optional_user_agent(&self) -> Option<String>; fn get_original_amount(&self) -> i64; fn get_surcharge_amount(&self) -> Option<i64>; fn get_tax_on_surcharge_amount(&self) -> Option<i64>; fn get_total_surcharge_amount(&self) -> Option<i64>; fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue>; fn get_authentication_data(&self) -> Result<AuthenticationData, Error>; fn get_customer_name(&self) -> Result<Secret<String>, Error>; fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>; fn get_card_holder_name_from_additional_payment_method_data( &self, ) -> Result<Secret<String>, Error>; fn is_cit_mandate_payment(&self) -> bool; fn get_optional_network_transaction_id(&self) -> Option<String>; fn get_optional_email(&self) -> Option<Email>; fn get_card_network_from_additional_payment_method_data( &self, ) -> Result<enums::CardNetwork, Error>; fn get_connector_testing_data(&self) -> Option<pii::SecretSerdeValue>; fn get_order_id(&self) -> Result<String, errors::ConnectorError>; fn get_card_mandate_info(&self) -> Result<CardMandateInfo, Error>; } impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic) | None => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_optional_language_from_browser_info(&self) -> Option<String> { self.browser_info .clone() .and_then(|browser_info| browser_info.language) } fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { self.order_details .clone() .ok_or_else(missing_field_err("order_details")) } fn get_card(&self) -> Result<Card, Error> { match self.payment_method_data.clone() { PaymentMethodData::Card(card) => Ok(card), _ => Err(missing_field_err("card")()), } } fn get_complete_authorize_url(&self) -> Result<String, Error> { self.complete_authorize_url .clone() .ok_or_else(missing_field_err("complete_authorize_url")) } fn connector_mandate_id(&self) -> Option<String> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) } fn is_mandate_payment(&self) -> bool { ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && (self.setup_future_usage == Some(FutureUsage::OffSession))) || self .mandate_id .as_ref() .and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref()) .is_some() } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .clone() .ok_or_else(missing_field_err("webhook_url")) } fn get_router_return_url(&self) -> Result<String, Error> { self.router_return_url .clone() .ok_or_else(missing_field_err("return_url")) } fn is_wallet(&self) -> bool { matches!(self.payment_method_data, PaymentMethodData::Wallet(_)) } fn is_card(&self) -> bool { matches!(self.payment_method_data, PaymentMethodData::Card(_)) } fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> { self.payment_method_type .to_owned() .ok_or_else(missing_field_err("payment_method_type")) } fn get_connector_mandate_id(&self) -> Result<String, Error> { self.connector_mandate_id() .ok_or_else(missing_field_err("connector_mandate_id")) } fn get_connector_mandate_data(&self) -> Option<payments::ConnectorMandateReferenceId> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { Some(connector_mandate_ids.clone()) } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) } fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>> { self.browser_info.clone().and_then(|browser_info| { browser_info .ip_address .map(|ip| Secret::new(ip.to_string())) }) } fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> { let ip_address = self .browser_info .clone() .and_then(|browser_info| browser_info.ip_address); let val = ip_address.ok_or_else(missing_field_err("browser_info.ip_address"))?; Ok(Secret::new(val.to_string())) } fn get_optional_user_agent(&self) -> Option<String> { self.browser_info .clone() .and_then(|browser_info| browser_info.user_agent) } fn get_original_amount(&self) -> i64 { self.surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.original_amount.get_amount_as_i64()) .unwrap_or(self.amount) } fn get_surcharge_amount(&self) -> Option<i64> { self.surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.surcharge_amount.get_amount_as_i64()) } fn get_tax_on_surcharge_amount(&self) -> Option<i64> { self.surcharge_details.as_ref().map(|surcharge_details| { surcharge_details .tax_on_surcharge_amount .get_amount_as_i64() }) } fn get_total_surcharge_amount(&self) -> Option<i64> { self.surcharge_details.as_ref().map(|surcharge_details| { surcharge_details .get_total_surcharge_amount() .get_amount_as_i64() }) } fn is_customer_initiated_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(FutureUsage::OffSession) } fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue> { self.metadata.clone().and_then(|meta_data| match meta_data { Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) | Value::Array(_) => None, Value::Object(_) => Some(meta_data.into()), }) } fn get_authentication_data(&self) -> Result<AuthenticationData, Error> { self.authentication_data .clone() .ok_or_else(missing_field_err("authentication_data")) } fn get_customer_name(&self) -> Result<Secret<String>, Error> { self.customer_name .clone() .ok_or_else(missing_field_err("customer_name")) } fn get_card_holder_name_from_additional_payment_method_data( &self, ) -> Result<Secret<String>, Error> { match &self.additional_payment_method_data { Some(payments::AdditionalPaymentData::Card(card_data)) => Ok(card_data .card_holder_name .clone() .ok_or_else(|| errors::ConnectorError::MissingRequiredField { field_name: "card_holder_name", })?), _ => Err(errors::ConnectorError::MissingRequiredFields { field_names: vec!["card_holder_name"], } .into()), } } /// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`. fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_request_reference_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) .ok_or_else(missing_field_err("connector_mandate_request_reference_id")) } fn is_cit_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(FutureUsage::OffSession) } fn get_optional_network_transaction_id(&self) -> Option<String> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => { Some(network_transaction_id.clone()) } Some(payments::MandateReferenceId::ConnectorMandateId(_)) | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) | None => None, }) } fn get_optional_email(&self) -> Option<Email> { self.email.clone() } fn get_card_network_from_additional_payment_method_data( &self, ) -> Result<enums::CardNetwork, Error> { match &self.additional_payment_method_data { Some(payments::AdditionalPaymentData::Card(card_data)) => Ok(card_data .card_network .clone() .ok_or_else(|| errors::ConnectorError::MissingRequiredField { field_name: "card_network", })?), _ => Err(errors::ConnectorError::MissingRequiredFields { field_names: vec!["card_network"], } .into()), } } fn get_connector_testing_data(&self) -> Option<pii::SecretSerdeValue> { self.connector_testing_data.clone() } fn get_order_id(&self) -> Result<String, errors::ConnectorError> { self.order_id .to_owned() .ok_or(errors::ConnectorError::RequestEncodingFailed) } fn get_card_mandate_info(&self) -> Result<CardMandateInfo, Error> { match &self.additional_payment_method_data { Some(payments::AdditionalPaymentData::Card(card_data)) => Ok(CardMandateInfo { card_exp_month: card_data.card_exp_month.clone().ok_or_else(|| { errors::ConnectorError::MissingRequiredField { field_name: "card_exp_month", } })?, card_exp_year: card_data.card_exp_year.clone().ok_or_else(|| { errors::ConnectorError::MissingRequiredField { field_name: "card_exp_year", } })?, }), _ => Err(errors::ConnectorError::MissingRequiredFields { field_names: vec!["card_exp_month", "card_exp_year"], } .into()), } } } pub trait PaymentsCaptureRequestData { fn get_optional_language_from_browser_info(&self) -> Option<String>; fn is_multiple_capture(&self) -> bool; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_webhook_url(&self) -> Result<String, Error>; } impl PaymentsCaptureRequestData for PaymentsCaptureData { fn is_multiple_capture(&self) -> bool { self.multiple_capture_data.is_some() } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_optional_language_from_browser_info(&self) -> Option<String> { self.browser_info .clone() .and_then(|browser_info| browser_info.language) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .clone() .ok_or_else(missing_field_err("webhook_url")) } } pub trait PaymentsSyncRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError>; fn is_mandate_payment(&self) -> bool; fn get_optional_connector_transaction_id(&self) -> Option<String>; } impl PaymentsSyncRequestData for PaymentsSyncData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic) | None => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError> { match self.connector_transaction_id.clone() { ResponseId::ConnectorTransactionId(txn_id) => Ok(txn_id), _ => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "connector_transaction_id", }, ) .attach_printable("Expected connector transaction ID not found") .change_context(errors::ConnectorError::MissingConnectorTransactionID)?, } } fn is_mandate_payment(&self) -> bool { matches!(self.setup_future_usage, Some(FutureUsage::OffSession)) } fn get_optional_connector_transaction_id(&self) -> Option<String> { match self.connector_transaction_id.clone() { ResponseId::ConnectorTransactionId(txn_id) => Some(txn_id), _ => None, } } } pub trait PaymentsPostSessionTokensRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; } impl PaymentsPostSessionTokensRequestData for PaymentsPostSessionTokensData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } } pub trait PaymentsCancelRequestData { fn get_optional_language_from_browser_info(&self) -> Option<String>; fn get_amount(&self) -> Result<i64, Error>; fn get_currency(&self) -> Result<enums::Currency, Error>; fn get_cancellation_reason(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_webhook_url(&self) -> Result<String, Error>; } impl PaymentsCancelRequestData for PaymentsCancelData { fn get_amount(&self) -> Result<i64, Error> { self.amount.ok_or_else(missing_field_err("amount")) } fn get_currency(&self) -> Result<enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } fn get_cancellation_reason(&self) -> Result<String, Error> { self.cancellation_reason .clone() .ok_or_else(missing_field_err("cancellation_reason")) } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_optional_language_from_browser_info(&self) -> Option<String> { self.browser_info .clone() .and_then(|browser_info| browser_info.language) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .clone() .ok_or_else(missing_field_err("webhook_url")) } } pub trait RefundsRequestData { fn get_optional_language_from_browser_info(&self) -> Option<String>; fn get_connector_refund_id(&self) -> Result<String, Error>; fn get_webhook_url(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_connector_metadata(&self) -> Result<Value, Error>; } impl RefundsRequestData for RefundsData { #[track_caller] fn get_connector_refund_id(&self) -> Result<String, Error> { self.connector_refund_id .clone() .get_required_value("connector_refund_id") .change_context(errors::ConnectorError::MissingConnectorTransactionID) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .clone() .ok_or_else(missing_field_err("webhook_url")) } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_optional_language_from_browser_info(&self) -> Option<String> { self.browser_info .clone() .and_then(|browser_info| browser_info.language) } fn get_connector_metadata(&self) -> Result<Value, Error> { self.connector_metadata .clone() .ok_or_else(missing_field_err("connector_metadata")) } } pub trait PaymentsSetupMandateRequestData { fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_email(&self) -> Result<Email, Error>; fn get_router_return_url(&self) -> Result<String, Error>; fn is_card(&self) -> bool; fn get_return_url(&self) -> Result<String, Error>; fn get_webhook_url(&self) -> Result<String, Error>; fn get_optional_language_from_browser_info(&self) -> Option<String>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn is_auto_capture(&self) -> Result<bool, Error>; fn is_customer_initiated_mandate_payment(&self) -> bool; } impl PaymentsSetupMandateRequestData for SetupMandateRequestData { fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_router_return_url(&self) -> Result<String, Error> { self.router_return_url .clone() .ok_or_else(missing_field_err("router_return_url")) } fn is_card(&self) -> bool { matches!(self.payment_method_data, PaymentMethodData::Card(_)) } fn get_return_url(&self) -> Result<String, Error> { self.router_return_url .clone() .ok_or_else(missing_field_err("return_url")) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .clone() .ok_or_else(missing_field_err("webhook_url")) } fn get_optional_language_from_browser_info(&self) -> Option<String> { self.browser_info .clone() .and_then(|browser_info| browser_info.language) } fn get_complete_authorize_url(&self) -> Result<String, Error> { self.complete_authorize_url .clone() .ok_or_else(missing_field_err("complete_authorize_url")) } fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic) | None => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } fn is_customer_initiated_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(FutureUsage::OffSession) } } pub trait PaymentMethodTokenizationRequestData { fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn is_mandate_payment(&self) -> bool; } impl PaymentMethodTokenizationRequestData for PaymentMethodTokenizationData { fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn is_mandate_payment(&self) -> bool { ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && (self.setup_future_usage == Some(FutureUsage::OffSession))) || self .mandate_id .as_ref() .and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref()) .is_some() } } pub trait PaymentsCompleteAuthorizeRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; fn get_email(&self) -> Result<Email, Error>; fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn is_mandate_payment(&self) -> bool; fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>; fn is_cit_mandate_payment(&self) -> bool; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_threeds_method_comp_ind(&self) -> Result<payments::ThreeDsCompletionIndicator, Error>; fn get_connector_mandate_id(&self) -> Option<String>; } impl PaymentsCompleteAuthorizeRequestData for CompleteAuthorizeData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic) | None => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> { self.redirect_response .as_ref() .and_then(|res| res.payload.to_owned()) .ok_or( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.payload", } .into(), ) } fn get_complete_authorize_url(&self) -> Result<String, Error> { self.complete_authorize_url .clone() .ok_or_else(missing_field_err("complete_authorize_url")) } fn is_mandate_payment(&self) -> bool { ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(FutureUsage::OffSession)) || self .mandate_id .as_ref() .and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref()) .is_some() } /// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`. fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_request_reference_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) .ok_or_else(missing_field_err("connector_mandate_request_reference_id")) } fn is_cit_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(FutureUsage::OffSession) } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_threeds_method_comp_ind(&self) -> Result<payments::ThreeDsCompletionIndicator, Error> { self.threeds_method_comp_ind .clone() .ok_or_else(missing_field_err("threeds_method_comp_ind")) } fn get_connector_mandate_id(&self) -> Option<String> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) } } pub trait AddressData { fn get_optional_full_name(&self) -> Option<Secret<String>>; fn get_email(&self) -> Result<Email, Error>; fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error>; fn get_optional_first_name(&self) -> Option<Secret<String>>; fn get_optional_last_name(&self) -> Option<Secret<String>>; } impl AddressData for Address { fn get_optional_full_name(&self) -> Option<Secret<String>> { self.address .as_ref() .and_then(|billing_address| billing_address.get_optional_full_name()) } fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error> { self.phone .clone() .map(|phone_details| phone_details.get_number_with_country_code()) .transpose()? .ok_or_else(missing_field_err("phone")) } fn get_optional_first_name(&self) -> Option<Secret<String>> { self.address .as_ref() .and_then(|billing_address| billing_address.get_optional_first_name()) } fn get_optional_last_name(&self) -> Option<Secret<String>> { self.address .as_ref() .and_then(|billing_address| billing_address.get_optional_last_name()) } } pub trait PaymentsPreProcessingRequestData { fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>; fn get_email(&self) -> Result<Email, Error>; fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>; fn get_currency(&self) -> Result<enums::Currency, Error>; fn get_amount(&self) -> Result<i64, Error>; fn get_minor_amount(&self) -> Result<MinorUnit, Error>; fn is_auto_capture(&self) -> Result<bool, Error>; fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; fn get_webhook_url(&self) -> Result<String, Error>; fn get_router_return_url(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn connector_mandate_id(&self) -> Option<String>; fn get_payment_method_data(&self) -> Result<PaymentMethodData, Error>; fn is_customer_initiated_mandate_payment(&self) -> bool; } impl PaymentsPreProcessingRequestData for PaymentsPreProcessingData { fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> { self.payment_method_type .to_owned() .ok_or_else(missing_field_err("payment_method_type")) } fn get_payment_method_data(&self) -> Result<PaymentMethodData, Error> { self.payment_method_data .to_owned() .ok_or_else(missing_field_err("payment_method_data")) } fn get_currency(&self) -> Result<enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } fn get_amount(&self) -> Result<i64, Error> { self.amount.ok_or_else(missing_field_err("amount")) } // New minor amount function for amount framework fn get_minor_amount(&self) -> Result<MinorUnit, Error> { self.minor_amount.ok_or_else(missing_field_err("amount")) } fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(enums::CaptureMethod::ManualMultiple) | Some(enums::CaptureMethod::Scheduled) => { Err(errors::ConnectorError::CaptureMethodNotSupported.into()) } } } fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { self.order_details .clone() .ok_or_else(missing_field_err("order_details")) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .clone() .ok_or_else(missing_field_err("webhook_url")) } fn get_router_return_url(&self) -> Result<String, Error> { self.router_return_url .clone() .ok_or_else(missing_field_err("return_url")) } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_complete_authorize_url(&self) -> Result<String, Error> { self.complete_authorize_url .clone() .ok_or_else(missing_field_err("complete_authorize_url")) } fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> { self.redirect_response .as_ref() .and_then(|res| res.payload.to_owned()) .ok_or( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.payload", } .into(), ) } fn connector_mandate_id(&self) -> Option<String> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) } fn is_customer_initiated_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(FutureUsage::OffSession) } } pub trait BrowserInformationData { fn get_accept_header(&self) -> Result<String, Error>; fn get_language(&self) -> Result<String, Error>; fn get_screen_height(&self) -> Result<u32, Error>; fn get_screen_width(&self) -> Result<u32, Error>; fn get_color_depth(&self) -> Result<u8, Error>; fn get_user_agent(&self) -> Result<String, Error>; fn get_time_zone(&self) -> Result<i32, Error>; fn get_java_enabled(&self) -> Result<bool, Error>; fn get_java_script_enabled(&self) -> Result<bool, Error>; fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error>; fn get_os_type(&self) -> Result<String, Error>; fn get_os_version(&self) -> Result<String, Error>; fn get_device_model(&self) -> Result<String, Error>; } impl BrowserInformationData for BrowserInformation { fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> { let ip_address = self .ip_address .ok_or_else(missing_field_err("browser_info.ip_address"))?; Ok(Secret::new(ip_address.to_string())) } fn get_accept_header(&self) -> Result<String, Error> { self.accept_header .clone() .ok_or_else(missing_field_err("browser_info.accept_header")) } fn get_language(&self) -> Result<String, Error> { self.language .clone() .ok_or_else(missing_field_err("browser_info.language")) } fn get_screen_height(&self) -> Result<u32, Error> { self.screen_height .ok_or_else(missing_field_err("browser_info.screen_height")) } fn get_screen_width(&self) -> Result<u32, Error> { self.screen_width .ok_or_else(missing_field_err("browser_info.screen_width")) } fn get_color_depth(&self) -> Result<u8, Error> { self.color_depth .ok_or_else(missing_field_err("browser_info.color_depth")) } fn get_user_agent(&self) -> Result<String, Error> { self.user_agent .clone() .ok_or_else(missing_field_err("browser_info.user_agent")) } fn get_time_zone(&self) -> Result<i32, Error> { self.time_zone .ok_or_else(missing_field_err("browser_info.time_zone")) } fn get_java_enabled(&self) -> Result<bool, Error> { self.java_enabled .ok_or_else(missing_field_err("browser_info.java_enabled")) } fn get_java_script_enabled(&self) -> Result<bool, Error> { self.java_script_enabled .ok_or_else(missing_field_err("browser_info.java_script_enabled")) } fn get_os_type(&self) -> Result<String, Error> { self.os_type .clone() .ok_or_else(missing_field_err("browser_info.os_type")) } fn get_os_version(&self) -> Result<String, Error> { self.os_version .clone() .ok_or_else(missing_field_err("browser_info.os_version")) } fn get_device_model(&self) -> Result<String, Error> { self.device_model .clone() .ok_or_else(missing_field_err("browser_info.device_model")) } } pub fn get_header_key_value<'a>( key: &str, headers: &'a actix_web::http::header::HeaderMap, ) -> CustomResult<&'a str, errors::ConnectorError> { get_header_field(headers.get(key)) } pub fn get_http_header<'a>( key: &str, headers: &'a http::HeaderMap, ) -> CustomResult<&'a str, errors::ConnectorError> { get_header_field(headers.get(key)) } fn get_header_field( field: Option<&http::HeaderValue>, ) -> CustomResult<&str, errors::ConnectorError> { field .map(|header_value| { header_value .to_str() .change_context(errors::ConnectorError::WebhookSignatureNotFound) }) .ok_or(report!( errors::ConnectorError::WebhookSourceVerificationFailed ))? } pub trait CryptoData { fn get_pay_currency(&self) -> Result<String, Error>; } impl CryptoData for payment_method_data::CryptoData { fn get_pay_currency(&self) -> Result<String, Error> { self.pay_currency .clone() .ok_or_else(missing_field_err("crypto_data.pay_currency")) } } #[macro_export] macro_rules! capture_method_not_supported { ($connector:expr, $capture_method:expr) => { Err(errors::ConnectorError::NotSupported { message: format!("{} for selected payment method", $capture_method), connector: $connector, } .into()) }; ($connector:expr, $capture_method:expr, $payment_method_type:expr) => { Err(errors::ConnectorError::NotSupported { message: format!("{} for {}", $capture_method, $payment_method_type), connector: $connector, } .into()) }; } #[macro_export] macro_rules! get_formatted_date_time { ($date_format:tt) => {{ let format = time::macros::format_description!($date_format); time::OffsetDateTime::now_utc() .format(&format) .change_context(ConnectorError::InvalidDateFormat) }}; } #[macro_export] macro_rules! unimplemented_payment_method { ($payment_method:expr, $connector:expr) => { hyperswitch_interfaces::errors::ConnectorError::NotImplemented(format!( "{} through {}", $payment_method, $connector )) }; ($payment_method:expr, $flow:expr, $connector:expr) => { hyperswitch_interfaces::errors::ConnectorError::NotImplemented(format!( "{} {} through {}", $payment_method, $flow, $connector )) }; } impl ForeignTryFrom<String> for UsStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "UsStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => { let binding = value.as_str().to_lowercase(); let state = binding.as_str(); match state { "alabama" => Ok(Self::AL), "alaska" => Ok(Self::AK), "american samoa" => Ok(Self::AS), "arizona" => Ok(Self::AZ), "arkansas" => Ok(Self::AR), "california" => Ok(Self::CA), "colorado" => Ok(Self::CO), "connecticut" => Ok(Self::CT), "delaware" => Ok(Self::DE), "district of columbia" | "columbia" => Ok(Self::DC), "federated states of micronesia" | "micronesia" => Ok(Self::FM), "florida" => Ok(Self::FL), "georgia" => Ok(Self::GA), "guam" => Ok(Self::GU), "hawaii" => Ok(Self::HI), "idaho" => Ok(Self::ID), "illinois" => Ok(Self::IL), "indiana" => Ok(Self::IN), "iowa" => Ok(Self::IA), "kansas" => Ok(Self::KS), "kentucky" => Ok(Self::KY), "louisiana" => Ok(Self::LA), "maine" => Ok(Self::ME), "marshall islands" => Ok(Self::MH), "maryland" => Ok(Self::MD), "massachusetts" => Ok(Self::MA), "michigan" => Ok(Self::MI), "minnesota" => Ok(Self::MN), "mississippi" => Ok(Self::MS), "missouri" => Ok(Self::MO), "montana" => Ok(Self::MT), "nebraska" => Ok(Self::NE), "nevada" => Ok(Self::NV), "new hampshire" => Ok(Self::NH), "new jersey" => Ok(Self::NJ), "new mexico" => Ok(Self::NM), "new york" => Ok(Self::NY), "north carolina" => Ok(Self::NC), "north dakota" => Ok(Self::ND), "northern mariana islands" => Ok(Self::MP), "ohio" => Ok(Self::OH), "oklahoma" => Ok(Self::OK), "oregon" => Ok(Self::OR), "palau" => Ok(Self::PW), "pennsylvania" => Ok(Self::PA), "puerto rico" => Ok(Self::PR), "rhode island" => Ok(Self::RI), "south carolina" => Ok(Self::SC), "south dakota" => Ok(Self::SD), "tennessee" => Ok(Self::TN), "texas" => Ok(Self::TX), "utah" => Ok(Self::UT), "vermont" => Ok(Self::VT), "virgin islands" => Ok(Self::VI), "virginia" => Ok(Self::VA), "washington" => Ok(Self::WA), "west virginia" => Ok(Self::WV), "wisconsin" => Ok(Self::WI), "wyoming" => Ok(Self::WY), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } } } impl ForeignTryFrom<String> for CanadaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "CanadaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => { let binding = value.as_str().to_lowercase(); let state = binding.as_str(); match state { "alberta" => Ok(Self::AB), "british columbia" => Ok(Self::BC), "manitoba" => Ok(Self::MB), "new brunswick" => Ok(Self::NB), "newfoundland and labrador" | "newfoundland & labrador" => Ok(Self::NL), "northwest territories" => Ok(Self::NT), "nova scotia" => Ok(Self::NS), "nunavut" => Ok(Self::NU), "ontario" => Ok(Self::ON), "prince edward island" => Ok(Self::PE), "quebec" => Ok(Self::QC), "saskatchewan" => Ok(Self::SK), "yukon" => Ok(Self::YT), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } } } impl ForeignTryFrom<String> for AustraliaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state = parse_state_enum::<Self>(value, "AustraliaStatesAbbreviation", "address.state")?; match state.as_str() { "newsouthwales" => Ok(Self::NSW), "queensland" => Ok(Self::QLD), "southaustralia" => Ok(Self::SA), "westernaustralia" => Ok(Self::WA), "victoria" => Ok(Self::VIC), "northernterritory" => Ok(Self::NT), "australiancapitalterritory" => Ok(Self::ACT), "tasmania" => Ok(Self::TAS), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } impl ForeignTryFrom<String> for PolandStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "PolandStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Greater Poland" => Ok(Self::GreaterPoland), "Holy Cross" => Ok(Self::HolyCross), "Kuyavia-Pomerania" => Ok(Self::KuyaviaPomerania), "Lesser Poland" => Ok(Self::LesserPoland), "Lower Silesia" => Ok(Self::LowerSilesia), "Lublin" => Ok(Self::Lublin), "Lubusz" => Ok(Self::Lubusz), "Łódź" => Ok(Self::Łódź), "Mazovia" => Ok(Self::Mazovia), "Podlaskie" => Ok(Self::Podlaskie), "Pomerania" => Ok(Self::Pomerania), "Silesia" => Ok(Self::Silesia), "Subcarpathia" => Ok(Self::Subcarpathia), "Upper Silesia" => Ok(Self::UpperSilesia), "Warmia-Masuria" => Ok(Self::WarmiaMasuria), "West Pomerania" => Ok(Self::WestPomerania), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for FranceStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "FranceStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Ain" => Ok(Self::Ain), "Aisne" => Ok(Self::Aisne), "Allier" => Ok(Self::Allier), "Alpes-de-Haute-Provence" => Ok(Self::AlpesDeHauteProvence), "Alpes-Maritimes" => Ok(Self::AlpesMaritimes), "Alsace" => Ok(Self::Alsace), "Ardèche" => Ok(Self::Ardeche), "Ardennes" => Ok(Self::Ardennes), "Ariège" => Ok(Self::Ariege), "Aube" => Ok(Self::Aube), "Aude" => Ok(Self::Aude), "Auvergne-Rhône-Alpes" => Ok(Self::AuvergneRhoneAlpes), "Aveyron" => Ok(Self::Aveyron), "Bas-Rhin" => Ok(Self::BasRhin), "Bouches-du-Rhône" => Ok(Self::BouchesDuRhone), "Bourgogne-Franche-Comté" => Ok(Self::BourgogneFrancheComte), "Bretagne" => Ok(Self::Bretagne), "Calvados" => Ok(Self::Calvados), "Cantal" => Ok(Self::Cantal), "Centre-Val de Loire" => Ok(Self::CentreValDeLoire), "Charente" => Ok(Self::Charente), "Charente-Maritime" => Ok(Self::CharenteMaritime), "Cher" => Ok(Self::Cher), "Clipperton" => Ok(Self::Clipperton), "Corrèze" => Ok(Self::Correze), "Corse" => Ok(Self::Corse), "Corse-du-Sud" => Ok(Self::CorseDuSud), "Côte-d'Or" => Ok(Self::CoteDor), "Côtes-d'Armor" => Ok(Self::CotesDarmor), "Creuse" => Ok(Self::Creuse), "Deux-Sèvres" => Ok(Self::DeuxSevres), "Dordogne" => Ok(Self::Dordogne), "Doubs" => Ok(Self::Doubs), "Drôme" => Ok(Self::Drome), "Essonne" => Ok(Self::Essonne), "Eure" => Ok(Self::Eure), "Eure-et-Loir" => Ok(Self::EureEtLoir), "Finistère" => Ok(Self::Finistere), "French Guiana" => Ok(Self::FrenchGuiana), "French Polynesia" => Ok(Self::FrenchPolynesia), "French Southern and Antarctic Lands" => Ok(Self::FrenchSouthernAndAntarcticLands), "Gard" => Ok(Self::Gard), "Gers" => Ok(Self::Gers), "Gironde" => Ok(Self::Gironde), "Grand-Est" => Ok(Self::GrandEst), "Guadeloupe" => Ok(Self::Guadeloupe), "Haut-Rhin" => Ok(Self::HautRhin), "Haute-Corse" => Ok(Self::HauteCorse), "Haute-Garonne" => Ok(Self::HauteGaronne), "Haute-Loire" => Ok(Self::HauteLoire), "Haute-Marne" => Ok(Self::HauteMarne), "Haute-Saône" => Ok(Self::HauteSaone), "Haute-Savoie" => Ok(Self::HauteSavoie), "Haute-Vienne" => Ok(Self::HauteVienne), "Hautes-Alpes" => Ok(Self::HautesAlpes), "Hautes-Pyrénées" => Ok(Self::HautesPyrenees), "Hauts-de-France" => Ok(Self::HautsDeFrance), "Hauts-de-Seine" => Ok(Self::HautsDeSeine), "Hérault" => Ok(Self::Herault), "Île-de-France" => Ok(Self::IleDeFrance), "Ille-et-Vilaine" => Ok(Self::IlleEtVilaine), "Indre" => Ok(Self::Indre), "Indre-et-Loire" => Ok(Self::IndreEtLoire), "Isère" => Ok(Self::Isere), "Jura" => Ok(Self::Jura), "La Réunion" => Ok(Self::LaReunion), "Landes" => Ok(Self::Landes), "Loir-et-Cher" => Ok(Self::LoirEtCher), "Loire" => Ok(Self::Loire), "Loire-Atlantique" => Ok(Self::LoireAtlantique), "Loiret" => Ok(Self::Loiret), "Lot" => Ok(Self::Lot), "Lot-et-Garonne" => Ok(Self::LotEtGaronne), "Lozère" => Ok(Self::Lozere), "Maine-et-Loire" => Ok(Self::MaineEtLoire), "Manche" => Ok(Self::Manche), "Marne" => Ok(Self::Marne), "Martinique" => Ok(Self::Martinique), "Mayenne" => Ok(Self::Mayenne), "Mayotte" => Ok(Self::Mayotte), "Métropole de Lyon" => Ok(Self::MetropoleDeLyon), "Meurthe-et-Moselle" => Ok(Self::MeurtheEtMoselle), "Meuse" => Ok(Self::Meuse), "Morbihan" => Ok(Self::Morbihan), "Moselle" => Ok(Self::Moselle), "Nièvre" => Ok(Self::Nievre), "Nord" => Ok(Self::Nord), "Normandie" => Ok(Self::Normandie), "Nouvelle-Aquitaine" => Ok(Self::NouvelleAquitaine), "Occitanie" => Ok(Self::Occitanie), "Oise" => Ok(Self::Oise), "Orne" => Ok(Self::Orne), "Paris" => Ok(Self::Paris), "Pas-de-Calais" => Ok(Self::PasDeCalais), "Pays-de-la-Loire" => Ok(Self::PaysDeLaLoire), "Provence-Alpes-Côte-d'Azur" => Ok(Self::ProvenceAlpesCoteDazur), "Puy-de-Dôme" => Ok(Self::PuyDeDome), "Pyrénées-Atlantiques" => Ok(Self::PyreneesAtlantiques), "Pyrénées-Orientales" => Ok(Self::PyreneesOrientales), "Rhône" => Ok(Self::Rhone), "Saint Pierre and Miquelon" => Ok(Self::SaintPierreAndMiquelon), "Saint-Barthélemy" => Ok(Self::SaintBarthelemy), "Saint-Martin" => Ok(Self::SaintMartin), "Saône-et-Loire" => Ok(Self::SaoneEtLoire), "Sarthe" => Ok(Self::Sarthe), "Savoie" => Ok(Self::Savoie), "Seine-et-Marne" => Ok(Self::SeineEtMarne), "Seine-Maritime" => Ok(Self::SeineMaritime), "Seine-Saint-Denis" => Ok(Self::SeineSaintDenis), "Somme" => Ok(Self::Somme), "Tarn" => Ok(Self::Tarn), "Tarn-et-Garonne" => Ok(Self::TarnEtGaronne), "Territoire de Belfort" => Ok(Self::TerritoireDeBelfort), "Val-d'Oise" => Ok(Self::ValDoise), "Val-de-Marne" => Ok(Self::ValDeMarne), "Var" => Ok(Self::Var), "Vaucluse" => Ok(Self::Vaucluse), "Vendée" => Ok(Self::Vendee), "Vienne" => Ok(Self::Vienne), "Vosges" => Ok(Self::Vosges), "Wallis and Futuna" => Ok(Self::WallisAndFutuna), "Yonne" => Ok(Self::Yonne), "Yvelines" => Ok(Self::Yvelines), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for GermanyStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "GermanyStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Baden-Württemberg" => Ok(Self::BW), "Bavaria" => Ok(Self::BY), "Berlin" => Ok(Self::BE), "Brandenburg" => Ok(Self::BB), "Bremen" => Ok(Self::HB), "Hamburg" => Ok(Self::HH), "Hessen" => Ok(Self::HE), "Lower Saxony" => Ok(Self::NI), "Mecklenburg-Vorpommern" => Ok(Self::MV), "North Rhine-Westphalia" => Ok(Self::NW), "Rhineland-Palatinate" => Ok(Self::RP), "Saarland" => Ok(Self::SL), "Saxony" => Ok(Self::SN), "Saxony-Anhalt" => Ok(Self::ST), "Schleswig-Holstein" => Ok(Self::SH), "Thuringia" => Ok(Self::TH), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for SpainStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "SpainStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "A Coruña Province" => Ok(Self::ACorunaProvince), "Albacete Province" => Ok(Self::AlbaceteProvince), "Alicante Province" => Ok(Self::AlicanteProvince), "Almería Province" => Ok(Self::AlmeriaProvince), "Andalusia" => Ok(Self::Andalusia), "Araba / Álava" => Ok(Self::ArabaAlava), "Aragon" => Ok(Self::Aragon), "Badajoz Province" => Ok(Self::BadajozProvince), "Balearic Islands" => Ok(Self::BalearicIslands), "Barcelona Province" => Ok(Self::BarcelonaProvince), "Basque Country" => Ok(Self::BasqueCountry), "Biscay" => Ok(Self::Biscay), "Burgos Province" => Ok(Self::BurgosProvince), "Canary Islands" => Ok(Self::CanaryIslands), "Cantabria" => Ok(Self::Cantabria), "Castellón Province" => Ok(Self::CastellonProvince), "Castile and León" => Ok(Self::CastileAndLeon), "Castilla-La Mancha" => Ok(Self::CastileLaMancha), "Catalonia" => Ok(Self::Catalonia), "Ceuta" => Ok(Self::Ceuta), "Ciudad Real Province" => Ok(Self::CiudadRealProvince), "Community of Madrid" => Ok(Self::CommunityOfMadrid), "Cuenca Province" => Ok(Self::CuencaProvince), "Cáceres Province" => Ok(Self::CaceresProvince), "Cádiz Province" => Ok(Self::CadizProvince), "Córdoba Province" => Ok(Self::CordobaProvince), "Extremadura" => Ok(Self::Extremadura), "Galicia" => Ok(Self::Galicia), "Gipuzkoa" => Ok(Self::Gipuzkoa), "Girona Province" => Ok(Self::GironaProvince), "Granada Province" => Ok(Self::GranadaProvince), "Guadalajara Province" => Ok(Self::GuadalajaraProvince), "Huelva Province" => Ok(Self::HuelvaProvince), "Huesca Province" => Ok(Self::HuescaProvince), "Jaén Province" => Ok(Self::JaenProvince), "La Rioja" => Ok(Self::LaRioja), "Las Palmas Province" => Ok(Self::LasPalmasProvince), "León Province" => Ok(Self::LeonProvince), "Lleida Province" => Ok(Self::LleidaProvince), "Lugo Province" => Ok(Self::LugoProvince), "Madrid Province" => Ok(Self::MadridProvince), "Melilla" => Ok(Self::Melilla), "Murcia Province" => Ok(Self::MurciaProvince), "Málaga Province" => Ok(Self::MalagaProvince), "Navarre" => Ok(Self::Navarre), "Ourense Province" => Ok(Self::OurenseProvince), "Palencia Province" => Ok(Self::PalenciaProvince), "Pontevedra Province" => Ok(Self::PontevedraProvince), "Province of Asturias" => Ok(Self::ProvinceOfAsturias), "Province of Ávila" => Ok(Self::ProvinceOfAvila), "Region of Murcia" => Ok(Self::RegionOfMurcia), "Salamanca Province" => Ok(Self::SalamancaProvince), "Santa Cruz de Tenerife Province" => Ok(Self::SantaCruzDeTenerifeProvince), "Segovia Province" => Ok(Self::SegoviaProvince), "Seville Province" => Ok(Self::SevilleProvince), "Soria Province" => Ok(Self::SoriaProvince), "Tarragona Province" => Ok(Self::TarragonaProvince), "Teruel Province" => Ok(Self::TeruelProvince), "Toledo Province" => Ok(Self::ToledoProvince), "Valencia Province" => Ok(Self::ValenciaProvince), "Valencian Community" => Ok(Self::ValencianCommunity), "Valladolid Province" => Ok(Self::ValladolidProvince), "Zamora Province" => Ok(Self::ZamoraProvince), "Zaragoza Province" => Ok(Self::ZaragozaProvince), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for ItalyStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "ItalyStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Abruzzo" => Ok(Self::Abruzzo), "Aosta Valley" => Ok(Self::AostaValley), "Apulia" => Ok(Self::Apulia), "Basilicata" => Ok(Self::Basilicata), "Benevento Province" => Ok(Self::BeneventoProvince), "Calabria" => Ok(Self::Calabria), "Campania" => Ok(Self::Campania), "Emilia-Romagna" => Ok(Self::EmiliaRomagna), "Friuli–Venezia Giulia" => Ok(Self::FriuliVeneziaGiulia), "Lazio" => Ok(Self::Lazio), "Liguria" => Ok(Self::Liguria), "Lombardy" => Ok(Self::Lombardy), "Marche" => Ok(Self::Marche), "Molise" => Ok(Self::Molise), "Piedmont" => Ok(Self::Piedmont), "Sardinia" => Ok(Self::Sardinia), "Sicily" => Ok(Self::Sicily), "Trentino-South Tyrol" => Ok(Self::TrentinoSouthTyrol), "Tuscany" => Ok(Self::Tuscany), "Umbria" => Ok(Self::Umbria), "Veneto" => Ok(Self::Veneto), "Libero consorzio comunale di Agrigento" => Ok(Self::Agrigento), "Libero consorzio comunale di Caltanissetta" => Ok(Self::Caltanissetta), "Libero consorzio comunale di Enna" => Ok(Self::Enna), "Libero consorzio comunale di Ragusa" => Ok(Self::Ragusa), "Libero consorzio comunale di Siracusa" => Ok(Self::Siracusa), "Libero consorzio comunale di Trapani" => Ok(Self::Trapani), "Metropolitan City of Bari" => Ok(Self::Bari), "Metropolitan City of Bologna" => Ok(Self::Bologna), "Metropolitan City of Cagliari" => Ok(Self::Cagliari), "Metropolitan City of Catania" => Ok(Self::Catania), "Metropolitan City of Florence" => Ok(Self::Florence), "Metropolitan City of Genoa" => Ok(Self::Genoa), "Metropolitan City of Messina" => Ok(Self::Messina), "Metropolitan City of Milan" => Ok(Self::Milan), "Metropolitan City of Naples" => Ok(Self::Naples), "Metropolitan City of Palermo" => Ok(Self::Palermo), "Metropolitan City of Reggio Calabria" => Ok(Self::ReggioCalabria), "Metropolitan City of Rome" => Ok(Self::Rome), "Metropolitan City of Turin" => Ok(Self::Turin), "Metropolitan City of Venice" => Ok(Self::Venice), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for JapanStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state = parse_state_enum::<Self>(value, "JapanStatesAbbreviation", "address.state")?; match state.as_str() { "aichi" => Ok(Self::Aichi), "akita" => Ok(Self::Akita), "aomori" => Ok(Self::Aomori), "chiba" => Ok(Self::Chiba), "ehime" => Ok(Self::Ehime), "fukui" => Ok(Self::Fukui), "fukuoka" => Ok(Self::Fukuoka), "fukushima" | "hukusima" => Ok(Self::Fukushima), "gifu" => Ok(Self::Gifu), "gunma" => Ok(Self::Gunma), "hiroshima" => Ok(Self::Hiroshima), "hokkaido" => Ok(Self::Hokkaido), "hyogo" => Ok(Self::Hyogo), "ibaraki" => Ok(Self::Ibaraki), "ishikawa" => Ok(Self::Ishikawa), "iwate" => Ok(Self::Iwate), "kagawa" => Ok(Self::Kagawa), "kagoshima" => Ok(Self::Kagoshima), "kanagawa" => Ok(Self::Kanagawa), "kochi" => Ok(Self::Kochi), "kumamoto" => Ok(Self::Kumamoto), "kyoto" => Ok(Self::Kyoto), "mie" => Ok(Self::Mie), "miyagi" => Ok(Self::Miyagi), "miyazaki" => Ok(Self::Miyazaki), "nagano" => Ok(Self::Nagano), "nagasaki" => Ok(Self::Nagasaki), "nara" => Ok(Self::Nara), "niigata" => Ok(Self::Niigata), "oita" => Ok(Self::Oita), "okayama" => Ok(Self::Okayama), "okinawa" => Ok(Self::Okinawa), "osaka" => Ok(Self::Osaka), "saga" => Ok(Self::Saga), "saitama" => Ok(Self::Saitama), "shiga" => Ok(Self::Shiga), "shimane" => Ok(Self::Shimane), "shizuoka" => Ok(Self::Shizuoka), "tochigi" => Ok(Self::Tochigi), "tokushima" | "tokusima" => Ok(Self::Tokusima), "tokyo" => Ok(Self::Tokyo), "tottori" => Ok(Self::Tottori), "toyama" => Ok(Self::Toyama), "wakayama" => Ok(Self::Wakayama), "yamagata" => Ok(Self::Yamagata), "yamaguchi" => Ok(Self::Yamaguchi), "yamanashi" => Ok(Self::Yamanashi), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } impl ForeignTryFrom<String> for ThailandStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state = parse_state_enum::<Self>(value, "ThailandStatesAbbreviation", "address.state")?; match state.as_str() { "amnatcharoen" => Ok(Self::AmnatCharoen), "angthong" => Ok(Self::AngThong), "bangkok" => Ok(Self::Bangkok), "buengkan" => Ok(Self::BuengKan), "buriram" => Ok(Self::BuriRam), "chachoengsao" => Ok(Self::Chachoengsao), "chainat" => Ok(Self::ChaiNat), "chaiyaphum" => Ok(Self::Chaiyaphum), "chanthaburi" => Ok(Self::Chanthaburi), "chiangmai" => Ok(Self::ChiangMai), "chiangrai" => Ok(Self::ChiangRai), "chonburi" => Ok(Self::ChonBuri), "chumphon" => Ok(Self::Chumphon), "kalasin" => Ok(Self::Kalasin), "kamphaengphet" => Ok(Self::KamphaengPhet), "kanchanaburi" => Ok(Self::Kanchanaburi), "khonkaen" => Ok(Self::KhonKaen), "krabi" => Ok(Self::Krabi), "lampang" => Ok(Self::Lampang), "lamphun" => Ok(Self::Lamphun), "loei" => Ok(Self::Loei), "lopburi" => Ok(Self::LopBuri), "maehongson" => Ok(Self::MaeHongSon), "mahasarakham" => Ok(Self::MahaSarakham), "mukdahan" => Ok(Self::Mukdahan), "nakhonnayok" => Ok(Self::NakhonNayok), "nakhonpathom" => Ok(Self::NakhonPathom), "nakhonphanom" => Ok(Self::NakhonPhanom), "nakhonratchasima" => Ok(Self::NakhonRatchasima), "nakhonsawan" => Ok(Self::NakhonSawan), "nakhonsithammarat" => Ok(Self::NakhonSiThammarat), "nan" => Ok(Self::Nan), "narathiwat" => Ok(Self::Narathiwat), "nongbualamphu" => Ok(Self::NongBuaLamPhu), "nongkhai" => Ok(Self::NongKhai), "nonthaburi" => Ok(Self::Nonthaburi), "pathumthani" => Ok(Self::PathumThani), "pattani" => Ok(Self::Pattani), "phangnga" => Ok(Self::Phangnga), "phatthalung" => Ok(Self::Phatthalung), "phayao" => Ok(Self::Phayao), "phatthaya" => Ok(Self::Phatthaya), "phetchabun" => Ok(Self::Phetchabun), "phetchaburi" => Ok(Self::Phetchaburi), "phichit" => Ok(Self::Phichit), "phitsanulok" => Ok(Self::Phitsanulok), "phrae" => Ok(Self::Phrae), "phuket" => Ok(Self::Phuket), "prachinburi" => Ok(Self::PrachinBuri), "phranakhonsiayutthaya" => Ok(Self::PhraNakhonSiAyutthaya), "prachuapkhirikhan" => Ok(Self::PrachuapKhiriKhan), "ranong" => Ok(Self::Ranong), "ratchaburi" => Ok(Self::Ratchaburi), "rayong" => Ok(Self::Rayong), "roiet" => Ok(Self::RoiEt), "sakaeo" => Ok(Self::SaKaeo), "sakonnakhon" => Ok(Self::SakonNakhon), "samutprakan" => Ok(Self::SamutPrakan), "samutsakhon" => Ok(Self::SamutSakhon), "samutsongkhram" => Ok(Self::SamutSongkhram), "saraburi" => Ok(Self::Saraburi), "satun" => Ok(Self::Satun), "sisaket" => Ok(Self::SiSaKet), "singburi" => Ok(Self::SingBuri), "songkhla" => Ok(Self::Songkhla), "sukhothai" => Ok(Self::Sukhothai), "suphanburi" => Ok(Self::SuphanBuri), "suratthani" => Ok(Self::SuratThani), "surin" => Ok(Self::Surin), "tak" => Ok(Self::Tak), "trang" => Ok(Self::Trang), "trat" => Ok(Self::Trat), "ubonratchathani" => Ok(Self::UbonRatchathani), "udonthani" => Ok(Self::UdonThani), "uthaithani" => Ok(Self::UthaiThani), "uttaradit" => Ok(Self::Uttaradit), "yala" => Ok(Self::Yala), "yasothon" => Ok(Self::Yasothon), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } impl ForeignTryFrom<String> for NorwayStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "NorwayStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Akershus" => Ok(Self::Akershus), "Buskerud" => Ok(Self::Buskerud), "Finnmark" => Ok(Self::Finnmark), "Hedmark" => Ok(Self::Hedmark), "Hordaland" => Ok(Self::Hordaland), "Jan Mayen" => Ok(Self::JanMayen), "Møre og Romsdal" => Ok(Self::MoreOgRomsdal), "Nord-Trøndelag" => Ok(Self::NordTrondelag), "Nordland" => Ok(Self::Nordland), "Oppland" => Ok(Self::Oppland), "Oslo" => Ok(Self::Oslo), "Rogaland" => Ok(Self::Rogaland), "Sogn og Fjordane" => Ok(Self::SognOgFjordane), "Svalbard" => Ok(Self::Svalbard), "Sør-Trøndelag" => Ok(Self::SorTrondelag), "Telemark" => Ok(Self::Telemark), "Troms" => Ok(Self::Troms), "Trøndelag" => Ok(Self::Trondelag), "Vest-Agder" => Ok(Self::VestAgder), "Vestfold" => Ok(Self::Vestfold), "Østfold" => Ok(Self::Ostfold), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for AlbaniaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "AlbaniaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Berat" => Ok(Self::Berat), "Dibër" => Ok(Self::Diber), "Durrës" => Ok(Self::Durres), "Elbasan" => Ok(Self::Elbasan), "Fier" => Ok(Self::Fier), "Gjirokastër" => Ok(Self::Gjirokaster), "Korçë" => Ok(Self::Korce), "Kukës" => Ok(Self::Kukes), "Lezhë" => Ok(Self::Lezhe), "Shkodër" => Ok(Self::Shkoder), "Tiranë" => Ok(Self::Tirane), "Vlorë" => Ok(Self::Vlore), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for AndorraStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "AndorraStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Andorra la Vella" => Ok(Self::AndorraLaVella), "Canillo" => Ok(Self::Canillo), "Encamp" => Ok(Self::Encamp), "Escaldes-Engordany" => Ok(Self::EscaldesEngordany), "La Massana" => Ok(Self::LaMassana), "Ordino" => Ok(Self::Ordino), "Sant Julià de Lòria" => Ok(Self::SantJuliaDeLoria), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for AustriaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "AustriaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Burgenland" => Ok(Self::Burgenland), "Carinthia" => Ok(Self::Carinthia), "Lower Austria" => Ok(Self::LowerAustria), "Salzburg" => Ok(Self::Salzburg), "Styria" => Ok(Self::Styria), "Tyrol" => Ok(Self::Tyrol), "Upper Austria" => Ok(Self::UpperAustria), "Vienna" => Ok(Self::Vienna), "Vorarlberg" => Ok(Self::Vorarlberg), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for RomaniaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "RomaniaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Alba" => Ok(Self::Alba), "Arad County" => Ok(Self::AradCounty), "Argeș" => Ok(Self::Arges), "Bacău County" => Ok(Self::BacauCounty), "Bihor County" => Ok(Self::BihorCounty), "Bistrița-Năsăud County" => Ok(Self::BistritaNasaudCounty), "Botoșani County" => Ok(Self::BotosaniCounty), "Brăila" => Ok(Self::Braila), "Brașov County" => Ok(Self::BrasovCounty), "Bucharest" => Ok(Self::Bucharest), "Buzău County" => Ok(Self::BuzauCounty), "Caraș-Severin County" => Ok(Self::CarasSeverinCounty), "Cluj County" => Ok(Self::ClujCounty), "Constanța County" => Ok(Self::ConstantaCounty), "Covasna County" => Ok(Self::CovasnaCounty), "Călărași County" => Ok(Self::CalarasiCounty), "Dolj County" => Ok(Self::DoljCounty), "Dâmbovița County" => Ok(Self::DambovitaCounty), "Galați County" => Ok(Self::GalatiCounty), "Giurgiu County" => Ok(Self::GiurgiuCounty), "Gorj County" => Ok(Self::GorjCounty), "Harghita County" => Ok(Self::HarghitaCounty), "Hunedoara County" => Ok(Self::HunedoaraCounty), "Ialomița County" => Ok(Self::IalomitaCounty), "Iași County" => Ok(Self::IasiCounty), "Ilfov County" => Ok(Self::IlfovCounty), "Mehedinți County" => Ok(Self::MehedintiCounty), "Mureș County" => Ok(Self::MuresCounty), "Neamț County" => Ok(Self::NeamtCounty), "Olt County" => Ok(Self::OltCounty), "Prahova County" => Ok(Self::PrahovaCounty), "Satu Mare County" => Ok(Self::SatuMareCounty), "Sibiu County" => Ok(Self::SibiuCounty), "Suceava County" => Ok(Self::SuceavaCounty), "Sălaj County" => Ok(Self::SalajCounty), "Teleorman County" => Ok(Self::TeleormanCounty), "Timiș County" => Ok(Self::TimisCounty), "Tulcea County" => Ok(Self::TulceaCounty), "Vaslui County" => Ok(Self::VasluiCounty), "Vrancea County" => Ok(Self::VranceaCounty), "Vâlcea County" => Ok(Self::ValceaCounty), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for PortugalStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "PortugalStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Aveiro District" => Ok(Self::AveiroDistrict), "Azores" => Ok(Self::Azores), "Beja District" => Ok(Self::BejaDistrict), "Braga District" => Ok(Self::BragaDistrict), "Bragança District" => Ok(Self::BragancaDistrict), "Castelo Branco District" => Ok(Self::CasteloBrancoDistrict), "Coimbra District" => Ok(Self::CoimbraDistrict), "Faro District" => Ok(Self::FaroDistrict), "Guarda District" => Ok(Self::GuardaDistrict), "Leiria District" => Ok(Self::LeiriaDistrict), "Lisbon District" => Ok(Self::LisbonDistrict), "Madeira" => Ok(Self::Madeira), "Portalegre District" => Ok(Self::PortalegreDistrict), "Porto District" => Ok(Self::PortoDistrict), "Santarém District" => Ok(Self::SantaremDistrict), "Setúbal District" => Ok(Self::SetubalDistrict), "Viana do Castelo District" => Ok(Self::VianaDoCasteloDistrict), "Vila Real District" => Ok(Self::VilaRealDistrict), "Viseu District" => Ok(Self::ViseuDistrict), "Évora District" => Ok(Self::EvoraDistrict), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for SwitzerlandStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "SwitzerlandStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Aargau" => Ok(Self::Aargau), "Appenzell Ausserrhoden" => Ok(Self::AppenzellAusserrhoden), "Appenzell Innerrhoden" => Ok(Self::AppenzellInnerrhoden), "Basel-Landschaft" => Ok(Self::BaselLandschaft), "Canton of Fribourg" => Ok(Self::CantonOfFribourg), "Canton of Geneva" => Ok(Self::CantonOfGeneva), "Canton of Jura" => Ok(Self::CantonOfJura), "Canton of Lucerne" => Ok(Self::CantonOfLucerne), "Canton of Neuchâtel" => Ok(Self::CantonOfNeuchatel), "Canton of Schaffhausen" => Ok(Self::CantonOfSchaffhausen), "Canton of Solothurn" => Ok(Self::CantonOfSolothurn), "Canton of St. Gallen" => Ok(Self::CantonOfStGallen), "Canton of Valais" => Ok(Self::CantonOfValais), "Canton of Vaud" => Ok(Self::CantonOfVaud), "Canton of Zug" => Ok(Self::CantonOfZug), "Glarus" => Ok(Self::Glarus), "Graubünden" => Ok(Self::Graubunden), "Nidwalden" => Ok(Self::Nidwalden), "Obwalden" => Ok(Self::Obwalden), "Schwyz" => Ok(Self::Schwyz), "Thurgau" => Ok(Self::Thurgau), "Ticino" => Ok(Self::Ticino), "Uri" => Ok(Self::Uri), "canton of Bern" => Ok(Self::CantonOfBern), "canton of Zürich" => Ok(Self::CantonOfZurich), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for NorthMacedoniaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "NorthMacedoniaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Aerodrom Municipality" => Ok(Self::AerodromMunicipality), "Aračinovo Municipality" => Ok(Self::AracinovoMunicipality), "Berovo Municipality" => Ok(Self::BerovoMunicipality), "Bitola Municipality" => Ok(Self::BitolaMunicipality), "Bogdanci Municipality" => Ok(Self::BogdanciMunicipality), "Bogovinje Municipality" => Ok(Self::BogovinjeMunicipality), "Bosilovo Municipality" => Ok(Self::BosilovoMunicipality), "Brvenica Municipality" => Ok(Self::BrvenicaMunicipality), "Butel Municipality" => Ok(Self::ButelMunicipality), "Centar Municipality" => Ok(Self::CentarMunicipality), "Centar Župa Municipality" => Ok(Self::CentarZupaMunicipality), "Debarca Municipality" => Ok(Self::DebarcaMunicipality), "Delčevo Municipality" => Ok(Self::DelcevoMunicipality), "Demir Hisar Municipality" => Ok(Self::DemirHisarMunicipality), "Demir Kapija Municipality" => Ok(Self::DemirKapijaMunicipality), "Dojran Municipality" => Ok(Self::DojranMunicipality), "Dolneni Municipality" => Ok(Self::DolneniMunicipality), "Drugovo Municipality" => Ok(Self::DrugovoMunicipality), "Gazi Baba Municipality" => Ok(Self::GaziBabaMunicipality), "Gevgelija Municipality" => Ok(Self::GevgelijaMunicipality), "Gjorče Petrov Municipality" => Ok(Self::GjorcePetrovMunicipality), "Gostivar Municipality" => Ok(Self::GostivarMunicipality), "Gradsko Municipality" => Ok(Self::GradskoMunicipality), "Greater Skopje" => Ok(Self::GreaterSkopje), "Ilinden Municipality" => Ok(Self::IlindenMunicipality), "Jegunovce Municipality" => Ok(Self::JegunovceMunicipality), "Karbinci" => Ok(Self::Karbinci), "Karpoš Municipality" => Ok(Self::KarposMunicipality), "Kavadarci Municipality" => Ok(Self::KavadarciMunicipality), "Kisela Voda Municipality" => Ok(Self::KiselaVodaMunicipality), "Kičevo Municipality" => Ok(Self::KicevoMunicipality), "Konče Municipality" => Ok(Self::KonceMunicipality), "Kočani Municipality" => Ok(Self::KocaniMunicipality), "Kratovo Municipality" => Ok(Self::KratovoMunicipality), "Kriva Palanka Municipality" => Ok(Self::KrivaPalankaMunicipality), "Krivogaštani Municipality" => Ok(Self::KrivogastaniMunicipality), "Kruševo Municipality" => Ok(Self::KrusevoMunicipality), "Kumanovo Municipality" => Ok(Self::KumanovoMunicipality), "Lipkovo Municipality" => Ok(Self::LipkovoMunicipality), "Lozovo Municipality" => Ok(Self::LozovoMunicipality), "Makedonska Kamenica Municipality" => Ok(Self::MakedonskaKamenicaMunicipality), "Makedonski Brod Municipality" => Ok(Self::MakedonskiBrodMunicipality), "Mavrovo and Rostuša Municipality" => Ok(Self::MavrovoAndRostusaMunicipality), "Mogila Municipality" => Ok(Self::MogilaMunicipality), "Negotino Municipality" => Ok(Self::NegotinoMunicipality), "Novaci Municipality" => Ok(Self::NovaciMunicipality), "Novo Selo Municipality" => Ok(Self::NovoSeloMunicipality), "Ohrid Municipality" => Ok(Self::OhridMunicipality), "Oslomej Municipality" => Ok(Self::OslomejMunicipality), "Pehčevo Municipality" => Ok(Self::PehcevoMunicipality), "Petrovec Municipality" => Ok(Self::PetrovecMunicipality), "Plasnica Municipality" => Ok(Self::PlasnicaMunicipality), "Prilep Municipality" => Ok(Self::PrilepMunicipality), "Probištip Municipality" => Ok(Self::ProbishtipMunicipality), "Radoviš Municipality" => Ok(Self::RadovisMunicipality), "Rankovce Municipality" => Ok(Self::RankovceMunicipality), "Resen Municipality" => Ok(Self::ResenMunicipality), "Rosoman Municipality" => Ok(Self::RosomanMunicipality), "Saraj Municipality" => Ok(Self::SarajMunicipality), "Sopište Municipality" => Ok(Self::SopisteMunicipality), "Staro Nagoričane Municipality" => Ok(Self::StaroNagoricaneMunicipality), "Struga Municipality" => Ok(Self::StrugaMunicipality), "Strumica Municipality" => Ok(Self::StrumicaMunicipality), "Studeničani Municipality" => Ok(Self::StudenicaniMunicipality), "Sveti Nikole Municipality" => Ok(Self::SvetiNikoleMunicipality), "Tearce Municipality" => Ok(Self::TearceMunicipality), "Tetovo Municipality" => Ok(Self::TetovoMunicipality), "Valandovo Municipality" => Ok(Self::ValandovoMunicipality), "Vasilevo Municipality" => Ok(Self::VasilevoMunicipality), "Veles Municipality" => Ok(Self::VelesMunicipality), "Vevčani Municipality" => Ok(Self::VevcaniMunicipality), "Vinica Municipality" => Ok(Self::VinicaMunicipality), "Vraneštica Municipality" => Ok(Self::VranesticaMunicipality), "Vrapčište Municipality" => Ok(Self::VrapcisteMunicipality), "Zajas Municipality" => Ok(Self::ZajasMunicipality), "Zelenikovo Municipality" => Ok(Self::ZelenikovoMunicipality), "Zrnovci Municipality" => Ok(Self::ZrnovciMunicipality), "Čair Municipality" => Ok(Self::CairMunicipality), "Čaška Municipality" => Ok(Self::CaskaMunicipality), "Češinovo-Obleševo Municipality" => Ok(Self::CesinovoOblesevoMunicipality), "Čučer-Sandevo Municipality" => Ok(Self::CucerSandevoMunicipality), "Štip Municipality" => Ok(Self::StipMunicipality), "Šuto Orizari Municipality" => Ok(Self::ShutoOrizariMunicipality), "Želino Municipality" => Ok(Self::ZelinoMunicipality), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for MontenegroStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "MontenegroStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Andrijevica Municipality" => Ok(Self::AndrijevicaMunicipality), "Bar Municipality" => Ok(Self::BarMunicipality), "Berane Municipality" => Ok(Self::BeraneMunicipality), "Bijelo Polje Municipality" => Ok(Self::BijeloPoljeMunicipality), "Budva Municipality" => Ok(Self::BudvaMunicipality), "Danilovgrad Municipality" => Ok(Self::DanilovgradMunicipality), "Gusinje Municipality" => Ok(Self::GusinjeMunicipality), "Kolašin Municipality" => Ok(Self::KolasinMunicipality), "Kotor Municipality" => Ok(Self::KotorMunicipality), "Mojkovac Municipality" => Ok(Self::MojkovacMunicipality), "Nikšić Municipality" => Ok(Self::NiksicMunicipality), "Petnjica Municipality" => Ok(Self::PetnjicaMunicipality), "Plav Municipality" => Ok(Self::PlavMunicipality), "Pljevlja Municipality" => Ok(Self::PljevljaMunicipality), "Plužine Municipality" => Ok(Self::PlužineMunicipality), "Podgorica Municipality" => Ok(Self::PodgoricaMunicipality), "Rožaje Municipality" => Ok(Self::RožajeMunicipality), "Tivat Municipality" => Ok(Self::TivatMunicipality), "Ulcinj Municipality" => Ok(Self::UlcinjMunicipality), "Žabljak Municipality" => Ok(Self::ŽabljakMunicipality), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for MonacoStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "MonacoStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Monaco" => Ok(Self::Monaco), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for NetherlandsStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "NetherlandsStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Bonaire" => Ok(Self::Bonaire), "Drenthe" => Ok(Self::Drenthe), "Flevoland" => Ok(Self::Flevoland), "Friesland" => Ok(Self::Friesland), "Gelderland" => Ok(Self::Gelderland), "Groningen" => Ok(Self::Groningen), "Limburg" => Ok(Self::Limburg), "North Brabant" => Ok(Self::NorthBrabant), "North Holland" => Ok(Self::NorthHolland), "Overijssel" => Ok(Self::Overijssel), "Saba" => Ok(Self::Saba), "Sint Eustatius" => Ok(Self::SintEustatius), "South Holland" => Ok(Self::SouthHolland), "Utrecht" => Ok(Self::Utrecht), "Zeeland" => Ok(Self::Zeeland), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for NewZealandStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state = parse_state_enum::<Self>(value, "NewZealandStatesAbbreviation", "address.state")?; match state.as_str() { "auckland" | "tamakimakaurau" => Ok(Self::Auckland), "bayofplenty" | "toimoana" => Ok(Self::BayOfPlenty), "canterbury" | "waitaha" => Ok(Self::Canterbury), "chathamislandsterritory" | "wharekauri" => Ok(Self::ChathamIslandsTerritory), "gisborne" | "tetairawhiti" => Ok(Self::Gisborne), "hawkesbay" | "tematauamaui" => Ok(Self::HawkesBay), "manawatuwanganui" => Ok(Self::ManawatūWhanganui), "marlborough" => Ok(Self::Marlborough), "nelson" | "whakatu" => Ok(Self::Nelson), "northland" | "tetaitokerau" => Ok(Self::Northland), "otago" | "otakou" => Ok(Self::Otago), "southland" | "tetaiaotonga" => Ok(Self::Southland), "taranaki" => Ok(Self::Taranaki), "tasman" | "tetaioaorere" => Ok(Self::Tasman), "waikato" => Ok(Self::Waikato), "greaterwellington" | "tepanematuataiao" => Ok(Self::GreaterWellington), "westcoast" | "tetaiopoutini" => Ok(Self::WestCoast), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } impl ForeignTryFrom<String> for SingaporeStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state = parse_state_enum::<Self>(value, "SingaporeStatesAbbreviation", "address.state")?; match state.as_str() { "centralsingapore" => Ok(Self::CentralSingapore), "northeast" => Ok(Self::NorthEast), "northwest" => Ok(Self::NorthWest), "southeast" => Ok(Self::SouthEast), "southwest" => Ok(Self::SouthWest), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } impl ForeignTryFrom<String> for PhilippinesStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state = parse_state_enum::<Self>(value, "PhilippinesStatesAbbreviation", "address.state")?; match state.as_str() { "abra" => Ok(Self::Abra), "agusandelnorte" | "hilagangagusan" => Ok(Self::AgusanDelNorte), "agusandelsur" | "timogagusan" => Ok(Self::AgusanDelSur), "aklan" => Ok(Self::Aklan), "albay" => Ok(Self::Albay), "antique" | "antike" => Ok(Self::Antique), "apayao" | "apayaw" => Ok(Self::Apayao), "aurora" => Ok(Self::Aurora), "autonomousregioninmuslimmindanao" | "nagsasarilingrehiyonngmuslimsamindanaw" => { Ok(Self::AutonomousRegionInMuslimMindanao) } "basilan" => Ok(Self::Basilan), "bataan" => Ok(Self::Bataan), "batanes" => Ok(Self::Batanes), "batangas" => Ok(Self::Batangas), "benguet" | "benget" => Ok(Self::Benguet), "bicol" | "rehiyonngbikol" => Ok(Self::Bicol), "biliran" => Ok(Self::Biliran), "bohol" => Ok(Self::Bohol), "bukidnon" => Ok(Self::Bukidnon), "bulacan" | "bulakan" => Ok(Self::Bulacan), "cagayan" | "kagayan" => Ok(Self::Cagayan), "cagayanvalley" | "rehiyonnglambakngkagayan" => Ok(Self::CagayanValley), "calabarzon" | "rehiyonngcalabarzon" => Ok(Self::Calabarzon), "camarinesnorte" | "hilagangkamarines" => Ok(Self::CamarinesNorte), "camarinessur" | "timogkamarines" => Ok(Self::CamarinesSur), "camiguin" | "kamigin" => Ok(Self::Camiguin), "capiz" | "kapis" => Ok(Self::Capiz), "caraga" | "rehiyonngkaraga" => Ok(Self::Caraga), "catanduanes" | "katanduanes" => Ok(Self::Catanduanes), "cavite" | "kabite" => Ok(Self::Cavite), "cebu" | "sebu" => Ok(Self::Cebu), "centralluzon" | "rehiyonnggitnangluzon" => Ok(Self::CentralLuzon), "centralvisayas" | "rehiyonnggitnangbisaya" => Ok(Self::CentralVisayas), "cordilleraadministrativeregion" | "rehiyonngadministratibongkordilyera" => { Ok(Self::CordilleraAdministrativeRegion) } "cotabato" | "kotabato" => Ok(Self::Cotabato), "davao" | "rehiyonngdabaw" => Ok(Self::Davao), "davaooccidental" | "kanlurangdabaw" => Ok(Self::DavaoOccidental), "davaooriental" | "silangangdabaw" => Ok(Self::DavaoOriental), "davaodeoro" => Ok(Self::DavaoDeOro), "davaodelnorte" | "hilagangdabaw" => Ok(Self::DavaoDelNorte), "davaodelsur" | "timogdabaw" => Ok(Self::DavaoDelSur), "dinagatislands" | "pulongdinagat" => Ok(Self::DinagatIslands), "easternsamar" | "silangangsamar" => Ok(Self::EasternSamar), "easternvisayas" | "rehiyonngsilangangbisaya" => Ok(Self::EasternVisayas), "guimaras" | "gimaras" => Ok(Self::Guimaras), "hilagangiloko" | "ilocosnorte" => Ok(Self::HilagangIloko), "hilaganglanaw" | "lanaodelnorte" => Ok(Self::HilagangLanaw), "hilagangmagindanaw" | "maguindanaodelnorte" => Ok(Self::HilagangMagindanaw), "hilagangsamar" | "northernsamar" => Ok(Self::HilagangSamar), "hilagangsambuwangga" | "zamboangadelnorte" => Ok(Self::HilagangSambuwangga), "hilagangsurigaw" | "surigaodelnorte" => Ok(Self::HilagangSurigaw), "ifugao" | "ipugaw" => Ok(Self::Ifugao), "ilocos" | "rehiyonngiloko" => Ok(Self::Ilocos), "ilocossur" | "timogiloko" => Ok(Self::IlocosSur), "iloilo" | "iloylo" => Ok(Self::Iloilo), "isabela" => Ok(Self::Isabela), "kalinga" => Ok(Self::Kalinga), "kanlurangmindoro" | "mindorooccidental" => Ok(Self::KanlurangMindoro), "kanlurangmisamis" | "misamisoriental" => Ok(Self::KanlurangMisamis), "kanlurangnegros" | "negrosoccidental" => Ok(Self::KanlurangNegros), "katimogangleyte" | "southernleyte" => Ok(Self::KatimogangLeyte), "keson" | "quezon" => Ok(Self::Keson), "kirino" | "quirino" => Ok(Self::Kirino), "launion" => Ok(Self::LaUnion), "laguna" => Ok(Self::Laguna), "lalawigangbulubundukin" | "mountainprovince" => Ok(Self::LalawigangBulubundukin), "lanaodelsur" | "timoglanaw" => Ok(Self::LanaoDelSur), "leyte" => Ok(Self::Leyte), "maguidanaodelsur" | "timogmaguindanao" => Ok(Self::MaguindanaoDelSur), "marinduque" => Ok(Self::Marinduque), "masbate" => Ok(Self::Masbate), "mimaropa" | "rehiyonngmimaropa" => Ok(Self::Mimaropa), "mindorooriental" | "silingangmindoro" => Ok(Self::MindoroOriental), "misamisoccidental" | "silingangmisamis" => Ok(Self::MisamisOccidental), "nationalcapitalregion" | "pambansangpunonglungsod" => Ok(Self::NationalCapitalRegion), "negrosoriental" | "silingangnegros" => Ok(Self::NegrosOriental), "northernmindanao" | "rehiyonnghilagangmindanao" => Ok(Self::NorthernMindanao), "nuevaecija" | "nuwevaesiha" => Ok(Self::NuevaEcija), "nuevavizcaya" => Ok(Self::NuevaVizcaya), "palawan" => Ok(Self::Palawan), "pampanga" => Ok(Self::Pampanga), "pangasinan" => Ok(Self::Pangasinan), "rehiyonngkanlurangbisaya" | "westernvisayas" => Ok(Self::RehiyonNgKanlurangBisaya), "rehiyonngsoccsksargen" | "soccsksargen" => Ok(Self::RehiyonNgSoccsksargen), "rehiyonngtangwayngsambuwangga" | "zamboangapeninsula" => { Ok(Self::RehiyonNgTangwayNgSambuwangga) } "risal" | "rizal" => Ok(Self::Risal), "romblon" => Ok(Self::Romblon), "samar" => Ok(Self::Samar), "sambales" | "zambales" => Ok(Self::Sambales), "sambuwanggasibugay" | "zamboangasibugay" => Ok(Self::SambuwanggaSibugay), "sarangani" => Ok(Self::Sarangani), "siquijor" | "sikihor" => Ok(Self::Sikihor), "sorsogon" => Ok(Self::Sorsogon), "southcotabato" | "timogkotabato" => Ok(Self::SouthCotabato), "sultankudarat" => Ok(Self::SultanKudarat), "sulu" => Ok(Self::Sulu), "surigaodelsur" | "timogsurigaw" => Ok(Self::SurigaoDelSur), "tarlac" => Ok(Self::Tarlac), "tawitawi" => Ok(Self::TawiTawi), "timogsambuwangga" | "zamboangadelsur" => Ok(Self::TimogSambuwangga), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } impl ForeignTryFrom<String> for IndiaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state = parse_state_enum::<Self>(value, "IndiaStatesAbbreviation", "address.state")?; match state.as_str() { "andamanandnicobarislands" => Ok(Self::AndamanAndNicobarIslands), "andhrapradesh" => Ok(Self::AndhraPradesh), "arunachalpradesh" => Ok(Self::ArunachalPradesh), "assam" => Ok(Self::Assam), "bihar" => Ok(Self::Bihar), "chandigarh" => Ok(Self::Chandigarh), "chhattisgarh" => Ok(Self::Chhattisgarh), "dadraandnagarhavelianddamananddiu" => Ok(Self::DadraAndNagarHaveliAndDamanAndDiu), "delhi" => Ok(Self::Delhi), "goa" => Ok(Self::Goa), "gujarat" => Ok(Self::Gujarat), "haryana" => Ok(Self::Haryana), "himachalpradesh" => Ok(Self::HimachalPradesh), "jammuandkashmir" => Ok(Self::JammuAndKashmir), "jharkhand" => Ok(Self::Jharkhand), "karnataka" => Ok(Self::Karnataka), "kerala" => Ok(Self::Kerala), "ladakh" => Ok(Self::Ladakh), "lakshadweep" => Ok(Self::Lakshadweep), "madhyapradesh" => Ok(Self::MadhyaPradesh), "maharashtra" => Ok(Self::Maharashtra), "manipur" => Ok(Self::Manipur), "meghalaya" => Ok(Self::Meghalaya), "mizoram" => Ok(Self::Mizoram), "nagaland" => Ok(Self::Nagaland), "odisha" => Ok(Self::Odisha), "puducherry" | "pondicherry" => Ok(Self::Puducherry), "punjab" => Ok(Self::Punjab), "rajasthan" => Ok(Self::Rajasthan), "sikkim" => Ok(Self::Sikkim), "tamilnadu" => Ok(Self::TamilNadu), "telangana" => Ok(Self::Telangana), "tripura" => Ok(Self::Tripura), "uttarpradesh" => Ok(Self::UttarPradesh), "uttarakhand" => Ok(Self::Uttarakhand), "westbengal" => Ok(Self::WestBengal), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } impl ForeignTryFrom<String> for MoldovaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "MoldovaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Anenii Noi District" => Ok(Self::AneniiNoiDistrict), "Basarabeasca District" => Ok(Self::BasarabeascaDistrict), "Bender Municipality" => Ok(Self::BenderMunicipality), "Briceni District" => Ok(Self::BriceniDistrict), "Bălți Municipality" => Ok(Self::BălțiMunicipality), "Cahul District" => Ok(Self::CahulDistrict), "Cantemir District" => Ok(Self::CantemirDistrict), "Chișinău Municipality" => Ok(Self::ChișinăuMunicipality), "Cimișlia District" => Ok(Self::CimișliaDistrict), "Criuleni District" => Ok(Self::CriuleniDistrict), "Călărași District" => Ok(Self::CălărașiDistrict), "Căușeni District" => Ok(Self::CăușeniDistrict), "Dondușeni District" => Ok(Self::DondușeniDistrict), "Drochia District" => Ok(Self::DrochiaDistrict), "Dubăsari District" => Ok(Self::DubăsariDistrict), "Edineț District" => Ok(Self::EdinețDistrict), "Florești District" => Ok(Self::FloreștiDistrict), "Fălești District" => Ok(Self::FăleștiDistrict), "Găgăuzia" => Ok(Self::Găgăuzia), "Glodeni District" => Ok(Self::GlodeniDistrict), "Hîncești District" => Ok(Self::HînceștiDistrict), "Ialoveni District" => Ok(Self::IaloveniDistrict), "Nisporeni District" => Ok(Self::NisporeniDistrict), "Ocnița District" => Ok(Self::OcnițaDistrict), "Orhei District" => Ok(Self::OrheiDistrict), "Rezina District" => Ok(Self::RezinaDistrict), "Rîșcani District" => Ok(Self::RîșcaniDistrict), "Soroca District" => Ok(Self::SorocaDistrict), "Strășeni District" => Ok(Self::StrășeniDistrict), "Sîngerei District" => Ok(Self::SîngereiDistrict), "Taraclia District" => Ok(Self::TaracliaDistrict), "Telenești District" => Ok(Self::TeleneștiDistrict), "Transnistria Autonomous Territorial Unit" => { Ok(Self::TransnistriaAutonomousTerritorialUnit) } "Ungheni District" => Ok(Self::UngheniDistrict), "Șoldănești District" => Ok(Self::ȘoldăneștiDistrict), "Ștefan Vodă District" => Ok(Self::ȘtefanVodăDistrict), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for LithuaniaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "LithuaniaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Akmenė District Municipality" => Ok(Self::AkmeneDistrictMunicipality), "Alytus City Municipality" => Ok(Self::AlytusCityMunicipality), "Alytus County" => Ok(Self::AlytusCounty), "Alytus District Municipality" => Ok(Self::AlytusDistrictMunicipality), "Birštonas Municipality" => Ok(Self::BirstonasMunicipality), "Biržai District Municipality" => Ok(Self::BirzaiDistrictMunicipality), "Druskininkai municipality" => Ok(Self::DruskininkaiMunicipality), "Elektrėnai municipality" => Ok(Self::ElektrenaiMunicipality), "Ignalina District Municipality" => Ok(Self::IgnalinaDistrictMunicipality), "Jonava District Municipality" => Ok(Self::JonavaDistrictMunicipality), "Joniškis District Municipality" => Ok(Self::JoniskisDistrictMunicipality), "Jurbarkas District Municipality" => Ok(Self::JurbarkasDistrictMunicipality), "Kaišiadorys District Municipality" => Ok(Self::KaisiadorysDistrictMunicipality), "Kalvarija municipality" => Ok(Self::KalvarijaMunicipality), "Kaunas City Municipality" => Ok(Self::KaunasCityMunicipality), "Kaunas County" => Ok(Self::KaunasCounty), "Kaunas District Municipality" => Ok(Self::KaunasDistrictMunicipality), "Kazlų Rūda municipality" => Ok(Self::KazluRudaMunicipality), "Kelmė District Municipality" => Ok(Self::KelmeDistrictMunicipality), "Klaipeda City Municipality" => Ok(Self::KlaipedaCityMunicipality), "Klaipėda County" => Ok(Self::KlaipedaCounty), "Klaipėda District Municipality" => Ok(Self::KlaipedaDistrictMunicipality), "Kretinga District Municipality" => Ok(Self::KretingaDistrictMunicipality), "Kupiškis District Municipality" => Ok(Self::KupiskisDistrictMunicipality), "Kėdainiai District Municipality" => Ok(Self::KedainiaiDistrictMunicipality), "Lazdijai District Municipality" => Ok(Self::LazdijaiDistrictMunicipality), "Marijampolė County" => Ok(Self::MarijampoleCounty), "Marijampolė Municipality" => Ok(Self::MarijampoleMunicipality), "Mažeikiai District Municipality" => Ok(Self::MazeikiaiDistrictMunicipality), "Molėtai District Municipality" => Ok(Self::MoletaiDistrictMunicipality), "Neringa Municipality" => Ok(Self::NeringaMunicipality), "Pagėgiai municipality" => Ok(Self::PagegiaiMunicipality), "Pakruojis District Municipality" => Ok(Self::PakruojisDistrictMunicipality), "Palanga City Municipality" => Ok(Self::PalangaCityMunicipality), "Panevėžys City Municipality" => Ok(Self::PanevezysCityMunicipality), "Panevėžys County" => Ok(Self::PanevezysCounty), "Panevėžys District Municipality" => Ok(Self::PanevezysDistrictMunicipality), "Pasvalys District Municipality" => Ok(Self::PasvalysDistrictMunicipality), "Plungė District Municipality" => Ok(Self::PlungeDistrictMunicipality), "Prienai District Municipality" => Ok(Self::PrienaiDistrictMunicipality), "Radviliškis District Municipality" => Ok(Self::RadviliskisDistrictMunicipality), "Raseiniai District Municipality" => Ok(Self::RaseiniaiDistrictMunicipality), "Rietavas municipality" => Ok(Self::RietavasMunicipality), "Rokiškis District Municipality" => Ok(Self::RokiskisDistrictMunicipality), "Skuodas District Municipality" => Ok(Self::SkuodasDistrictMunicipality), "Tauragė County" => Ok(Self::TaurageCounty), "Tauragė District Municipality" => Ok(Self::TaurageDistrictMunicipality), "Telšiai County" => Ok(Self::TelsiaiCounty), "Telšiai District Municipality" => Ok(Self::TelsiaiDistrictMunicipality), "Trakai District Municipality" => Ok(Self::TrakaiDistrictMunicipality), "Ukmergė District Municipality" => Ok(Self::UkmergeDistrictMunicipality), "Utena County" => Ok(Self::UtenaCounty), "Utena District Municipality" => Ok(Self::UtenaDistrictMunicipality), "Varėna District Municipality" => Ok(Self::VarenaDistrictMunicipality), "Vilkaviškis District Municipality" => Ok(Self::VilkaviskisDistrictMunicipality), "Vilnius City Municipality" => Ok(Self::VilniusCityMunicipality), "Vilnius County" => Ok(Self::VilniusCounty), "Vilnius District Municipality" => Ok(Self::VilniusDistrictMunicipality), "Visaginas Municipality" => Ok(Self::VisaginasMunicipality), "Zarasai District Municipality" => Ok(Self::ZarasaiDistrictMunicipality), "Šakiai District Municipality" => Ok(Self::SakiaiDistrictMunicipality), "Šalčininkai District Municipality" => Ok(Self::SalcininkaiDistrictMunicipality), "Šiauliai City Municipality" => Ok(Self::SiauliaiCityMunicipality), "Šiauliai County" => Ok(Self::SiauliaiCounty), "Šiauliai District Municipality" => Ok(Self::SiauliaiDistrictMunicipality), "Šilalė District Municipality" => Ok(Self::SilaleDistrictMunicipality), "Šilutė District Municipality" => Ok(Self::SiluteDistrictMunicipality), "Širvintos District Municipality" => Ok(Self::SirvintosDistrictMunicipality), "Švenčionys District Municipality" => Ok(Self::SvencionysDistrictMunicipality), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for LiechtensteinStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "LiechtensteinStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Balzers" => Ok(Self::Balzers), "Eschen" => Ok(Self::Eschen), "Gamprin" => Ok(Self::Gamprin), "Mauren" => Ok(Self::Mauren), "Planken" => Ok(Self::Planken), "Ruggell" => Ok(Self::Ruggell), "Schaan" => Ok(Self::Schaan), "Schellenberg" => Ok(Self::Schellenberg), "Triesen" => Ok(Self::Triesen), "Triesenberg" => Ok(Self::Triesenberg), "Vaduz" => Ok(Self::Vaduz), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for LatviaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "LatviaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Aglona Municipality" => Ok(Self::AglonaMunicipality), "Aizkraukle Municipality" => Ok(Self::AizkraukleMunicipality), "Aizpute Municipality" => Ok(Self::AizputeMunicipality), "Aknīste Municipality" => Ok(Self::AknīsteMunicipality), "Aloja Municipality" => Ok(Self::AlojaMunicipality), "Alsunga Municipality" => Ok(Self::AlsungaMunicipality), "Alūksne Municipality" => Ok(Self::AlūksneMunicipality), "Amata Municipality" => Ok(Self::AmataMunicipality), "Ape Municipality" => Ok(Self::ApeMunicipality), "Auce Municipality" => Ok(Self::AuceMunicipality), "Babīte Municipality" => Ok(Self::BabīteMunicipality), "Baldone Municipality" => Ok(Self::BaldoneMunicipality), "Baltinava Municipality" => Ok(Self::BaltinavaMunicipality), "Balvi Municipality" => Ok(Self::BalviMunicipality), "Bauska Municipality" => Ok(Self::BauskaMunicipality), "Beverīna Municipality" => Ok(Self::BeverīnaMunicipality), "Brocēni Municipality" => Ok(Self::BrocēniMunicipality), "Burtnieki Municipality" => Ok(Self::BurtniekiMunicipality), "Carnikava Municipality" => Ok(Self::CarnikavaMunicipality), "Cesvaine Municipality" => Ok(Self::CesvaineMunicipality), "Cibla Municipality" => Ok(Self::CiblaMunicipality), "Cēsis Municipality" => Ok(Self::CēsisMunicipality), "Dagda Municipality" => Ok(Self::DagdaMunicipality), "Daugavpils" => Ok(Self::Daugavpils), "Daugavpils Municipality" => Ok(Self::DaugavpilsMunicipality), "Dobele Municipality" => Ok(Self::DobeleMunicipality), "Dundaga Municipality" => Ok(Self::DundagaMunicipality), "Durbe Municipality" => Ok(Self::DurbeMunicipality), "Engure Municipality" => Ok(Self::EngureMunicipality), "Garkalne Municipality" => Ok(Self::GarkalneMunicipality), "Grobiņa Municipality" => Ok(Self::GrobiņaMunicipality), "Gulbene Municipality" => Ok(Self::GulbeneMunicipality), "Iecava Municipality" => Ok(Self::IecavaMunicipality), "Ikšķile Municipality" => Ok(Self::IkšķileMunicipality), "Ilūkste Municipalityy" => Ok(Self::IlūksteMunicipality), "Inčukalns Municipality" => Ok(Self::InčukalnsMunicipality), "Jaunjelgava Municipality" => Ok(Self::JaunjelgavaMunicipality), "Jaunpiebalga Municipality" => Ok(Self::JaunpiebalgaMunicipality), "Jaunpils Municipality" => Ok(Self::JaunpilsMunicipality), "Jelgava" => Ok(Self::Jelgava), "Jelgava Municipality" => Ok(Self::JelgavaMunicipality), "Jēkabpils" => Ok(Self::Jēkabpils), "Jēkabpils Municipality" => Ok(Self::JēkabpilsMunicipality), "Jūrmala" => Ok(Self::Jūrmala), "Kandava Municipality" => Ok(Self::KandavaMunicipality), "Kocēni Municipality" => Ok(Self::KocēniMunicipality), "Koknese Municipality" => Ok(Self::KokneseMunicipality), "Krimulda Municipality" => Ok(Self::KrimuldaMunicipality), "Krustpils Municipality" => Ok(Self::KrustpilsMunicipality), "Krāslava Municipality" => Ok(Self::KrāslavaMunicipality), "Kuldīga Municipality" => Ok(Self::KuldīgaMunicipality), "Kārsava Municipality" => Ok(Self::KārsavaMunicipality), "Lielvārde Municipality" => Ok(Self::LielvārdeMunicipality), "Liepāja" => Ok(Self::Liepāja), "Limbaži Municipality" => Ok(Self::LimbažiMunicipality), "Lubāna Municipality" => Ok(Self::LubānaMunicipality), "Ludza Municipality" => Ok(Self::LudzaMunicipality), "Līgatne Municipality" => Ok(Self::LīgatneMunicipality), "Līvāni Municipality" => Ok(Self::LīvāniMunicipality), "Madona Municipality" => Ok(Self::MadonaMunicipality), "Mazsalaca Municipality" => Ok(Self::MazsalacaMunicipality), "Mālpils Municipality" => Ok(Self::MālpilsMunicipality), "Mārupe Municipality" => Ok(Self::MārupeMunicipality), "Mērsrags Municipality" => Ok(Self::MērsragsMunicipality), "Naukšēni Municipality" => Ok(Self::NaukšēniMunicipality), "Nereta Municipality" => Ok(Self::NeretaMunicipality), "Nīca Municipality" => Ok(Self::NīcaMunicipality), "Ogre Municipality" => Ok(Self::OgreMunicipality), "Olaine Municipality" => Ok(Self::OlaineMunicipality), "Ozolnieki Municipality" => Ok(Self::OzolniekiMunicipality), "Preiļi Municipality" => Ok(Self::PreiļiMunicipality), "Priekule Municipality" => Ok(Self::PriekuleMunicipality), "Priekuļi Municipality" => Ok(Self::PriekuļiMunicipality), "Pārgauja Municipality" => Ok(Self::PārgaujaMunicipality), "Pāvilosta Municipality" => Ok(Self::PāvilostaMunicipality), "Pļaviņas Municipality" => Ok(Self::PļaviņasMunicipality), "Rauna Municipality" => Ok(Self::RaunaMunicipality), "Riebiņi Municipality" => Ok(Self::RiebiņiMunicipality), "Riga" => Ok(Self::Riga), "Roja Municipality" => Ok(Self::RojaMunicipality), "Ropaži Municipality" => Ok(Self::RopažiMunicipality), "Rucava Municipality" => Ok(Self::RucavaMunicipality), "Rugāji Municipality" => Ok(Self::RugājiMunicipality), "Rundāle Municipality" => Ok(Self::RundāleMunicipality), "Rēzekne" => Ok(Self::Rēzekne), "Rēzekne Municipality" => Ok(Self::RēzekneMunicipality), "Rūjiena Municipality" => Ok(Self::RūjienaMunicipality), "Sala Municipality" => Ok(Self::SalaMunicipality), "Salacgrīva Municipality" => Ok(Self::SalacgrīvaMunicipality), "Salaspils Municipality" => Ok(Self::SalaspilsMunicipality), "Saldus Municipality" => Ok(Self::SaldusMunicipality), "Saulkrasti Municipality" => Ok(Self::SaulkrastiMunicipality), "Sigulda Municipality" => Ok(Self::SiguldaMunicipality), "Skrunda Municipality" => Ok(Self::SkrundaMunicipality), "Skrīveri Municipality" => Ok(Self::SkrīveriMunicipality), "Smiltene Municipality" => Ok(Self::SmilteneMunicipality), "Stopiņi Municipality" => Ok(Self::StopiņiMunicipality), "Strenči Municipality" => Ok(Self::StrenčiMunicipality), "Sēja Municipality" => Ok(Self::SējaMunicipality), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for MaltaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "MaltaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Attard" => Ok(Self::Attard), "Balzan" => Ok(Self::Balzan), "Birgu" => Ok(Self::Birgu), "Birkirkara" => Ok(Self::Birkirkara), "Birżebbuġa" => Ok(Self::Birżebbuġa), "Cospicua" => Ok(Self::Cospicua), "Dingli" => Ok(Self::Dingli), "Fgura" => Ok(Self::Fgura), "Floriana" => Ok(Self::Floriana), "Fontana" => Ok(Self::Fontana), "Gudja" => Ok(Self::Gudja), "Gżira" => Ok(Self::Gżira), "Għajnsielem" => Ok(Self::Għajnsielem), "Għarb" => Ok(Self::Għarb), "Għargħur" => Ok(Self::Għargħur), "Għasri" => Ok(Self::Għasri), "Għaxaq" => Ok(Self::Għaxaq), "Ħamrun" => Ok(Self::Ħamrun), "Iklin" => Ok(Self::Iklin), "Senglea" => Ok(Self::Senglea), "Kalkara" => Ok(Self::Kalkara), "Kerċem" => Ok(Self::Kerċem), "Kirkop" => Ok(Self::Kirkop), "Lija" => Ok(Self::Lija), "Luqa" => Ok(Self::Luqa), "Marsa" => Ok(Self::Marsa), "Marsaskala" => Ok(Self::Marsaskala), "Marsaxlokk" => Ok(Self::Marsaxlokk), "Mdina" => Ok(Self::Mdina), "Mellieħa" => Ok(Self::Mellieħa), "Mosta" => Ok(Self::Mosta), "Mqabba" => Ok(Self::Mqabba), "Msida" => Ok(Self::Msida), "Mtarfa" => Ok(Self::Mtarfa), "Munxar" => Ok(Self::Munxar), "Mġarr" => Ok(Self::Mġarr), "Nadur" => Ok(Self::Nadur), "Naxxar" => Ok(Self::Naxxar), "Paola" => Ok(Self::Paola), "Pembroke" => Ok(Self::Pembroke), "Pietà" => Ok(Self::Pietà), "Qala" => Ok(Self::Qala), "Qormi" => Ok(Self::Qormi), "Qrendi" => Ok(Self::Qrendi), "Rabat" => Ok(Self::Rabat), "Saint Lawrence" => Ok(Self::SaintLawrence), "San Ġwann" => Ok(Self::SanĠwann), "Sannat" => Ok(Self::Sannat), "Santa Luċija" => Ok(Self::SantaLuċija), "Santa Venera" => Ok(Self::SantaVenera), "Siġġiewi" => Ok(Self::Siġġiewi), "Sliema" => Ok(Self::Sliema), "St. Julian's" => Ok(Self::StJulians), "St. Paul's Bay" => Ok(Self::StPaulsBay), "Swieqi" => Ok(Self::Swieqi), "Ta' Xbiex" => Ok(Self::TaXbiex), "Tarxien" => Ok(Self::Tarxien), "Valletta" => Ok(Self::Valletta), "Victoria" => Ok(Self::Victoria), "Xagħra" => Ok(Self::Xagħra), "Xewkija" => Ok(Self::Xewkija), "Xgħajra" => Ok(Self::Xgħajra), "Żabbar" => Ok(Self::Żabbar), "Żebbuġ Gozo" => Ok(Self::ŻebbuġGozo), "Żebbuġ Malta" => Ok(Self::ŻebbuġMalta), "Żejtun" => Ok(Self::Żejtun), "Żurrieq" => Ok(Self::Żurrieq), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for BelarusStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "BelarusStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Brest Region" => Ok(Self::BrestRegion), "Gomel Region" => Ok(Self::GomelRegion), "Grodno Region" => Ok(Self::GrodnoRegion), "Minsk" => Ok(Self::Minsk), "Minsk Region" => Ok(Self::MinskRegion), "Mogilev Region" => Ok(Self::MogilevRegion), "Vitebsk Region" => Ok(Self::VitebskRegion), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for IrelandStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "IrelandStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Connacht" => Ok(Self::Connacht), "County Carlow" => Ok(Self::CountyCarlow), "County Cavan" => Ok(Self::CountyCavan), "County Clare" => Ok(Self::CountyClare), "County Cork" => Ok(Self::CountyCork), "County Donegal" => Ok(Self::CountyDonegal), "County Dublin" => Ok(Self::CountyDublin), "County Galway" => Ok(Self::CountyGalway), "County Kerry" => Ok(Self::CountyKerry), "County Kildare" => Ok(Self::CountyKildare), "County Kilkenny" => Ok(Self::CountyKilkenny), "County Laois" => Ok(Self::CountyLaois), "County Limerick" => Ok(Self::CountyLimerick), "County Longford" => Ok(Self::CountyLongford), "County Louth" => Ok(Self::CountyLouth), "County Mayo" => Ok(Self::CountyMayo), "County Meath" => Ok(Self::CountyMeath), "County Monaghan" => Ok(Self::CountyMonaghan), "County Offaly" => Ok(Self::CountyOffaly), "County Roscommon" => Ok(Self::CountyRoscommon), "County Sligo" => Ok(Self::CountySligo), "County Tipperary" => Ok(Self::CountyTipperary), "County Waterford" => Ok(Self::CountyWaterford), "County Westmeath" => Ok(Self::CountyWestmeath), "County Wexford" => Ok(Self::CountyWexford), "County Wicklow" => Ok(Self::CountyWicklow), "Leinster" => Ok(Self::Leinster), "Munster" => Ok(Self::Munster), "Ulster" => Ok(Self::Ulster), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for IcelandStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "IcelandStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Capital Region" => Ok(Self::CapitalRegion), "Eastern Region" => Ok(Self::EasternRegion), "Northeastern Region" => Ok(Self::NortheasternRegion), "Northwestern Region" => Ok(Self::NorthwesternRegion), "Southern Peninsula Region" => Ok(Self::SouthernPeninsulaRegion), "Southern Region" => Ok(Self::SouthernRegion), "Western Region" => Ok(Self::WesternRegion), "Westfjords" => Ok(Self::Westfjords), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for HungaryStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "HungaryStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Baranya County" => Ok(Self::BaranyaCounty), "Borsod-Abaúj-Zemplén County" => Ok(Self::BorsodAbaujZemplenCounty), "Budapest" => Ok(Self::Budapest), "Bács-Kiskun County" => Ok(Self::BacsKiskunCounty), "Békés County" => Ok(Self::BekesCounty), "Békéscsaba" => Ok(Self::Bekescsaba), "Csongrád County" => Ok(Self::CsongradCounty), "Debrecen" => Ok(Self::Debrecen), "Dunaújváros" => Ok(Self::Dunaujvaros), "Eger" => Ok(Self::Eger), "Fejér County" => Ok(Self::FejerCounty), "Győr" => Ok(Self::Gyor), "Győr-Moson-Sopron County" => Ok(Self::GyorMosonSopronCounty), "Hajdú-Bihar County" => Ok(Self::HajduBiharCounty), "Heves County" => Ok(Self::HevesCounty), "Hódmezővásárhely" => Ok(Self::Hodmezovasarhely), "Jász-Nagykun-Szolnok County" => Ok(Self::JaszNagykunSzolnokCounty), "Kaposvár" => Ok(Self::Kaposvar), "Kecskemét" => Ok(Self::Kecskemet), "Miskolc" => Ok(Self::Miskolc), "Nagykanizsa" => Ok(Self::Nagykanizsa), "Nyíregyháza" => Ok(Self::Nyiregyhaza), "Nógrád County" => Ok(Self::NogradCounty), "Pest County" => Ok(Self::PestCounty), "Pécs" => Ok(Self::Pecs), "Salgótarján" => Ok(Self::Salgotarjan), "Somogy County" => Ok(Self::SomogyCounty), "Sopron" => Ok(Self::Sopron), "Szabolcs-Szatmár-Bereg County" => Ok(Self::SzabolcsSzatmarBeregCounty), "Szeged" => Ok(Self::Szeged), "Szekszárd" => Ok(Self::Szekszard), "Szolnok" => Ok(Self::Szolnok), "Szombathely" => Ok(Self::Szombathely), "Székesfehérvár" => Ok(Self::Szekesfehervar), "Tatabánya" => Ok(Self::Tatabanya), "Tolna County" => Ok(Self::TolnaCounty), "Vas County" => Ok(Self::VasCounty), "Veszprém" => Ok(Self::Veszprem), "Veszprém County" => Ok(Self::VeszpremCounty), "Zala County" => Ok(Self::ZalaCounty), "Zalaegerszeg" => Ok(Self::Zalaegerszeg), "Érd" => Ok(Self::Erd), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for GreeceStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "GreeceStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Achaea Regional Unit" => Ok(Self::AchaeaRegionalUnit), "Aetolia-Acarnania Regional Unit" => Ok(Self::AetoliaAcarnaniaRegionalUnit), "Arcadia Prefecture" => Ok(Self::ArcadiaPrefecture), "Argolis Regional Unit" => Ok(Self::ArgolisRegionalUnit), "Attica Region" => Ok(Self::AtticaRegion), "Boeotia Regional Unit" => Ok(Self::BoeotiaRegionalUnit), "Central Greece Region" => Ok(Self::CentralGreeceRegion), "Central Macedonia" => Ok(Self::CentralMacedonia), "Chania Regional Unit" => Ok(Self::ChaniaRegionalUnit), "Corfu Prefecture" => Ok(Self::CorfuPrefecture), "Corinthia Regional Unit" => Ok(Self::CorinthiaRegionalUnit), "Crete Region" => Ok(Self::CreteRegion), "Drama Regional Unit" => Ok(Self::DramaRegionalUnit), "East Attica Regional Unit" => Ok(Self::EastAtticaRegionalUnit), "East Macedonia and Thrace" => Ok(Self::EastMacedoniaAndThrace), "Epirus Region" => Ok(Self::EpirusRegion), "Euboea" => Ok(Self::Euboea), "Grevena Prefecture" => Ok(Self::GrevenaPrefecture), "Imathia Regional Unit" => Ok(Self::ImathiaRegionalUnit), "Ioannina Regional Unit" => Ok(Self::IoanninaRegionalUnit), "Ionian Islands Region" => Ok(Self::IonianIslandsRegion), "Karditsa Regional Unit" => Ok(Self::KarditsaRegionalUnit), "Kastoria Regional Unit" => Ok(Self::KastoriaRegionalUnit), "Kefalonia Prefecture" => Ok(Self::KefaloniaPrefecture), "Kilkis Regional Unit" => Ok(Self::KilkisRegionalUnit), "Kozani Prefecture" => Ok(Self::KozaniPrefecture), "Laconia" => Ok(Self::Laconia), "Larissa Prefecture" => Ok(Self::LarissaPrefecture), "Lefkada Regional Unit" => Ok(Self::LefkadaRegionalUnit), "Pella Regional Unit" => Ok(Self::PellaRegionalUnit), "Peloponnese Region" => Ok(Self::PeloponneseRegion), "Phthiotis Prefecture" => Ok(Self::PhthiotisPrefecture), "Preveza Prefecture" => Ok(Self::PrevezaPrefecture), "Serres Prefecture" => Ok(Self::SerresPrefecture), "South Aegean" => Ok(Self::SouthAegean), "Thessaloniki Regional Unit" => Ok(Self::ThessalonikiRegionalUnit), "West Greece Region" => Ok(Self::WestGreeceRegion), "West Macedonia Region" => Ok(Self::WestMacedoniaRegion), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for FinlandStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "FinlandStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Central Finland" => Ok(Self::CentralFinland), "Central Ostrobothnia" => Ok(Self::CentralOstrobothnia), "Eastern Finland Province" => Ok(Self::EasternFinlandProvince), "Finland Proper" => Ok(Self::FinlandProper), "Kainuu" => Ok(Self::Kainuu), "Kymenlaakso" => Ok(Self::Kymenlaakso), "Lapland" => Ok(Self::Lapland), "North Karelia" => Ok(Self::NorthKarelia), "Northern Ostrobothnia" => Ok(Self::NorthernOstrobothnia), "Northern Savonia" => Ok(Self::NorthernSavonia), "Ostrobothnia" => Ok(Self::Ostrobothnia), "Oulu Province" => Ok(Self::OuluProvince), "Pirkanmaa" => Ok(Self::Pirkanmaa), "Päijänne Tavastia" => Ok(Self::PaijanneTavastia), "Satakunta" => Ok(Self::Satakunta), "South Karelia" => Ok(Self::SouthKarelia), "Southern Ostrobothnia" => Ok(Self::SouthernOstrobothnia), "Southern Savonia" => Ok(Self::SouthernSavonia), "Tavastia Proper" => Ok(Self::TavastiaProper), "Uusimaa" => Ok(Self::Uusimaa), "Åland Islands" => Ok(Self::AlandIslands), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for DenmarkStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "DenmarkStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Capital Region of Denmark" => Ok(Self::CapitalRegionOfDenmark), "Central Denmark Region" => Ok(Self::CentralDenmarkRegion), "North Denmark Region" => Ok(Self::NorthDenmarkRegion), "Region Zealand" => Ok(Self::RegionZealand), "Region of Southern Denmark" => Ok(Self::RegionOfSouthernDenmark), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for CzechRepublicStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "CzechRepublicStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Benešov District" => Ok(Self::BenesovDistrict), "Beroun District" => Ok(Self::BerounDistrict), "Blansko District" => Ok(Self::BlanskoDistrict), "Brno-City District" => Ok(Self::BrnoCityDistrict), "Brno-Country District" => Ok(Self::BrnoCountryDistrict), "Bruntál District" => Ok(Self::BruntalDistrict), "Břeclav District" => Ok(Self::BreclavDistrict), "Central Bohemian Region" => Ok(Self::CentralBohemianRegion), "Cheb District" => Ok(Self::ChebDistrict), "Chomutov District" => Ok(Self::ChomutovDistrict), "Chrudim District" => Ok(Self::ChrudimDistrict), "Domažlice Distric" => Ok(Self::DomazliceDistrict), "Děčín District" => Ok(Self::DecinDistrict), "Frýdek-Místek District" => Ok(Self::FrydekMistekDistrict), "Havlíčkův Brod District" => Ok(Self::HavlickuvBrodDistrict), "Hodonín District" => Ok(Self::HodoninDistrict), "Horní Počernice" => Ok(Self::HorniPocernice), "Hradec Králové District" => Ok(Self::HradecKraloveDistrict), "Hradec Králové Region" => Ok(Self::HradecKraloveRegion), "Jablonec nad Nisou District" => Ok(Self::JablonecNadNisouDistrict), "Jeseník District" => Ok(Self::JesenikDistrict), "Jihlava District" => Ok(Self::JihlavaDistrict), "Jindřichův Hradec District" => Ok(Self::JindrichuvHradecDistrict), "Jičín District" => Ok(Self::JicinDistrict), "Karlovy Vary District" => Ok(Self::KarlovyVaryDistrict), "Karlovy Vary Region" => Ok(Self::KarlovyVaryRegion), "Karviná District" => Ok(Self::KarvinaDistrict), "Kladno District" => Ok(Self::KladnoDistrict), "Klatovy District" => Ok(Self::KlatovyDistrict), "Kolín District" => Ok(Self::KolinDistrict), "Kroměříž District" => Ok(Self::KromerizDistrict), "Liberec District" => Ok(Self::LiberecDistrict), "Liberec Region" => Ok(Self::LiberecRegion), "Litoměřice District" => Ok(Self::LitomericeDistrict), "Louny District" => Ok(Self::LounyDistrict), "Mladá Boleslav District" => Ok(Self::MladaBoleslavDistrict), "Moravian-Silesian Region" => Ok(Self::MoravianSilesianRegion), "Most District" => Ok(Self::MostDistrict), "Mělník District" => Ok(Self::MelnikDistrict), "Nový Jičín District" => Ok(Self::NovyJicinDistrict), "Nymburk District" => Ok(Self::NymburkDistrict), "Náchod District" => Ok(Self::NachodDistrict), "Olomouc District" => Ok(Self::OlomoucDistrict), "Olomouc Region" => Ok(Self::OlomoucRegion), "Opava District" => Ok(Self::OpavaDistrict), "Ostrava-City District" => Ok(Self::OstravaCityDistrict), "Pardubice District" => Ok(Self::PardubiceDistrict), "Pardubice Region" => Ok(Self::PardubiceRegion), "Pelhřimov District" => Ok(Self::PelhrimovDistrict), "Plzeň Region" => Ok(Self::PlzenRegion), "Plzeň-City District" => Ok(Self::PlzenCityDistrict), "Plzeň-North District" => Ok(Self::PlzenNorthDistrict), "Plzeň-South District" => Ok(Self::PlzenSouthDistrict), "Prachatice District" => Ok(Self::PrachaticeDistrict), "Prague" => Ok(Self::Prague), "Prague 1" => Ok(Self::Prague1), "Prague 10" => Ok(Self::Prague10), "Prague 11" => Ok(Self::Prague11), "Prague 12" => Ok(Self::Prague12), "Prague 13" => Ok(Self::Prague13), "Prague 14" => Ok(Self::Prague14), "Prague 15" => Ok(Self::Prague15), "Prague 16" => Ok(Self::Prague16), "Prague 2" => Ok(Self::Prague2), "Prague 21" => Ok(Self::Prague21), "Prague 3" => Ok(Self::Prague3), "Prague 4" => Ok(Self::Prague4), "Prague 5" => Ok(Self::Prague5), "Prague 6" => Ok(Self::Prague6), "Prague 7" => Ok(Self::Prague7), "Prague 8" => Ok(Self::Prague8), "Prague 9" => Ok(Self::Prague9), "Prague-East District" => Ok(Self::PragueEastDistrict), "Prague-West District" => Ok(Self::PragueWestDistrict), "Prostějov District" => Ok(Self::ProstejovDistrict), "Písek District" => Ok(Self::PisekDistrict), "Přerov District" => Ok(Self::PrerovDistrict), "Příbram District" => Ok(Self::PribramDistrict), "Rakovník District" => Ok(Self::RakovnikDistrict), "Rokycany District" => Ok(Self::RokycanyDistrict), "Rychnov nad Kněžnou District" => Ok(Self::RychnovNadKneznouDistrict), "Semily District" => Ok(Self::SemilyDistrict), "Sokolov District" => Ok(Self::SokolovDistrict), "South Bohemian Region" => Ok(Self::SouthBohemianRegion), "South Moravian Region" => Ok(Self::SouthMoravianRegion), "Strakonice District" => Ok(Self::StrakoniceDistrict), "Svitavy District" => Ok(Self::SvitavyDistrict), "Tachov District" => Ok(Self::TachovDistrict), "Teplice District" => Ok(Self::TepliceDistrict), "Trutnov District" => Ok(Self::TrutnovDistrict), "Tábor District" => Ok(Self::TaborDistrict), "Třebíč District" => Ok(Self::TrebicDistrict), "Uherské Hradiště District" => Ok(Self::UherskeHradisteDistrict), "Vsetín District" => Ok(Self::VsetinDistrict), "Vysočina Region" => Ok(Self::VysocinaRegion), "Vyškov District" => Ok(Self::VyskovDistrict), "Zlín District" => Ok(Self::ZlinDistrict), "Zlín Region" => Ok(Self::ZlinRegion), "Znojmo District" => Ok(Self::ZnojmoDistrict), "Ústí nad Labem District" => Ok(Self::UstiNadLabemDistrict), "Ústí nad Labem Region" => Ok(Self::UstiNadLabemRegion), "Ústí nad Orlicí District" => Ok(Self::UstiNadOrliciDistrict), "Česká Lípa District" => Ok(Self::CeskaLipaDistrict), "České Budějovice District" => Ok(Self::CeskeBudejoviceDistrict), "Český Krumlov District" => Ok(Self::CeskyKrumlovDistrict), "Šumperk District" => Ok(Self::SumperkDistrict), "Žďár nad Sázavou District" => Ok(Self::ZdarNadSazavouDistrict), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for CroatiaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "CroatiaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Bjelovar-Bilogora County" => Ok(Self::BjelovarBilogoraCounty), "Brod-Posavina County" => Ok(Self::BrodPosavinaCounty), "Dubrovnik-Neretva County" => Ok(Self::DubrovnikNeretvaCounty), "Istria County" => Ok(Self::IstriaCounty), "Koprivnica-Križevci County" => Ok(Self::KoprivnicaKrizevciCounty), "Krapina-Zagorje County" => Ok(Self::KrapinaZagorjeCounty), "Lika-Senj County" => Ok(Self::LikaSenjCounty), "Međimurje County" => Ok(Self::MedimurjeCounty), "Osijek-Baranja County" => Ok(Self::OsijekBaranjaCounty), "Požega-Slavonia County" => Ok(Self::PozegaSlavoniaCounty), "Primorje-Gorski Kotar County" => Ok(Self::PrimorjeGorskiKotarCounty), "Sisak-Moslavina County" => Ok(Self::SisakMoslavinaCounty), "Split-Dalmatia County" => Ok(Self::SplitDalmatiaCounty), "Varaždin County" => Ok(Self::VarazdinCounty), "Virovitica-Podravina County" => Ok(Self::ViroviticaPodravinaCounty), "Vukovar-Syrmia County" => Ok(Self::VukovarSyrmiaCounty), "Zadar County" => Ok(Self::ZadarCounty), "Zagreb" => Ok(Self::Zagreb), "Zagreb County" => Ok(Self::ZagrebCounty), "Šibenik-Knin County" => Ok(Self::SibenikKninCounty), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for BulgariaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "BulgariaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Blagoevgrad Province" => Ok(Self::BlagoevgradProvince), "Burgas Province" => Ok(Self::BurgasProvince), "Dobrich Province" => Ok(Self::DobrichProvince), "Gabrovo Province" => Ok(Self::GabrovoProvince), "Haskovo Province" => Ok(Self::HaskovoProvince), "Kardzhali Province" => Ok(Self::KardzhaliProvince), "Kyustendil Province" => Ok(Self::KyustendilProvince), "Lovech Province" => Ok(Self::LovechProvince), "Montana Province" => Ok(Self::MontanaProvince), "Pazardzhik Province" => Ok(Self::PazardzhikProvince), "Pernik Province" => Ok(Self::PernikProvince), "Pleven Province" => Ok(Self::PlevenProvince), "Plovdiv Province" => Ok(Self::PlovdivProvince), "Razgrad Province" => Ok(Self::RazgradProvince), "Ruse Province" => Ok(Self::RuseProvince), "Shumen" => Ok(Self::Shumen), "Silistra Province" => Ok(Self::SilistraProvince), "Sliven Province" => Ok(Self::SlivenProvince), "Smolyan Province" => Ok(Self::SmolyanProvince), "Sofia City Province" => Ok(Self::SofiaCityProvince), "Sofia Province" => Ok(Self::SofiaProvince), "Stara Zagora Province" => Ok(Self::StaraZagoraProvince), "Targovishte Provinc" => Ok(Self::TargovishteProvince), "Varna Province" => Ok(Self::VarnaProvince), "Veliko Tarnovo Province" => Ok(Self::VelikoTarnovoProvince), "Vidin Province" => Ok(Self::VidinProvince), "Vratsa Province" => Ok(Self::VratsaProvince), "Yambol Province" => Ok(Self::YambolProvince), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for BosniaAndHerzegovinaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "BosniaAndHerzegovinaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Bosnian Podrinje Canton" => Ok(Self::BosnianPodrinjeCanton), "Brčko District" => Ok(Self::BrckoDistrict), "Canton 10" => Ok(Self::Canton10), "Central Bosnia Canton" => Ok(Self::CentralBosniaCanton), "Federation of Bosnia and Herzegovina" => { Ok(Self::FederationOfBosniaAndHerzegovina) } "Herzegovina-Neretva Canton" => Ok(Self::HerzegovinaNeretvaCanton), "Posavina Canton" => Ok(Self::PosavinaCanton), "Republika Srpska" => Ok(Self::RepublikaSrpska), "Sarajevo Canton" => Ok(Self::SarajevoCanton), "Tuzla Canton" => Ok(Self::TuzlaCanton), "Una-Sana Canton" => Ok(Self::UnaSanaCanton), "West Herzegovina Canton" => Ok(Self::WestHerzegovinaCanton), "Zenica-Doboj Canton" => Ok(Self::ZenicaDobojCanton), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for UnitedKingdomStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "UnitedKingdomStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Aberdeen" => Ok(Self::Aberdeen), "Aberdeenshire" => Ok(Self::Aberdeenshire), "Angus" => Ok(Self::Angus), "Antrim" => Ok(Self::Antrim), "Antrim and Newtownabbey" => Ok(Self::AntrimAndNewtownabbey), "Ards" => Ok(Self::Ards), "Ards and North Down" => Ok(Self::ArdsAndNorthDown), "Argyll and Bute" => Ok(Self::ArgyllAndBute), "Armagh City and District Council" => Ok(Self::ArmaghCityAndDistrictCouncil), "Armagh, Banbridge and Craigavon" => Ok(Self::ArmaghBanbridgeAndCraigavon), "Ascension Island" => Ok(Self::AscensionIsland), "Ballymena Borough" => Ok(Self::BallymenaBorough), "Ballymoney" => Ok(Self::Ballymoney), "Banbridge" => Ok(Self::Banbridge), "Barnsley" => Ok(Self::Barnsley), "Bath and North East Somerset" => Ok(Self::BathAndNorthEastSomerset), "Bedford" => Ok(Self::Bedford), "Belfast district" => Ok(Self::BelfastDistrict), "Birmingham" => Ok(Self::Birmingham), "Blackburn with Darwen" => Ok(Self::BlackburnWithDarwen), "Blackpool" => Ok(Self::Blackpool), "Blaenau Gwent County Borough" => Ok(Self::BlaenauGwentCountyBorough), "Bolton" => Ok(Self::Bolton), "Bournemouth" => Ok(Self::Bournemouth), "Bracknell Forest" => Ok(Self::BracknellForest), "Bradford" => Ok(Self::Bradford), "Bridgend County Borough" => Ok(Self::BridgendCountyBorough), "Brighton and Hove" => Ok(Self::BrightonAndHove), "Buckinghamshire" => Ok(Self::Buckinghamshire), "Bury" => Ok(Self::Bury), "Caerphilly County Borough" => Ok(Self::CaerphillyCountyBorough), "Calderdale" => Ok(Self::Calderdale), "Cambridgeshire" => Ok(Self::Cambridgeshire), "Carmarthenshire" => Ok(Self::Carmarthenshire), "Carrickfergus Borough Council" => Ok(Self::CarrickfergusBoroughCouncil), "Castlereagh" => Ok(Self::Castlereagh), "Causeway Coast and Glens" => Ok(Self::CausewayCoastAndGlens), "Central Bedfordshire" => Ok(Self::CentralBedfordshire), "Ceredigion" => Ok(Self::Ceredigion), "Cheshire East" => Ok(Self::CheshireEast), "Cheshire West and Chester" => Ok(Self::CheshireWestAndChester), "City and County of Cardiff" => Ok(Self::CityAndCountyOfCardiff), "City and County of Swansea" => Ok(Self::CityAndCountyOfSwansea), "City of Bristol" => Ok(Self::CityOfBristol), "City of Derby" => Ok(Self::CityOfDerby), "City of Kingston upon Hull" => Ok(Self::CityOfKingstonUponHull), "City of Leicester" => Ok(Self::CityOfLeicester), "City of London" => Ok(Self::CityOfLondon), "City of Nottingham" => Ok(Self::CityOfNottingham), "City of Peterborough" => Ok(Self::CityOfPeterborough), "City of Plymouth" => Ok(Self::CityOfPlymouth), "City of Portsmouth" => Ok(Self::CityOfPortsmouth), "City of Southampton" => Ok(Self::CityOfSouthampton), "City of Stoke-on-Trent" => Ok(Self::CityOfStokeOnTrent), "City of Sunderland" => Ok(Self::CityOfSunderland), "City of Westminster" => Ok(Self::CityOfWestminster), "City of Wolverhampton" => Ok(Self::CityOfWolverhampton), "City of York" => Ok(Self::CityOfYork), "Clackmannanshire" => Ok(Self::Clackmannanshire), "Coleraine Borough Council" => Ok(Self::ColeraineBoroughCouncil), "Conwy County Borough" => Ok(Self::ConwyCountyBorough), "Cookstown District Council" => Ok(Self::CookstownDistrictCouncil), "Cornwall" => Ok(Self::Cornwall), "County Durham" => Ok(Self::CountyDurham), "Coventry" => Ok(Self::Coventry), "Craigavon Borough Council" => Ok(Self::CraigavonBoroughCouncil), "Cumbria" => Ok(Self::Cumbria), "Darlington" => Ok(Self::Darlington), "Denbighshire" => Ok(Self::Denbighshire), "Derbyshire" => Ok(Self::Derbyshire), "Derry City and Strabane" => Ok(Self::DerryCityAndStrabane), "Derry City Council" => Ok(Self::DerryCityCouncil), "Devon" => Ok(Self::Devon), "Doncaster" => Ok(Self::Doncaster), "Dorset" => Ok(Self::Dorset), "Down District Council" => Ok(Self::DownDistrictCouncil), "Dudley" => Ok(Self::Dudley), "Dumfries and Galloway" => Ok(Self::DumfriesAndGalloway), "Dundee" => Ok(Self::Dundee), "Dungannon and South Tyrone Borough Council" => { Ok(Self::DungannonAndSouthTyroneBoroughCouncil) } "East Ayrshire" => Ok(Self::EastAyrshire), "East Dunbartonshire" => Ok(Self::EastDunbartonshire), "East Lothian" => Ok(Self::EastLothian), "East Renfrewshire" => Ok(Self::EastRenfrewshire), "East Riding of Yorkshire" => Ok(Self::EastRidingOfYorkshire), "East Sussex" => Ok(Self::EastSussex), "Edinburgh" => Ok(Self::Edinburgh), "England" => Ok(Self::England), "Essex" => Ok(Self::Essex), "Falkirk" => Ok(Self::Falkirk), "Fermanagh and Omagh" => Ok(Self::FermanaghAndOmagh), "Fermanagh District Council" => Ok(Self::FermanaghDistrictCouncil), "Fife" => Ok(Self::Fife), "Flintshire" => Ok(Self::Flintshire), "Gateshead" => Ok(Self::Gateshead), "Glasgow" => Ok(Self::Glasgow), "Gloucestershire" => Ok(Self::Gloucestershire), "Gwynedd" => Ok(Self::Gwynedd), "Halton" => Ok(Self::Halton), "Hampshire" => Ok(Self::Hampshire), "Hartlepool" => Ok(Self::Hartlepool), "Herefordshire" => Ok(Self::Herefordshire), "Hertfordshire" => Ok(Self::Hertfordshire), "Highland" => Ok(Self::Highland), "Inverclyde" => Ok(Self::Inverclyde), "Isle of Wight" => Ok(Self::IsleOfWight), "Isles of Scilly" => Ok(Self::IslesOfScilly), "Kent" => Ok(Self::Kent), "Kirklees" => Ok(Self::Kirklees), "Knowsley" => Ok(Self::Knowsley), "Lancashire" => Ok(Self::Lancashire), "Larne Borough Council" => Ok(Self::LarneBoroughCouncil), "Leeds" => Ok(Self::Leeds), "Leicestershire" => Ok(Self::Leicestershire), "Limavady Borough Council" => Ok(Self::LimavadyBoroughCouncil), "Lincolnshire" => Ok(Self::Lincolnshire), "Lisburn and Castlereagh" => Ok(Self::LisburnAndCastlereagh), "Lisburn City Council" => Ok(Self::LisburnCityCouncil), "Liverpool" => Ok(Self::Liverpool), "London Borough of Barking and Dagenham" => { Ok(Self::LondonBoroughOfBarkingAndDagenham) } "London Borough of Barnet" => Ok(Self::LondonBoroughOfBarnet), "London Borough of Bexley" => Ok(Self::LondonBoroughOfBexley), "London Borough of Brent" => Ok(Self::LondonBoroughOfBrent), "London Borough of Bromley" => Ok(Self::LondonBoroughOfBromley), "London Borough of Camden" => Ok(Self::LondonBoroughOfCamden), "London Borough of Croydon" => Ok(Self::LondonBoroughOfCroydon), "London Borough of Ealing" => Ok(Self::LondonBoroughOfEaling), "London Borough of Enfield" => Ok(Self::LondonBoroughOfEnfield), "London Borough of Hackney" => Ok(Self::LondonBoroughOfHackney), "London Borough of Hammersmith and Fulham" => { Ok(Self::LondonBoroughOfHammersmithAndFulham) } "London Borough of Haringey" => Ok(Self::LondonBoroughOfHaringey), "London Borough of Harrow" => Ok(Self::LondonBoroughOfHarrow), "London Borough of Havering" => Ok(Self::LondonBoroughOfHavering), "London Borough of Hillingdon" => Ok(Self::LondonBoroughOfHillingdon), "London Borough of Hounslow" => Ok(Self::LondonBoroughOfHounslow), "London Borough of Islington" => Ok(Self::LondonBoroughOfIslington), "London Borough of Lambeth" => Ok(Self::LondonBoroughOfLambeth), "London Borough of Lewisham" => Ok(Self::LondonBoroughOfLewisham), "London Borough of Merton" => Ok(Self::LondonBoroughOfMerton), "London Borough of Newham" => Ok(Self::LondonBoroughOfNewham), "London Borough of Redbridge" => Ok(Self::LondonBoroughOfRedbridge), "London Borough of Richmond upon Thames" => { Ok(Self::LondonBoroughOfRichmondUponThames) } "London Borough of Southwark" => Ok(Self::LondonBoroughOfSouthwark), "London Borough of Sutton" => Ok(Self::LondonBoroughOfSutton), "London Borough of Tower Hamlets" => Ok(Self::LondonBoroughOfTowerHamlets), "London Borough of Waltham Forest" => Ok(Self::LondonBoroughOfWalthamForest), "London Borough of Wandsworth" => Ok(Self::LondonBoroughOfWandsworth), "Magherafelt District Council" => Ok(Self::MagherafeltDistrictCouncil), "Manchester" => Ok(Self::Manchester), "Medway" => Ok(Self::Medway), "Merthyr Tydfil County Borough" => Ok(Self::MerthyrTydfilCountyBorough), "Metropolitan Borough of Wigan" => Ok(Self::MetropolitanBoroughOfWigan), "Mid and East Antrim" => Ok(Self::MidAndEastAntrim), "Mid Ulster" => Ok(Self::MidUlster), "Middlesbrough" => Ok(Self::Middlesbrough), "Midlothian" => Ok(Self::Midlothian), "Milton Keynes" => Ok(Self::MiltonKeynes), "Monmouthshire" => Ok(Self::Monmouthshire), "Moray" => Ok(Self::Moray), "Moyle District Council" => Ok(Self::MoyleDistrictCouncil), "Neath Port Talbot County Borough" => Ok(Self::NeathPortTalbotCountyBorough), "Newcastle upon Tyne" => Ok(Self::NewcastleUponTyne), "Newport" => Ok(Self::Newport), "Newry and Mourne District Council" => Ok(Self::NewryAndMourneDistrictCouncil), "Newry, Mourne and Down" => Ok(Self::NewryMourneAndDown), "Newtownabbey Borough Council" => Ok(Self::NewtownabbeyBoroughCouncil), "Norfolk" => Ok(Self::Norfolk), "North Ayrshire" => Ok(Self::NorthAyrshire), "North Down Borough Council" => Ok(Self::NorthDownBoroughCouncil), "North East Lincolnshire" => Ok(Self::NorthEastLincolnshire), "North Lanarkshire" => Ok(Self::NorthLanarkshire), "North Lincolnshire" => Ok(Self::NorthLincolnshire), "North Somerset" => Ok(Self::NorthSomerset), "North Tyneside" => Ok(Self::NorthTyneside), "North Yorkshire" => Ok(Self::NorthYorkshire), "Northamptonshire" => Ok(Self::Northamptonshire), "Northern Ireland" => Ok(Self::NorthernIreland), "Northumberland" => Ok(Self::Northumberland), "Nottinghamshire" => Ok(Self::Nottinghamshire), "Oldham" => Ok(Self::Oldham), "Omagh District Council" => Ok(Self::OmaghDistrictCouncil), "Orkney Islands" => Ok(Self::OrkneyIslands), "Outer Hebrides" => Ok(Self::OuterHebrides), "Oxfordshire" => Ok(Self::Oxfordshire), "Pembrokeshire" => Ok(Self::Pembrokeshire), "Perth and Kinross" => Ok(Self::PerthAndKinross), "Poole" => Ok(Self::Poole), "Powys" => Ok(Self::Powys), "Reading" => Ok(Self::Reading), "Redcar and Cleveland" => Ok(Self::RedcarAndCleveland), "Renfrewshire" => Ok(Self::Renfrewshire), "Rhondda Cynon Taf" => Ok(Self::RhonddaCynonTaf), "Rochdale" => Ok(Self::Rochdale), "Rotherham" => Ok(Self::Rotherham), "Royal Borough of Greenwich" => Ok(Self::RoyalBoroughOfGreenwich), "Royal Borough of Kensington and Chelsea" => { Ok(Self::RoyalBoroughOfKensingtonAndChelsea) } "Royal Borough of Kingston upon Thames" => { Ok(Self::RoyalBoroughOfKingstonUponThames) } "Rutland" => Ok(Self::Rutland), "Saint Helena" => Ok(Self::SaintHelena), "Salford" => Ok(Self::Salford), "Sandwell" => Ok(Self::Sandwell), "Scotland" => Ok(Self::Scotland), "Scottish Borders" => Ok(Self::ScottishBorders), "Sefton" => Ok(Self::Sefton), "Sheffield" => Ok(Self::Sheffield), "Shetland Islands" => Ok(Self::ShetlandIslands), "Shropshire" => Ok(Self::Shropshire), "Slough" => Ok(Self::Slough), "Solihull" => Ok(Self::Solihull), "Somerset" => Ok(Self::Somerset), "South Ayrshire" => Ok(Self::SouthAyrshire), "South Gloucestershire" => Ok(Self::SouthGloucestershire), "South Lanarkshire" => Ok(Self::SouthLanarkshire), "South Tyneside" => Ok(Self::SouthTyneside), "Southend-on-Sea" => Ok(Self::SouthendOnSea), "St Helens" => Ok(Self::StHelens), "Staffordshire" => Ok(Self::Staffordshire), "Stirling" => Ok(Self::Stirling), "Stockport" => Ok(Self::Stockport), "Stockton-on-Tees" => Ok(Self::StocktonOnTees), "Strabane District Council" => Ok(Self::StrabaneDistrictCouncil), "Suffolk" => Ok(Self::Suffolk), "Surrey" => Ok(Self::Surrey), "Swindon" => Ok(Self::Swindon), "Tameside" => Ok(Self::Tameside), "Telford and Wrekin" => Ok(Self::TelfordAndWrekin), "Thurrock" => Ok(Self::Thurrock), "Torbay" => Ok(Self::Torbay), "Torfaen" => Ok(Self::Torfaen), "Trafford" => Ok(Self::Trafford), "United Kingdom" => Ok(Self::UnitedKingdom), "Vale of Glamorgan" => Ok(Self::ValeOfGlamorgan), "Wakefield" => Ok(Self::Wakefield), "Wales" => Ok(Self::Wales), "Walsall" => Ok(Self::Walsall), "Warrington" => Ok(Self::Warrington), "Warwickshire" => Ok(Self::Warwickshire), "West Berkshire" => Ok(Self::WestBerkshire), "West Dunbartonshire" => Ok(Self::WestDunbartonshire), "West Lothian" => Ok(Self::WestLothian), "West Sussex" => Ok(Self::WestSussex), "Wiltshire" => Ok(Self::Wiltshire), "Windsor and Maidenhead" => Ok(Self::WindsorAndMaidenhead), "Wirral" => Ok(Self::Wirral), "Wokingham" => Ok(Self::Wokingham), "Worcestershire" => Ok(Self::Worcestershire), "Wrexham County Borough" => Ok(Self::WrexhamCountyBorough), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for BelgiumStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "BelgiumStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Antwerp" => Ok(Self::Antwerp), "Brussels-Capital Region" => Ok(Self::BrusselsCapitalRegion), "East Flanders" => Ok(Self::EastFlanders), "Flanders" => Ok(Self::Flanders), "Flemish Brabant" => Ok(Self::FlemishBrabant), "Hainaut" => Ok(Self::Hainaut), "Limburg" => Ok(Self::Limburg), "Liège" => Ok(Self::Liege), "Luxembourg" => Ok(Self::Luxembourg), "Namur" => Ok(Self::Namur), "Wallonia" => Ok(Self::Wallonia), "Walloon Brabant" => Ok(Self::WalloonBrabant), "West Flanders" => Ok(Self::WestFlanders), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for LuxembourgStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "LuxembourgStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Canton of Capellen" => Ok(Self::CantonOfCapellen), "Canton of Clervaux" => Ok(Self::CantonOfClervaux), "Canton of Diekirch" => Ok(Self::CantonOfDiekirch), "Canton of Echternach" => Ok(Self::CantonOfEchternach), "Canton of Esch-sur-Alzette" => Ok(Self::CantonOfEschSurAlzette), "Canton of Grevenmacher" => Ok(Self::CantonOfGrevenmacher), "Canton of Luxembourg" => Ok(Self::CantonOfLuxembourg), "Canton of Mersch" => Ok(Self::CantonOfMersch), "Canton of Redange" => Ok(Self::CantonOfRedange), "Canton of Remich" => Ok(Self::CantonOfRemich), "Canton of Vianden" => Ok(Self::CantonOfVianden), "Canton of Wiltz" => Ok(Self::CantonOfWiltz), "Diekirch District" => Ok(Self::DiekirchDistrict), "Grevenmacher District" => Ok(Self::GrevenmacherDistrict), "Luxembourg District" => Ok(Self::LuxembourgDistrict), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for RussiaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "RussiaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Altai Krai" => Ok(Self::AltaiKrai), "Altai Republic" => Ok(Self::AltaiRepublic), "Amur Oblast" => Ok(Self::AmurOblast), "Arkhangelsk" => Ok(Self::Arkhangelsk), "Astrakhan Oblast" => Ok(Self::AstrakhanOblast), "Belgorod Oblast" => Ok(Self::BelgorodOblast), "Bryansk Oblast" => Ok(Self::BryanskOblast), "Chechen Republic" => Ok(Self::ChechenRepublic), "Chelyabinsk Oblast" => Ok(Self::ChelyabinskOblast), "Chukotka Autonomous Okrug" => Ok(Self::ChukotkaAutonomousOkrug), "Chuvash Republic" => Ok(Self::ChuvashRepublic), "Irkutsk" => Ok(Self::Irkutsk), "Ivanovo Oblast" => Ok(Self::IvanovoOblast), "Jewish Autonomous Oblast" => Ok(Self::JewishAutonomousOblast), "Kabardino-Balkar Republic" => Ok(Self::KabardinoBalkarRepublic), "Kaliningrad" => Ok(Self::Kaliningrad), "Kaluga Oblast" => Ok(Self::KalugaOblast), "Kamchatka Krai" => Ok(Self::KamchatkaKrai), "Karachay-Cherkess Republic" => Ok(Self::KarachayCherkessRepublic), "Kemerovo Oblast" => Ok(Self::KemerovoOblast), "Khabarovsk Krai" => Ok(Self::KhabarovskKrai), "Khanty-Mansi Autonomous Okrug" => Ok(Self::KhantyMansiAutonomousOkrug), "Kirov Oblast" => Ok(Self::KirovOblast), "Komi Republic" => Ok(Self::KomiRepublic), "Kostroma Oblast" => Ok(Self::KostromaOblast), "Krasnodar Krai" => Ok(Self::KrasnodarKrai), "Krasnoyarsk Krai" => Ok(Self::KrasnoyarskKrai), "Kurgan Oblast" => Ok(Self::KurganOblast), "Kursk Oblast" => Ok(Self::KurskOblast), "Leningrad Oblast" => Ok(Self::LeningradOblast), "Lipetsk Oblast" => Ok(Self::LipetskOblast), "Magadan Oblast" => Ok(Self::MagadanOblast), "Mari El Republic" => Ok(Self::MariElRepublic), "Moscow" => Ok(Self::Moscow), "Moscow Oblast" => Ok(Self::MoscowOblast), "Murmansk Oblast" => Ok(Self::MurmanskOblast), "Nenets Autonomous Okrug" => Ok(Self::NenetsAutonomousOkrug), "Nizhny Novgorod Oblast" => Ok(Self::NizhnyNovgorodOblast), "Novgorod Oblast" => Ok(Self::NovgorodOblast), "Novosibirsk" => Ok(Self::Novosibirsk), "Omsk Oblast" => Ok(Self::OmskOblast), "Orenburg Oblast" => Ok(Self::OrenburgOblast), "Oryol Oblast" => Ok(Self::OryolOblast), "Penza Oblast" => Ok(Self::PenzaOblast), "Perm Krai" => Ok(Self::PermKrai), "Primorsky Krai" => Ok(Self::PrimorskyKrai), "Pskov Oblast" => Ok(Self::PskovOblast), "Republic of Adygea" => Ok(Self::RepublicOfAdygea), "Republic of Bashkortostan" => Ok(Self::RepublicOfBashkortostan), "Republic of Buryatia" => Ok(Self::RepublicOfBuryatia), "Republic of Dagestan" => Ok(Self::RepublicOfDagestan), "Republic of Ingushetia" => Ok(Self::RepublicOfIngushetia), "Republic of Kalmykia" => Ok(Self::RepublicOfKalmykia), "Republic of Karelia" => Ok(Self::RepublicOfKarelia), "Republic of Khakassia" => Ok(Self::RepublicOfKhakassia), "Republic of Mordovia" => Ok(Self::RepublicOfMordovia), "Republic of North Ossetia-Alania" => Ok(Self::RepublicOfNorthOssetiaAlania), "Republic of Tatarstan" => Ok(Self::RepublicOfTatarstan), "Rostov Oblast" => Ok(Self::RostovOblast), "Ryazan Oblast" => Ok(Self::RyazanOblast), "Saint Petersburg" => Ok(Self::SaintPetersburg), "Sakha Republic" => Ok(Self::SakhaRepublic), "Sakhalin" => Ok(Self::Sakhalin), "Samara Oblast" => Ok(Self::SamaraOblast), "Saratov Oblast" => Ok(Self::SaratovOblast), "Sevastopol" => Ok(Self::Sevastopol), "Smolensk Oblast" => Ok(Self::SmolenskOblast), "Stavropol Krai" => Ok(Self::StavropolKrai), "Sverdlovsk" => Ok(Self::Sverdlovsk), "Tambov Oblast" => Ok(Self::TambovOblast), "Tomsk Oblast" => Ok(Self::TomskOblast), "Tula Oblast" => Ok(Self::TulaOblast), "Tuva Republic" => Ok(Self::TuvaRepublic), "Tver Oblast" => Ok(Self::TverOblast), "Tyumen Oblast" => Ok(Self::TyumenOblast), "Udmurt Republic" => Ok(Self::UdmurtRepublic), "Ulyanovsk Oblast" => Ok(Self::UlyanovskOblast), "Vladimir Oblast" => Ok(Self::VladimirOblast), "Vologda Oblast" => Ok(Self::VologdaOblast), "Voronezh Oblast" => Ok(Self::VoronezhOblast), "Yamalo-Nenets Autonomous Okrug" => Ok(Self::YamaloNenetsAutonomousOkrug), "Yaroslavl Oblast" => Ok(Self::YaroslavlOblast), "Zabaykalsky Krai" => Ok(Self::ZabaykalskyKrai), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for SanMarinoStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "SanMarinoStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Acquaviva" => Ok(Self::Acquaviva), "Borgo Maggiore" => Ok(Self::BorgoMaggiore), "Chiesanuova" => Ok(Self::Chiesanuova), "Domagnano" => Ok(Self::Domagnano), "Faetano" => Ok(Self::Faetano), "Fiorentino" => Ok(Self::Fiorentino), "Montegiardino" => Ok(Self::Montegiardino), "San Marino" => Ok(Self::SanMarino), "Serravalle" => Ok(Self::Serravalle), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for SerbiaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "SerbiaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Belgrade" => Ok(Self::Belgrade), "Bor District" => Ok(Self::BorDistrict), "Braničevo District" => Ok(Self::BraničevoDistrict), "Central Banat District" => Ok(Self::CentralBanatDistrict), "Jablanica District" => Ok(Self::JablanicaDistrict), "Kolubara District" => Ok(Self::KolubaraDistrict), "Mačva District" => Ok(Self::MačvaDistrict), "Moravica District" => Ok(Self::MoravicaDistrict), "Nišava District" => Ok(Self::NišavaDistrict), "North Banat District" => Ok(Self::NorthBanatDistrict), "North Bačka District" => Ok(Self::NorthBačkaDistrict), "Pirot District" => Ok(Self::PirotDistrict), "Podunavlje District" => Ok(Self::PodunavljeDistrict), "Pomoravlje District" => Ok(Self::PomoravljeDistrict), "Pčinja District" => Ok(Self::PčinjaDistrict), "Rasina District" => Ok(Self::RasinaDistrict), "Raška District" => Ok(Self::RaškaDistrict), "South Banat District" => Ok(Self::SouthBanatDistrict), "South Bačka District" => Ok(Self::SouthBačkaDistrict), "Srem District" => Ok(Self::SremDistrict), "Toplica District" => Ok(Self::ToplicaDistrict), "Vojvodina" => Ok(Self::Vojvodina), "West Bačka District" => Ok(Self::WestBačkaDistrict), "Zaječar District" => Ok(Self::ZaječarDistrict), "Zlatibor District" => Ok(Self::ZlatiborDistrict), "Šumadija District" => Ok(Self::ŠumadijaDistrict), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for SlovakiaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "SlovakiaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Banská Bystrica Region" => Ok(Self::BanskaBystricaRegion), "Bratislava Region" => Ok(Self::BratislavaRegion), "Košice Region" => Ok(Self::KosiceRegion), "Nitra Region" => Ok(Self::NitraRegion), "Prešov Region" => Ok(Self::PresovRegion), "Trenčín Region" => Ok(Self::TrencinRegion), "Trnava Region" => Ok(Self::TrnavaRegion), "Žilina Region" => Ok(Self::ZilinaRegion), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for SwedenStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "SwedenStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Blekinge" => Ok(Self::Blekinge), "Dalarna County" => Ok(Self::DalarnaCounty), "Gotland County" => Ok(Self::GotlandCounty), "Gävleborg County" => Ok(Self::GävleborgCounty), "Halland County" => Ok(Self::HallandCounty), "Jönköping County" => Ok(Self::JönköpingCounty), "Kalmar County" => Ok(Self::KalmarCounty), "Kronoberg County" => Ok(Self::KronobergCounty), "Norrbotten County" => Ok(Self::NorrbottenCounty), "Skåne County" => Ok(Self::SkåneCounty), "Stockholm County" => Ok(Self::StockholmCounty), "Södermanland County" => Ok(Self::SödermanlandCounty), "Uppsala County" => Ok(Self::UppsalaCounty), "Värmland County" => Ok(Self::VärmlandCounty), "Västerbotten County" => Ok(Self::VästerbottenCounty), "Västernorrland County" => Ok(Self::VästernorrlandCounty), "Västmanland County" => Ok(Self::VästmanlandCounty), "Västra Götaland County" => Ok(Self::VästraGötalandCounty), "Örebro County" => Ok(Self::ÖrebroCounty), "Östergötland County" => Ok(Self::ÖstergötlandCounty), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for SloveniaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "SloveniaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Ajdovščina Municipality" => Ok(Self::Ajdovščina), "Ankaran Municipality" => Ok(Self::Ankaran), "Beltinci Municipality" => Ok(Self::Beltinci), "Benedikt Municipality" => Ok(Self::Benedikt), "Bistrica ob Sotli Municipality" => Ok(Self::BistricaObSotli), "Bled Municipality" => Ok(Self::Bled), "Bloke Municipality" => Ok(Self::Bloke), "Bohinj Municipality" => Ok(Self::Bohinj), "Borovnica Municipality" => Ok(Self::Borovnica), "Bovec Municipality" => Ok(Self::Bovec), "Braslovče Municipality" => Ok(Self::Braslovče), "Brda Municipality" => Ok(Self::Brda), "Brezovica Municipality" => Ok(Self::Brezovica), "Brežice Municipality" => Ok(Self::Brežice), "Cankova Municipality" => Ok(Self::Cankova), "Cerklje na Gorenjskem Municipality" => Ok(Self::CerkljeNaGorenjskem), "Cerknica Municipality" => Ok(Self::Cerknica), "Cerkno Municipality" => Ok(Self::Cerkno), "Cerkvenjak Municipality" => Ok(Self::Cerkvenjak), "City Municipality of Celje" => Ok(Self::CityMunicipalityOfCelje), "City Municipality of Novo Mesto" => Ok(Self::CityMunicipalityOfNovoMesto), "Destrnik Municipality" => Ok(Self::Destrnik), "Divača Municipality" => Ok(Self::Divača), "Dobje Municipality" => Ok(Self::Dobje), "Dobrepolje Municipality" => Ok(Self::Dobrepolje), "Dobrna Municipality" => Ok(Self::Dobrna), "Dobrova–Polhov Gradec Municipality" => Ok(Self::DobrovaPolhovGradec), "Dobrovnik Municipality" => Ok(Self::Dobrovnik), "Dol pri Ljubljani Municipality" => Ok(Self::DolPriLjubljani), "Dolenjske Toplice Municipality" => Ok(Self::DolenjskeToplice), "Domžale Municipality" => Ok(Self::Domžale), "Dornava Municipality" => Ok(Self::Dornava), "Dravograd Municipality" => Ok(Self::Dravograd), "Duplek Municipality" => Ok(Self::Duplek), "Gorenja Vas–Poljane Municipality" => Ok(Self::GorenjaVasPoljane), "Gorišnica Municipality" => Ok(Self::Gorišnica), "Gorje Municipality" => Ok(Self::Gorje), "Gornja Radgona Municipality" => Ok(Self::GornjaRadgona), "Gornji Grad Municipality" => Ok(Self::GornjiGrad), "Gornji Petrovci Municipality" => Ok(Self::GornjiPetrovci), "Grad Municipality" => Ok(Self::Grad), "Grosuplje Municipality" => Ok(Self::Grosuplje), "Hajdina Municipality" => Ok(Self::Hajdina), "Hodoš Municipality" => Ok(Self::Hodoš), "Horjul Municipality" => Ok(Self::Horjul), "Hoče–Slivnica Municipality" => Ok(Self::HočeSlivnica), "Hrastnik Municipality" => Ok(Self::Hrastnik), "Hrpelje–Kozina Municipality" => Ok(Self::HrpeljeKozina), "Idrija Municipality" => Ok(Self::Idrija), "Ig Municipality" => Ok(Self::Ig), "Ivančna Gorica Municipality" => Ok(Self::IvančnaGorica), "Izola Municipality" => Ok(Self::Izola), "Jesenice Municipality" => Ok(Self::Jesenice), "Jezersko Municipality" => Ok(Self::Jezersko), "Juršinci Municipality" => Ok(Self::Jursinci), "Kamnik Municipality" => Ok(Self::Kamnik), "Kanal ob Soči Municipality" => Ok(Self::KanalObSoci), "Kidričevo Municipality" => Ok(Self::Kidricevo), "Kobarid Municipality" => Ok(Self::Kobarid), "Kobilje Municipality" => Ok(Self::Kobilje), "Komen Municipality" => Ok(Self::Komen), "Komenda Municipality" => Ok(Self::Komenda), "Koper City Municipality" => Ok(Self::Koper), "Kostanjevica na Krki Municipality" => Ok(Self::KostanjevicaNaKrki), "Kostel Municipality" => Ok(Self::Kostel), "Kozje Municipality" => Ok(Self::Kozje), "Kočevje Municipality" => Ok(Self::Kocevje), "Kranj City Municipality" => Ok(Self::Kranj), "Kranjska Gora Municipality" => Ok(Self::KranjskaGora), "Križevci Municipality" => Ok(Self::Krizevci), "Kungota" => Ok(Self::Kungota), "Kuzma Municipality" => Ok(Self::Kuzma), "Laško Municipality" => Ok(Self::Lasko), "Lenart Municipality" => Ok(Self::Lenart), "Lendava Municipality" => Ok(Self::Lendava), "Litija Municipality" => Ok(Self::Litija), "Ljubljana City Municipality" => Ok(Self::Ljubljana), "Ljubno Municipality" => Ok(Self::Ljubno), "Ljutomer Municipality" => Ok(Self::Ljutomer), "Logatec Municipality" => Ok(Self::Logatec), "Log–Dragomer Municipality" => Ok(Self::LogDragomer), "Lovrenc na Pohorju Municipality" => Ok(Self::LovrencNaPohorju), "Loška Dolina Municipality" => Ok(Self::LoskaDolina), "Loški Potok Municipality" => Ok(Self::LoskiPotok), "Lukovica Municipality" => Ok(Self::Lukovica), "Luče Municipality" => Ok(Self::Luče), "Majšperk Municipality" => Ok(Self::Majsperk), "Makole Municipality" => Ok(Self::Makole), "Maribor City Municipality" => Ok(Self::Maribor), "Markovci Municipality" => Ok(Self::Markovci), "Medvode Municipality" => Ok(Self::Medvode), "Mengeš Municipality" => Ok(Self::Menges), "Metlika Municipality" => Ok(Self::Metlika), "Mežica Municipality" => Ok(Self::Mezica), "Miklavž na Dravskem Polju Municipality" => Ok(Self::MiklavzNaDravskemPolju), "Miren–Kostanjevica Municipality" => Ok(Self::MirenKostanjevica), "Mirna Municipality" => Ok(Self::Mirna), "Mirna Peč Municipality" => Ok(Self::MirnaPec), "Mislinja Municipality" => Ok(Self::Mislinja), "Mokronog–Trebelno Municipality" => Ok(Self::MokronogTrebelno), "Moravske Toplice Municipality" => Ok(Self::MoravskeToplice), "Moravče Municipality" => Ok(Self::Moravce), "Mozirje Municipality" => Ok(Self::Mozirje), "Municipality of Apače" => Ok(Self::Apače), "Municipality of Cirkulane" => Ok(Self::Cirkulane), "Municipality of Ilirska Bistrica" => Ok(Self::IlirskaBistrica), "Municipality of Krško" => Ok(Self::Krsko), "Municipality of Škofljica" => Ok(Self::Skofljica), "Murska Sobota City Municipality" => Ok(Self::MurskaSobota), "Muta Municipality" => Ok(Self::Muta), "Naklo Municipality" => Ok(Self::Naklo), "Nazarje Municipality" => Ok(Self::Nazarje), "Nova Gorica City Municipality" => Ok(Self::NovaGorica), "Odranci Municipality" => Ok(Self::Odranci), "Oplotnica" => Ok(Self::Oplotnica), "Ormož Municipality" => Ok(Self::Ormoz), "Osilnica Municipality" => Ok(Self::Osilnica), "Pesnica Municipality" => Ok(Self::Pesnica), "Piran Municipality" => Ok(Self::Piran), "Pivka Municipality" => Ok(Self::Pivka), "Podlehnik Municipality" => Ok(Self::Podlehnik), "Podvelka Municipality" => Ok(Self::Podvelka), "Podčetrtek Municipality" => Ok(Self::Podcetrtek), "Poljčane Municipality" => Ok(Self::Poljcane), "Polzela Municipality" => Ok(Self::Polzela), "Postojna Municipality" => Ok(Self::Postojna), "Prebold Municipality" => Ok(Self::Prebold), "Preddvor Municipality" => Ok(Self::Preddvor), "Prevalje Municipality" => Ok(Self::Prevalje), "Ptuj City Municipality" => Ok(Self::Ptuj), "Puconci Municipality" => Ok(Self::Puconci), "Radenci Municipality" => Ok(Self::Radenci), "Radeče Municipality" => Ok(Self::Radece), "Radlje ob Dravi Municipality" => Ok(Self::RadljeObDravi), "Radovljica Municipality" => Ok(Self::Radovljica), "Ravne na Koroškem Municipality" => Ok(Self::RavneNaKoroskem), "Razkrižje Municipality" => Ok(Self::Razkrizje), "Rače–Fram Municipality" => Ok(Self::RaceFram), "Renče–Vogrsko Municipality" => Ok(Self::RenčeVogrsko), "Rečica ob Savinji Municipality" => Ok(Self::RecicaObSavinji), "Ribnica Municipality" => Ok(Self::Ribnica), "Ribnica na Pohorju Municipality" => Ok(Self::RibnicaNaPohorju), "Rogatec Municipality" => Ok(Self::Rogatec), "Rogaška Slatina Municipality" => Ok(Self::RogaskaSlatina), "Rogašovci Municipality" => Ok(Self::Rogasovci), "Ruše Municipality" => Ok(Self::Ruse), "Selnica ob Dravi Municipality" => Ok(Self::SelnicaObDravi), "Semič Municipality" => Ok(Self::Semic), "Sevnica Municipality" => Ok(Self::Sevnica), "Sežana Municipality" => Ok(Self::Sezana), "Slovenj Gradec City Municipality" => Ok(Self::SlovenjGradec), "Slovenska Bistrica Municipality" => Ok(Self::SlovenskaBistrica), "Slovenske Konjice Municipality" => Ok(Self::SlovenskeKonjice), "Sodražica Municipality" => Ok(Self::Sodrazica), "Solčava Municipality" => Ok(Self::Solcava), "Središče ob Dravi" => Ok(Self::SredisceObDravi), "Starše Municipality" => Ok(Self::Starse), "Straža Municipality" => Ok(Self::Straza), "Sveta Ana Municipality" => Ok(Self::SvetaAna), "Sveta Trojica v Slovenskih Goricah Municipality" => Ok(Self::SvetaTrojica), "Sveti Andraž v Slovenskih Goricah Municipality" => Ok(Self::SvetiAndraz), "Sveti Jurij ob Ščavnici Municipality" => Ok(Self::SvetiJurijObScavnici), "Sveti Jurij v Slovenskih Goricah Municipality" => { Ok(Self::SvetiJurijVSlovenskihGoricah) } "Sveti Tomaž Municipality" => Ok(Self::SvetiTomaz), "Tabor Municipality" => Ok(Self::Tabor), "Tišina Municipality" => Ok(Self::Tišina), "Tolmin Municipality" => Ok(Self::Tolmin), "Trbovlje Municipality" => Ok(Self::Trbovlje), "Trebnje Municipality" => Ok(Self::Trebnje), "Trnovska Vas Municipality" => Ok(Self::TrnovskaVas), "Trzin Municipality" => Ok(Self::Trzin), "Tržič Municipality" => Ok(Self::Tržič), "Turnišče Municipality" => Ok(Self::Turnišče), "Velika Polana Municipality" => Ok(Self::VelikaPolana), "Velike Lašče Municipality" => Ok(Self::VelikeLašče), "Veržej Municipality" => Ok(Self::Veržej), "Videm Municipality" => Ok(Self::Videm), "Vipava Municipality" => Ok(Self::Vipava), "Vitanje Municipality" => Ok(Self::Vitanje), "Vodice Municipality" => Ok(Self::Vodice), "Vojnik Municipality" => Ok(Self::Vojnik), "Vransko Municipality" => Ok(Self::Vransko), "Vrhnika Municipality" => Ok(Self::Vrhnika), "Vuzenica Municipality" => Ok(Self::Vuzenica), "Zagorje ob Savi Municipality" => Ok(Self::ZagorjeObSavi), "Zavrč Municipality" => Ok(Self::Zavrč), "Zreče Municipality" => Ok(Self::Zreče), "Črenšovci Municipality" => Ok(Self::Črenšovci), "Črna na Koroškem Municipality" => Ok(Self::ČrnaNaKoroškem), "Črnomelj Municipality" => Ok(Self::Črnomelj), "Šalovci Municipality" => Ok(Self::Šalovci), "Šempeter–Vrtojba Municipality" => Ok(Self::ŠempeterVrtojba), "Šentilj Municipality" => Ok(Self::Šentilj), "Šentjernej Municipality" => Ok(Self::Šentjernej), "Šentjur Municipality" => Ok(Self::Šentjur), "Šentrupert Municipality" => Ok(Self::Šentrupert), "Šenčur Municipality" => Ok(Self::Šenčur), "Škocjan Municipality" => Ok(Self::Škocjan), "Škofja Loka Municipality" => Ok(Self::ŠkofjaLoka), "Šmarje pri Jelšah Municipality" => Ok(Self::ŠmarjePriJelšah), "Šmarješke Toplice Municipality" => Ok(Self::ŠmarješkeToplice), "Šmartno ob Paki Municipality" => Ok(Self::ŠmartnoObPaki), "Šmartno pri Litiji Municipality" => Ok(Self::ŠmartnoPriLitiji), "Šoštanj Municipality" => Ok(Self::Šoštanj), "Štore Municipality" => Ok(Self::Štore), "Žalec Municipality" => Ok(Self::Žalec), "Železniki Municipality" => Ok(Self::Železniki), "Žetale Municipality" => Ok(Self::Žetale), "Žiri Municipality" => Ok(Self::Žiri), "Žirovnica Municipality" => Ok(Self::Žirovnica), "Žužemberk Municipality" => Ok(Self::Žužemberk), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for UkraineStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "UkraineStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Autonomous Republic of Crimea" => Ok(Self::AutonomousRepublicOfCrimea), "Cherkasy Oblast" => Ok(Self::CherkasyOblast), "Chernihiv Oblast" => Ok(Self::ChernihivOblast), "Chernivtsi Oblast" => Ok(Self::ChernivtsiOblast), "Dnipropetrovsk Oblast" => Ok(Self::DnipropetrovskOblast), "Donetsk Oblast" => Ok(Self::DonetskOblast), "Ivano-Frankivsk Oblast" => Ok(Self::IvanoFrankivskOblast), "Kharkiv Oblast" => Ok(Self::KharkivOblast), "Kherson Oblast" => Ok(Self::KhersonOblast), "Khmelnytsky Oblast" => Ok(Self::KhmelnytskyOblast), "Kiev" => Ok(Self::Kiev), "Kirovohrad Oblast" => Ok(Self::KirovohradOblast), "Kyiv Oblast" => Ok(Self::KyivOblast), "Luhansk Oblast" => Ok(Self::LuhanskOblast), "Lviv Oblast" => Ok(Self::LvivOblast), "Mykolaiv Oblast" => Ok(Self::MykolaivOblast), "Odessa Oblast" => Ok(Self::OdessaOblast), "Rivne Oblast" => Ok(Self::RivneOblast), "Sumy Oblast" => Ok(Self::SumyOblast), "Ternopil Oblast" => Ok(Self::TernopilOblast), "Vinnytsia Oblast" => Ok(Self::VinnytsiaOblast), "Volyn Oblast" => Ok(Self::VolynOblast), "Zakarpattia Oblast" => Ok(Self::ZakarpattiaOblast), "Zaporizhzhya Oblast" => Ok(Self::ZaporizhzhyaOblast), "Zhytomyr Oblast" => Ok(Self::ZhytomyrOblast), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } impl ForeignTryFrom<String> for BrazilStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.clone(), "BrazilStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => match value.as_str() { "Acre" => Ok(Self::Acre), "Alagoas" => Ok(Self::Alagoas), "Amapá" => Ok(Self::Amapá), "Amazonas" => Ok(Self::Amazonas), "Bahia" => Ok(Self::Bahia), "Ceará" => Ok(Self::Ceará), "Distrito Federal" => Ok(Self::DistritoFederal), "Espírito Santo" => Ok(Self::EspíritoSanto), "Goiás" => Ok(Self::Goiás), "Maranhão" => Ok(Self::Maranhão), "Mato Grosso" => Ok(Self::MatoGrosso), "Mato Grosso do Sul" => Ok(Self::MatoGrossoDoSul), "Minas Gerais" => Ok(Self::MinasGerais), "Pará" => Ok(Self::Pará), "Paraíba" => Ok(Self::Paraíba), "Paraná" => Ok(Self::Paraná), "Pernambuco" => Ok(Self::Pernambuco), "Piauí" => Ok(Self::Piauí), "Rio de Janeiro" => Ok(Self::RioDeJaneiro), "Rio Grande do Norte" => Ok(Self::RioGrandeDoNorte), "Rio Grande do Sul" => Ok(Self::RioGrandeDoSul), "Rondônia" => Ok(Self::Rondônia), "Roraima" => Ok(Self::Roraima), "Santa Catarina" => Ok(Self::SantaCatarina), "São Paulo" => Ok(Self::SãoPaulo), "Sergipe" => Ok(Self::Sergipe), "Tocantins" => Ok(Self::Tocantins), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), }, } } } pub trait ForeignTryFrom<F>: Sized { type Error; fn foreign_try_from(from: F) -> Result<Self, Self::Error>; } #[derive(Debug)] pub struct QrImage { pub data: String, } // Qr Image data source starts with this string // The base64 image data will be appended to it to image data source pub(crate) const QR_IMAGE_DATA_SOURCE_STRING: &str = "data:image/png;base64"; impl QrImage { pub fn new_from_data( data: String, ) -> Result<Self, error_stack::Report<common_utils::errors::QrCodeError>> { let qr_code = qrcode::QrCode::new(data.as_bytes()) .change_context(common_utils::errors::QrCodeError::FailedToCreateQrCode)?; let qrcode_image_buffer = qr_code.render::<Luma<u8>>().build(); let qrcode_dynamic_image = DynamicImage::ImageLuma8(qrcode_image_buffer); let mut image_bytes = std::io::BufWriter::new(std::io::Cursor::new(Vec::new())); // Encodes qrcode_dynamic_image and write it to image_bytes let _ = qrcode_dynamic_image.write_to(&mut image_bytes, ImageFormat::Png); let image_data_source = format!( "{},{}", QR_IMAGE_DATA_SOURCE_STRING, BASE64_ENGINE.encode(image_bytes.buffer()) ); Ok(Self { data: image_data_source, }) } pub fn new_colored_from_data( data: String, hex_color: &str, ) -> Result<Self, error_stack::Report<common_utils::errors::QrCodeError>> { let qr_code = qrcode::QrCode::new(data.as_bytes()) .change_context(common_utils::errors::QrCodeError::FailedToCreateQrCode)?; let qrcode_image_buffer = qr_code.render::<Luma<u8>>().build(); let (width, height) = qrcode_image_buffer.dimensions(); let mut colored_image = ImageBuffer::new(width, height); let rgb = Self::parse_hex_color(hex_color)?; for (x, y, pixel) in qrcode_image_buffer.enumerate_pixels() { let luminance = pixel.0[0]; let color = if luminance == 0 { Rgba([rgb.0, rgb.1, rgb.2, 255]) } else { Rgba([255, 255, 255, 255]) }; colored_image.put_pixel(x, y, color); } let qrcode_dynamic_image = DynamicImage::ImageRgba8(colored_image); let mut image_bytes = std::io::Cursor::new(Vec::new()); qrcode_dynamic_image .write_to(&mut image_bytes, ImageFormat::Png) .change_context(common_utils::errors::QrCodeError::FailedToCreateQrCode)?; let image_data_source = format!( "{},{}", QR_IMAGE_DATA_SOURCE_STRING, BASE64_ENGINE.encode(image_bytes.get_ref()) ); Ok(Self { data: image_data_source, }) } pub fn parse_hex_color(hex: &str) -> Result<(u8, u8, u8), common_utils::errors::QrCodeError> { let hex = hex.trim_start_matches('#'); if hex.len() == 6 { let r = u8::from_str_radix(&hex[0..2], 16).ok(); let g = u8::from_str_radix(&hex[2..4], 16).ok(); let b = u8::from_str_radix(&hex[4..6], 16).ok(); if let (Some(r), Some(g), Some(b)) = (r, g, b) { return Ok((r, g, b)); } } Err(common_utils::errors::QrCodeError::InvalidHexColor) } } #[cfg(test)] mod tests { use crate::utils; #[test] fn test_image_data_source_url() { let qr_image_data_source_url = utils::QrImage::new_from_data("Hyperswitch".to_string()); assert!(qr_image_data_source_url.is_ok()); } } pub fn is_mandate_supported( selected_pmd: PaymentMethodData, payment_method_type: Option<enums::PaymentMethodType>, mandate_implemented_pmds: HashSet<PaymentMethodDataType>, connector: &'static str, ) -> Result<(), Error> { if mandate_implemented_pmds.contains(&PaymentMethodDataType::from(selected_pmd.clone())) { Ok(()) } else { match payment_method_type { Some(pm_type) => Err(errors::ConnectorError::NotSupported { message: format!("{pm_type} mandate payment"), connector, } .into()), None => Err(errors::ConnectorError::NotSupported { message: "mandate payment".to_string(), connector, } .into()), } } } pub fn get_mandate_details( setup_mandate_details: Option<mandates::MandateData>, ) -> Result<Option<mandates::MandateAmountData>, error_stack::Report<errors::ConnectorError>> { setup_mandate_details .map(|mandate_data| match &mandate_data.mandate_type { Some(mandates::MandateDataType::SingleUse(mandate)) | Some(mandates::MandateDataType::MultiUse(Some(mandate))) => Ok(mandate.clone()), Some(mandates::MandateDataType::MultiUse(None)) => { Err(errors::ConnectorError::MissingRequiredField { field_name: "setup_future_usage.mandate_data.mandate_type.multi_use.amount", } .into()) } None => Err(errors::ConnectorError::MissingRequiredField { field_name: "setup_future_usage.mandate_data.mandate_type", } .into()), }) .transpose() } pub fn collect_values_by_removing_signature(value: &Value, signature: &String) -> Vec<String> { match value { Value::Null => vec!["null".to_owned()], Value::Bool(b) => vec![b.to_string()], Value::Number(n) => match n.as_f64() { Some(f) => vec![format!("{f:.2}")], None => vec![n.to_string()], }, Value::String(s) => { if signature == s { vec![] } else { vec![s.clone()] } } Value::Array(arr) => arr .iter() .flat_map(|v| collect_values_by_removing_signature(v, signature)) .collect(), Value::Object(obj) => obj .values() .flat_map(|v| collect_values_by_removing_signature(v, signature)) .collect(), } } pub fn collect_and_sort_values_by_removing_signature( value: &Value, signature: &String, ) -> Vec<String> { let mut values = collect_values_by_removing_signature(value, signature); values.sort(); values } #[derive(Debug, strum::Display, Eq, PartialEq, Hash)] pub enum PaymentMethodDataType { Card, Knet, Benefit, MomoAtm, CardRedirect, AliPayQr, AliPayRedirect, AliPayHkRedirect, AmazonPay, AmazonPayRedirect, Skrill, Paysera, MomoRedirect, KakaoPayRedirect, GoPayRedirect, GcashRedirect, ApplePay, ApplePayRedirect, ApplePayThirdPartySdk, DanaRedirect, DuitNow, GooglePay, Bluecode, GooglePayRedirect, GooglePayThirdPartySdk, MbWayRedirect, MobilePayRedirect, PaypalRedirect, PaypalSdk, Paze, SamsungPay, TwintRedirect, VippsRedirect, TouchNGoRedirect, WeChatPayRedirect, WeChatPayQr, CashappQr, SwishQr, KlarnaRedirect, KlarnaSdk, AffirmRedirect, AfterpayClearpayRedirect, PayBrightRedirect, WalleyRedirect, AlmaRedirect, AtomeRedirect, Breadpay, FlexitiRedirect, BancontactCard, Bizum, Blik, Eft, Eps, Giropay, Ideal, Interac, LocalBankRedirect, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingPoland, OnlineBankingSlovakia, OpenBankingUk, Przelewy24, Sofort, Trustly, OnlineBankingFpx, OnlineBankingThailand, AchBankDebit, SepaBankDebit, SepaGuarenteedDebit, BecsBankDebit, BacsBankDebit, AchBankTransfer, SepaBankTransfer, BacsBankTransfer, MultibancoBankTransfer, PermataBankTransfer, BcaBankTransfer, BniVaBankTransfer, BhnCardNetwork, BriVaBankTransfer, CimbVaBankTransfer, DanamonVaBankTransfer, MandiriVaBankTransfer, Pix, Pse, Crypto, MandatePayment, Reward, Upi, Boleto, Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart, Indomaret, Oxxo, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, Givex, PaySafeCar, CardToken, LocalBankTransfer, Mifinity, Fps, PromptPay, VietQr, OpenBanking, NetworkToken, NetworkTransactionIdAndCardDetails, DirectCarrierBilling, InstantBankTransfer, InstantBankTransferFinland, InstantBankTransferPoland, RevolutPay, IndonesianBankTransfer, } impl From<PaymentMethodData> for PaymentMethodDataType { fn from(pm_data: PaymentMethodData) -> Self { match pm_data { PaymentMethodData::Card(_) => Self::Card, PaymentMethodData::NetworkToken(_) => Self::NetworkToken, PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Self::NetworkTransactionIdAndCardDetails } PaymentMethodData::CardRedirect(card_redirect_data) => match card_redirect_data { payment_method_data::CardRedirectData::Knet {} => Self::Knet, payment_method_data::CardRedirectData::Benefit {} => Self::Benefit, payment_method_data::CardRedirectData::MomoAtm {} => Self::MomoAtm, payment_method_data::CardRedirectData::CardRedirect {} => Self::CardRedirect, }, PaymentMethodData::Wallet(wallet_data) => match wallet_data { payment_method_data::WalletData::AliPayQr(_) => Self::AliPayQr, payment_method_data::WalletData::AliPayRedirect(_) => Self::AliPayRedirect, payment_method_data::WalletData::AliPayHkRedirect(_) => Self::AliPayHkRedirect, payment_method_data::WalletData::AmazonPayRedirect(_) => Self::AmazonPayRedirect, payment_method_data::WalletData::Skrill(_) => Self::Skrill, payment_method_data::WalletData::Paysera(_) => Self::Paysera, payment_method_data::WalletData::MomoRedirect(_) => Self::MomoRedirect, payment_method_data::WalletData::KakaoPayRedirect(_) => Self::KakaoPayRedirect, payment_method_data::WalletData::GoPayRedirect(_) => Self::GoPayRedirect, payment_method_data::WalletData::GcashRedirect(_) => Self::GcashRedirect, payment_method_data::WalletData::AmazonPay(_) => Self::AmazonPay, payment_method_data::WalletData::ApplePay(_) => Self::ApplePay, payment_method_data::WalletData::ApplePayRedirect(_) => Self::ApplePayRedirect, payment_method_data::WalletData::ApplePayThirdPartySdk(_) => { Self::ApplePayThirdPartySdk } payment_method_data::WalletData::DanaRedirect {} => Self::DanaRedirect, payment_method_data::WalletData::GooglePay(_) => Self::GooglePay, payment_method_data::WalletData::BluecodeRedirect {} => Self::Bluecode, payment_method_data::WalletData::GooglePayRedirect(_) => Self::GooglePayRedirect, payment_method_data::WalletData::GooglePayThirdPartySdk(_) => { Self::GooglePayThirdPartySdk } payment_method_data::WalletData::MbWayRedirect(_) => Self::MbWayRedirect, payment_method_data::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect, payment_method_data::WalletData::PaypalRedirect(_) => Self::PaypalRedirect, payment_method_data::WalletData::PaypalSdk(_) => Self::PaypalSdk, payment_method_data::WalletData::Paze(_) => Self::Paze, payment_method_data::WalletData::SamsungPay(_) => Self::SamsungPay, payment_method_data::WalletData::TwintRedirect {} => Self::TwintRedirect, payment_method_data::WalletData::VippsRedirect {} => Self::VippsRedirect, payment_method_data::WalletData::TouchNGoRedirect(_) => Self::TouchNGoRedirect, payment_method_data::WalletData::WeChatPayRedirect(_) => Self::WeChatPayRedirect, payment_method_data::WalletData::WeChatPayQr(_) => Self::WeChatPayQr, payment_method_data::WalletData::CashappQr(_) => Self::CashappQr, payment_method_data::WalletData::SwishQr(_) => Self::SwishQr, payment_method_data::WalletData::Mifinity(_) => Self::Mifinity, payment_method_data::WalletData::RevolutPay(_) => Self::RevolutPay, }, PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { payment_method_data::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect, payment_method_data::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk, payment_method_data::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect, payment_method_data::PayLaterData::AfterpayClearpayRedirect { .. } => { Self::AfterpayClearpayRedirect } payment_method_data::PayLaterData::FlexitiRedirect { .. } => Self::FlexitiRedirect, payment_method_data::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect, payment_method_data::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect, payment_method_data::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect, payment_method_data::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect, payment_method_data::PayLaterData::BreadpayRedirect {} => Self::Breadpay, }, PaymentMethodData::BankRedirect(bank_redirect_data) => match bank_redirect_data { payment_method_data::BankRedirectData::BancontactCard { .. } => { Self::BancontactCard } payment_method_data::BankRedirectData::Bizum {} => Self::Bizum, payment_method_data::BankRedirectData::Blik { .. } => Self::Blik, payment_method_data::BankRedirectData::Eft { .. } => Self::Eft, payment_method_data::BankRedirectData::Eps { .. } => Self::Eps, payment_method_data::BankRedirectData::Giropay { .. } => Self::Giropay, payment_method_data::BankRedirectData::Ideal { .. } => Self::Ideal, payment_method_data::BankRedirectData::Interac { .. } => Self::Interac, payment_method_data::BankRedirectData::OnlineBankingCzechRepublic { .. } => { Self::OnlineBankingCzechRepublic } payment_method_data::BankRedirectData::OnlineBankingFinland { .. } => { Self::OnlineBankingFinland } payment_method_data::BankRedirectData::OnlineBankingPoland { .. } => { Self::OnlineBankingPoland } payment_method_data::BankRedirectData::OnlineBankingSlovakia { .. } => { Self::OnlineBankingSlovakia } payment_method_data::BankRedirectData::OpenBankingUk { .. } => Self::OpenBankingUk, payment_method_data::BankRedirectData::Przelewy24 { .. } => Self::Przelewy24, payment_method_data::BankRedirectData::Sofort { .. } => Self::Sofort, payment_method_data::BankRedirectData::Trustly { .. } => Self::Trustly, payment_method_data::BankRedirectData::OnlineBankingFpx { .. } => { Self::OnlineBankingFpx } payment_method_data::BankRedirectData::OnlineBankingThailand { .. } => { Self::OnlineBankingThailand } payment_method_data::BankRedirectData::LocalBankRedirect {} => { Self::LocalBankRedirect } }, PaymentMethodData::BankDebit(bank_debit_data) => match bank_debit_data { payment_method_data::BankDebitData::AchBankDebit { .. } => Self::AchBankDebit, payment_method_data::BankDebitData::SepaBankDebit { .. } => Self::SepaBankDebit, payment_method_data::BankDebitData::SepaGuarenteedBankDebit { .. } => { Self::SepaGuarenteedDebit } payment_method_data::BankDebitData::BecsBankDebit { .. } => Self::BecsBankDebit, payment_method_data::BankDebitData::BacsBankDebit { .. } => Self::BacsBankDebit, }, PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data { payment_method_data::BankTransferData::AchBankTransfer { .. } => { Self::AchBankTransfer } payment_method_data::BankTransferData::SepaBankTransfer { .. } => { Self::SepaBankTransfer } payment_method_data::BankTransferData::BacsBankTransfer { .. } => { Self::BacsBankTransfer } payment_method_data::BankTransferData::MultibancoBankTransfer { .. } => { Self::MultibancoBankTransfer } payment_method_data::BankTransferData::PermataBankTransfer { .. } => { Self::PermataBankTransfer } payment_method_data::BankTransferData::BcaBankTransfer { .. } => { Self::BcaBankTransfer } payment_method_data::BankTransferData::BniVaBankTransfer { .. } => { Self::BniVaBankTransfer } payment_method_data::BankTransferData::BriVaBankTransfer { .. } => { Self::BriVaBankTransfer } payment_method_data::BankTransferData::CimbVaBankTransfer { .. } => { Self::CimbVaBankTransfer } payment_method_data::BankTransferData::DanamonVaBankTransfer { .. } => { Self::DanamonVaBankTransfer } payment_method_data::BankTransferData::MandiriVaBankTransfer { .. } => { Self::MandiriVaBankTransfer } payment_method_data::BankTransferData::Pix { .. } => Self::Pix, payment_method_data::BankTransferData::Pse {} => Self::Pse, payment_method_data::BankTransferData::LocalBankTransfer { .. } => { Self::LocalBankTransfer } payment_method_data::BankTransferData::InstantBankTransfer {} => { Self::InstantBankTransfer } payment_method_data::BankTransferData::InstantBankTransferFinland {} => { Self::InstantBankTransferFinland } payment_method_data::BankTransferData::InstantBankTransferPoland {} => { Self::InstantBankTransferPoland } payment_method_data::BankTransferData::IndonesianBankTransfer { .. } => { Self::IndonesianBankTransfer } }, PaymentMethodData::Crypto(_) => Self::Crypto, PaymentMethodData::MandatePayment => Self::MandatePayment, PaymentMethodData::Reward => Self::Reward, PaymentMethodData::Upi(_) => Self::Upi, PaymentMethodData::Voucher(voucher_data) => match voucher_data { payment_method_data::VoucherData::Boleto(_) => Self::Boleto, payment_method_data::VoucherData::Efecty => Self::Efecty, payment_method_data::VoucherData::PagoEfectivo => Self::PagoEfectivo, payment_method_data::VoucherData::RedCompra => Self::RedCompra, payment_method_data::VoucherData::RedPagos => Self::RedPagos, payment_method_data::VoucherData::Alfamart(_) => Self::Alfamart, payment_method_data::VoucherData::Indomaret(_) => Self::Indomaret, payment_method_data::VoucherData::Oxxo => Self::Oxxo, payment_method_data::VoucherData::SevenEleven(_) => Self::SevenEleven, payment_method_data::VoucherData::Lawson(_) => Self::Lawson, payment_method_data::VoucherData::MiniStop(_) => Self::MiniStop, payment_method_data::VoucherData::FamilyMart(_) => Self::FamilyMart, payment_method_data::VoucherData::Seicomart(_) => Self::Seicomart, payment_method_data::VoucherData::PayEasy(_) => Self::PayEasy, }, PaymentMethodData::RealTimePayment(real_time_payment_data) => { match *real_time_payment_data { payment_method_data::RealTimePaymentData::DuitNow {} => Self::DuitNow, payment_method_data::RealTimePaymentData::Fps {} => Self::Fps, payment_method_data::RealTimePaymentData::PromptPay {} => Self::PromptPay, payment_method_data::RealTimePaymentData::VietQr {} => Self::VietQr, } } PaymentMethodData::GiftCard(gift_card_data) => match *gift_card_data { payment_method_data::GiftCardData::Givex(_) => Self::Givex, payment_method_data::GiftCardData::PaySafeCard {} => Self::PaySafeCar, payment_method_data::GiftCardData::BhnCardNetwork(_) => Self::BhnCardNetwork, }, PaymentMethodData::CardToken(_) => Self::CardToken, PaymentMethodData::OpenBanking(data) => match data { payment_method_data::OpenBankingData::OpenBankingPIS {} => Self::OpenBanking, }, PaymentMethodData::MobilePayment(mobile_payment_data) => match mobile_payment_data { payment_method_data::MobilePaymentData::DirectCarrierBilling { .. } => { Self::DirectCarrierBilling } }, } } } pub trait GooglePay { fn get_googlepay_encrypted_payment_data(&self) -> Result<Secret<String>, Error>; } impl GooglePay for payment_method_data::GooglePayWalletData { fn get_googlepay_encrypted_payment_data(&self) -> Result<Secret<String>, Error> { let encrypted_data = self .tokenization_data .get_encrypted_google_pay_payment_data_mandatory() .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Google Pay".to_string(), })?; Ok(Secret::new(encrypted_data.token.clone())) } } pub trait ApplePay { fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error>; } impl ApplePay for payment_method_data::ApplePayWalletData { fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error> { let apple_pay_encrypted_data = self .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", })?; let token = Secret::new( String::from_utf8( BASE64_ENGINE .decode(apple_pay_encrypted_data) .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })?, ) .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })?, ); Ok(token) } } pub trait WalletData { fn get_wallet_token(&self) -> Result<Secret<String>, Error>; fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error> where T: serde::de::DeserializeOwned; fn get_encoded_wallet_token(&self) -> Result<String, Error>; } impl WalletData for payment_method_data::WalletData { fn get_wallet_token(&self) -> Result<Secret<String>, Error> { match self { Self::GooglePay(data) => Ok(data.get_googlepay_encrypted_payment_data()?), Self::ApplePay(data) => Ok(data.get_applepay_decoded_payment_data()?), Self::PaypalSdk(data) => Ok(Secret::new(data.token.clone())), _ => Err(errors::ConnectorError::InvalidWallet.into()), } } fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error> where T: serde::de::DeserializeOwned, { serde_json::from_str::<T>(self.get_wallet_token()?.peek()) .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name }) } fn get_encoded_wallet_token(&self) -> Result<String, Error> { match self { Self::GooglePay(_) => { let json_token: Value = self.get_wallet_token_as_json("Google Pay".to_owned())?; let token_as_vec = serde_json::to_vec(&json_token).change_context( errors::ConnectorError::InvalidWalletToken { wallet_name: "Google Pay".to_string(), }, )?; let encoded_token = BASE64_ENGINE.encode(token_as_vec); Ok(encoded_token) } _ => Err( errors::ConnectorError::NotImplemented("SELECTED PAYMENT METHOD".to_owned()).into(), ), } } } pub fn deserialize_xml_to_struct<T: serde::de::DeserializeOwned>( xml_data: &[u8], ) -> Result<T, errors::ConnectorError> { let response_str = std::str::from_utf8(xml_data) .map_err(|e| { router_env::logger::error!("Error converting response data to UTF-8: {:?}", e); errors::ConnectorError::ResponseDeserializationFailed })? .trim(); let result: T = quick_xml::de::from_str(response_str).map_err(|e| { router_env::logger::error!("Error deserializing XML response: {:?}", e); errors::ConnectorError::ResponseDeserializationFailed })?; Ok(result) } pub fn is_html_response(response: &str) -> bool { response.starts_with("<html>") || response.starts_with("<!DOCTYPE html>") } #[cfg(feature = "payouts")] pub trait PayoutsData { fn get_transfer_id(&self) -> Result<String, Error>; fn get_customer_details( &self, ) -> Result<hyperswitch_domain_models::router_request_types::CustomerDetails, Error>; fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>; fn get_payout_type(&self) -> Result<enums::PayoutType, Error>; fn get_webhook_url(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; } #[cfg(feature = "payouts")] impl PayoutsData for hyperswitch_domain_models::router_request_types::PayoutsData { fn get_transfer_id(&self) -> Result<String, Error> { self.connector_payout_id .clone() .ok_or_else(missing_field_err("transfer_id")) } fn get_customer_details( &self, ) -> Result<hyperswitch_domain_models::router_request_types::CustomerDetails, Error> { self.customer_details .clone() .ok_or_else(missing_field_err("customer_details")) } fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error> { self.vendor_details .clone() .ok_or_else(missing_field_err("vendor_details")) } fn get_payout_type(&self) -> Result<enums::PayoutType, Error> { self.payout_type .to_owned() .ok_or_else(missing_field_err("payout_type")) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .to_owned() .ok_or_else(missing_field_err("webhook_url")) } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } } pub trait RevokeMandateRequestData { fn get_connector_mandate_id(&self) -> Result<String, Error>; } impl RevokeMandateRequestData for MandateRevokeRequestData { fn get_connector_mandate_id(&self) -> Result<String, Error> { self.connector_mandate_id .clone() .ok_or_else(missing_field_err("connector_mandate_id")) } } pub trait RecurringMandateData { fn get_original_payment_amount(&self) -> Result<i64, Error>; fn get_original_payment_currency(&self) -> Result<enums::Currency, Error>; } impl RecurringMandateData for RecurringMandatePaymentData { fn get_original_payment_amount(&self) -> Result<i64, Error> { self.original_payment_authorized_amount .ok_or_else(missing_field_err("original_payment_authorized_amount")) } fn get_original_payment_currency(&self) -> Result<enums::Currency, Error> { self.original_payment_authorized_currency .ok_or_else(missing_field_err("original_payment_authorized_currency")) } } #[cfg(feature = "payouts")] impl CardData for api_models::payouts::CardPayout { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.expiry_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let exp_month = self .expiry_month .peek() .to_string() .parse::<u8>() .map_err(|_| errors::ConnectorError::InvalidDataFormat { field_name: "payment_method_data.card.card_exp_month", })?; let month = ::cards::CardExpirationMonth::try_from(exp_month).map_err(|_| { errors::ConnectorError::InvalidDataFormat { field_name: "payment_method_data.card.card_exp_month", } })?; Ok(Secret::new(month.two_digits())) } fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.card_number.peek()) } fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?; Ok(Secret::new(format!( "{}{}{}", self.expiry_month.peek(), delimiter, year.peek() ))) } fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", year.peek(), delimiter, self.expiry_month.peek() )) } fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", self.expiry_month.peek(), delimiter, year.peek() )) } fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.expiry_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.expiry_month.clone().expose(); Ok(Secret::new(format!("{year}{month}"))) } fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { self.expiry_month .peek() .clone() .parse::<i8>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { self.expiry_year .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.expiry_month.clone().expose(); Ok(Secret::new(format!("{month}{year}"))) } fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> { self.get_expiry_year_4_digit() .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_cardholder_name(&self) -> Result<Secret<String>, Error> { self.card_holder_name .clone() .ok_or_else(missing_field_err("card.card_holder_name")) } } pub trait NetworkTokenData { fn get_card_issuer(&self) -> Result<CardIssuer, Error>; fn get_expiry_year_4_digit(&self) -> Secret<String>; fn get_network_token(&self) -> NetworkTokenNumber; fn get_network_token_expiry_month(&self) -> Secret<String>; fn get_network_token_expiry_year(&self) -> Secret<String>; fn get_cryptogram(&self) -> Option<Secret<String>>; fn get_token_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>; fn get_token_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError>; } impl NetworkTokenData for payment_method_data::NetworkTokenData { #[cfg(feature = "v1")] fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.token_number.peek()) } #[cfg(feature = "v2")] fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.network_token.peek()) } #[cfg(feature = "v1")] fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.token_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } #[cfg(feature = "v2")] fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.network_token_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } #[cfg(feature = "v1")] fn get_network_token(&self) -> NetworkTokenNumber { self.token_number.clone() } #[cfg(feature = "v2")] fn get_network_token(&self) -> NetworkTokenNumber { self.network_token.clone() } #[cfg(feature = "v1")] fn get_network_token_expiry_month(&self) -> Secret<String> { self.token_exp_month.clone() } #[cfg(feature = "v2")] fn get_network_token_expiry_month(&self) -> Secret<String> { self.network_token_exp_month.clone() } #[cfg(feature = "v1")] fn get_network_token_expiry_year(&self) -> Secret<String> { self.token_exp_year.clone() } #[cfg(feature = "v2")] fn get_network_token_expiry_year(&self) -> Secret<String> { self.network_token_exp_year.clone() } #[cfg(feature = "v1")] fn get_cryptogram(&self) -> Option<Secret<String>> { self.token_cryptogram.clone() } #[cfg(feature = "v2")] fn get_cryptogram(&self) -> Option<Secret<String>> { self.cryptogram.clone() } #[cfg(feature = "v1")] fn get_token_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.token_exp_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } #[cfg(feature = "v2")] fn get_token_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.network_token_exp_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } #[cfg(feature = "v1")] fn get_token_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_token_expiry_year_2_digit()?; Ok(Secret::new(format!( "{}{}{}", self.token_exp_month.peek(), delimiter, year.peek() ))) } #[cfg(feature = "v2")] fn get_token_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_token_expiry_year_2_digit()?; Ok(Secret::new(format!( "{}{}{}", self.network_token_exp_month.peek(), delimiter, year.peek() ))) } } pub fn convert_uppercase<'de, D, T>(v: D) -> Result<T, D::Error> where D: serde::Deserializer<'de>, T: FromStr, <T as FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error, { use serde::de::Error; let output = <&str>::deserialize(v)?; output.to_uppercase().parse::<T>().map_err(D::Error::custom) } pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data( data: &SetupMandateRouterData, ) -> PaymentsAuthorizeData { PaymentsAuthorizeData { currency: data.request.currency, payment_method_data: data.request.payment_method_data.clone(), confirm: data.request.confirm, statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(), mandate_id: data.request.mandate_id.clone(), setup_future_usage: data.request.setup_future_usage, off_session: data.request.off_session, setup_mandate_details: data.request.setup_mandate_details.clone(), router_return_url: data.request.router_return_url.clone(), email: data.request.email.clone(), customer_name: data.request.customer_name.clone(), amount: 0, order_tax_amount: Some(MinorUnit::zero()), minor_amount: MinorUnit::new(0), statement_descriptor: None, capture_method: data.request.capture_method, webhook_url: None, complete_authorize_url: None, browser_info: data.request.browser_info.clone(), order_details: None, order_category: None, session_token: None, enrolled_for_3ds: true, related_transaction_id: None, payment_experience: None, payment_method_type: None, customer_id: None, surcharge_details: None, request_extended_authorization: None, request_incremental_authorization: data.request.request_incremental_authorization, metadata: None, authentication_data: None, customer_acceptance: data.request.customer_acceptance.clone(), split_payments: None, // TODO: allow charges on mandates? merchant_order_reference_id: None, integrity_object: None, additional_payment_method_data: None, shipping_cost: data.request.shipping_cost, merchant_account_id: None, merchant_config_currency: None, connector_testing_data: data.request.connector_testing_data.clone(), order_id: None, locale: None, payment_channel: data.request.payment_channel.clone(), enable_partial_authorization: data.request.enable_partial_authorization, enable_overcapture: None, is_stored_credential: data.request.is_stored_credential, mit_category: None, } } pub(crate) fn convert_payment_authorize_router_response<F1, F2, T1, T2>( item: (&ConnectorRouterData<F1, T1, PaymentsResponseData>, T2), ) -> ConnectorRouterData<F2, T2, PaymentsResponseData> { let data = item.0; let request = item.1; ConnectorRouterData { flow: PhantomData, request, merchant_id: data.merchant_id.clone(), connector: data.connector.clone(), attempt_id: data.attempt_id.clone(), tenant_id: data.tenant_id.clone(), status: data.status, payment_method: data.payment_method, payment_method_type: data.payment_method_type, connector_auth_type: data.connector_auth_type.clone(), description: data.description.clone(), address: data.address.clone(), auth_type: data.auth_type, connector_meta_data: data.connector_meta_data.clone(), connector_wallets_details: data.connector_wallets_details.clone(), amount_captured: data.amount_captured, minor_amount_captured: data.minor_amount_captured, access_token: data.access_token.clone(), response: data.response.clone(), payment_id: data.payment_id.clone(), session_token: data.session_token.clone(), reference_id: data.reference_id.clone(), customer_id: data.customer_id.clone(), payment_method_token: None, preprocessing_id: None, connector_customer: data.connector_customer.clone(), recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(), connector_request_reference_id: data.connector_request_reference_id.clone(), #[cfg(feature = "payouts")] payout_method_data: data.payout_method_data.clone(), #[cfg(feature = "payouts")] quote_id: data.quote_id.clone(), test_mode: data.test_mode, payment_method_status: None, payment_method_balance: data.payment_method_balance.clone(), connector_api_version: data.connector_api_version.clone(), connector_http_status_code: data.connector_http_status_code, external_latency: data.external_latency, apple_pay_flow: data.apple_pay_flow.clone(), frm_metadata: data.frm_metadata.clone(), dispute_id: data.dispute_id.clone(), refund_id: data.refund_id.clone(), connector_response: data.connector_response.clone(), integrity_check: Ok(()), additional_merchant_data: data.additional_merchant_data.clone(), header_payload: data.header_payload.clone(), connector_mandate_request_reference_id: data.connector_mandate_request_reference_id.clone(), authentication_id: data.authentication_id.clone(), psd2_sca_exemption_type: data.psd2_sca_exemption_type, raw_connector_response: data.raw_connector_response.clone(), is_payment_id_from_merchant: data.is_payment_id_from_merchant, l2_l3_data: data.l2_l3_data.clone(), minor_amount_capturable: data.minor_amount_capturable, authorized_amount: data.authorized_amount, } } pub fn generate_12_digit_number() -> u64 { let mut rng = rand::thread_rng(); rng.gen_range(100_000_000_000..=999_999_999_999) } /// Normalizes a string by converting to lowercase, performing NFKD normalization(https://unicode.org/reports/tr15/#Description_Norm),and removing special characters and spaces. pub fn normalize_string(value: String) -> Result<String, regex::Error> { let nfkd_value = value.nfkd().collect::<String>(); let lowercase_value = nfkd_value.to_lowercase(); static REGEX: LazyLock<Result<Regex, regex::Error>> = LazyLock::new(|| Regex::new(r"[^a-z0-9]")); let regex = REGEX.as_ref().map_err(|e| e.clone())?; let normalized = regex.replace_all(&lowercase_value, "").to_string(); Ok(normalized) } fn normalize_state(value: String) -> Result<String, error_stack::Report<errors::ConnectorError>> { normalize_string(value).map_err(|_e| { error_stack::Report::new(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", }) }) } pub fn parse_state_enum<T>( value: String, enum_name: &'static str, field_name: &'static str, ) -> Result<String, error_stack::Report<errors::ConnectorError>> where T: FromStr, <T as FromStr>::Err: std::error::Error + Send + Sync + 'static, { match StringExt::<T>::parse_enum(value.clone(), enum_name) { Ok(_) => Ok(value), Err(_) => normalize_state(value).map_err(|_e| { error_stack::Report::new(errors::ConnectorError::InvalidDataFormat { field_name }) }), } } #[cfg(feature = "frm")] pub trait FrmTransactionRouterDataRequest { fn is_payment_successful(&self) -> Option<bool>; } #[cfg(feature = "frm")] impl FrmTransactionRouterDataRequest for FrmTransactionRouterData { fn is_payment_successful(&self) -> Option<bool> { match self.status { AttemptStatus::AuthenticationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthorizationFailed | AttemptStatus::Voided | AttemptStatus::VoidedPostCharge | AttemptStatus::CaptureFailed | AttemptStatus::Failure | AttemptStatus::AutoRefunded | AttemptStatus::Expired => Some(false), AttemptStatus::AuthenticationSuccessful | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::Authorized | AttemptStatus::Charged | AttemptStatus::IntegrityFailure | AttemptStatus::PartiallyAuthorized => Some(true), AttemptStatus::Started | AttemptStatus::AuthenticationPending | AttemptStatus::Authorizing | AttemptStatus::CodInitiated | AttemptStatus::VoidInitiated | AttemptStatus::CaptureInitiated | AttemptStatus::VoidFailed | AttemptStatus::PartialCharged | AttemptStatus::Unresolved | AttemptStatus::Pending | AttemptStatus::PaymentMethodAwaited | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending => None, } } } #[cfg(feature = "frm")] pub trait FraudCheckCheckoutRequest { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; } #[cfg(feature = "frm")] impl FraudCheckCheckoutRequest for FraudCheckCheckoutData { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { self.order_details .clone() .ok_or_else(missing_field_err("order_details")) } } #[cfg(feature = "frm")] pub trait FraudCheckTransactionRequest { fn get_currency(&self) -> Result<enums::Currency, Error>; } #[cfg(feature = "frm")] impl FraudCheckTransactionRequest for FraudCheckTransactionData { fn get_currency(&self) -> Result<enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } } /// Custom deserializer for Option<Currency> that treats empty strings as None pub fn deserialize_optional_currency<'de, D>( deserializer: D, ) -> Result<Option<enums::Currency>, D::Error> where D: serde::Deserializer<'de>, { let string_data: Option<String> = Option::deserialize(deserializer)?; match string_data { Some(ref value) if !value.is_empty() => value .clone() .parse_enum("Currency") .map(Some) .map_err(|_| serde::de::Error::custom(format!("Invalid currency code: {value}"))), _ => Ok(None), } } #[cfg(feature = "payouts")] pub trait CustomerDetails { fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError>; fn get_customer_name( &self, ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>; fn get_customer_email(&self) -> Result<Email, errors::ConnectorError>; fn get_customer_phone( &self, ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>; fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError>; } #[cfg(feature = "payouts")] impl CustomerDetails for hyperswitch_domain_models::router_request_types::CustomerDetails { fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError> { self.customer_id .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_id", }) } fn get_customer_name( &self, ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> { self.name .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_name", }) } fn get_customer_email(&self) -> Result<Email, errors::ConnectorError> { self.email .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_email", }) } fn get_customer_phone( &self, ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> { self.phone .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_phone", }) } fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError> { self.phone_country_code .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_phone_country_code", }) } } pub fn get_card_details( payment_method_data: PaymentMethodData, connector_name: &'static str, ) -> Result<Card, errors::ConnectorError> { match payment_method_data { PaymentMethodData::Card(details) => Ok(details), _ => Err(errors::ConnectorError::NotSupported { message: SELECTED_PAYMENT_METHOD.to_string(), connector: connector_name, })?, } } pub fn get_authorise_integrity_object<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: T, currency: String, ) -> Result<AuthoriseIntegrityObject, error_stack::Report<errors::ConnectorError>> { let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let amount_in_minor_unit = convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; Ok(AuthoriseIntegrityObject { amount: amount_in_minor_unit, currency: currency_enum, }) } pub fn get_sync_integrity_object<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: T, currency: String, ) -> Result<SyncIntegrityObject, error_stack::Report<errors::ConnectorError>> { let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let amount_in_minor_unit = convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; Ok(SyncIntegrityObject { amount: Some(amount_in_minor_unit), currency: Some(currency_enum), }) } pub fn get_capture_integrity_object<T>( amount_convertor: &dyn AmountConvertor<Output = T>, capture_amount: Option<T>, currency: String, ) -> Result<CaptureIntegrityObject, error_stack::Report<errors::ConnectorError>> { let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let capture_amount_in_minor_unit = capture_amount .map(|amount| convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)) .transpose()?; Ok(CaptureIntegrityObject { capture_amount: capture_amount_in_minor_unit, currency: currency_enum, }) } pub fn get_refund_integrity_object<T>( amount_convertor: &dyn AmountConvertor<Output = T>, refund_amount: T, currency: String, ) -> Result<RefundIntegrityObject, error_stack::Report<errors::ConnectorError>> { let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let refund_amount_in_minor_unit = convert_back_amount_to_minor_units(amount_convertor, refund_amount, currency_enum)?; Ok(RefundIntegrityObject { currency: currency_enum, refund_amount: refund_amount_in_minor_unit, }) } #[cfg(feature = "frm")] pub trait FraudCheckSaleRequest { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; } #[cfg(feature = "frm")] impl FraudCheckSaleRequest for FraudCheckSaleData { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { self.order_details .clone() .ok_or_else(missing_field_err("order_details")) } } #[cfg(feature = "frm")] pub trait FraudCheckRecordReturnRequest { fn get_currency(&self) -> Result<enums::Currency, Error>; } #[cfg(feature = "frm")] impl FraudCheckRecordReturnRequest for FraudCheckRecordReturnData { fn get_currency(&self) -> Result<enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } } pub trait SplitPaymentData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest>; } impl SplitPaymentData for PaymentsCaptureData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } impl SplitPaymentData for PaymentsAuthorizeData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { self.split_payments.clone() } } impl SplitPaymentData for PaymentsSyncData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { self.split_payments.clone() } } impl SplitPaymentData for PaymentsCancelData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } impl SplitPaymentData for SetupMandateRequestData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } impl SplitPaymentData for ExternalVaultProxyPaymentsData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } pub struct XmlSerializer; impl XmlSerializer { pub fn serialize_to_xml_bytes<T: Serialize>( item: &T, xml_version: &str, xml_encoding: Option<&str>, xml_standalone: Option<&str>, xml_doc_type: Option<&str>, ) -> Result<Vec<u8>, error_stack::Report<errors::ConnectorError>> { let mut xml_bytes = Vec::new(); let mut writer = Writer::new(std::io::Cursor::new(&mut xml_bytes)); writer .write_event(Event::Decl(BytesDecl::new( xml_version, xml_encoding, xml_standalone, ))) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to write XML declaration")?; if let Some(xml_doc_type_data) = xml_doc_type { writer .write_event(Event::DocType(BytesText::from_escaped(xml_doc_type_data))) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to write the XML declaration")?; }; let xml_body = quick_xml::se::to_string(&item) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to serialize the XML body")?; writer .write_event(Event::Text(BytesText::from_escaped(xml_body))) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to serialize the XML body")?; Ok(xml_bytes) } } pub fn deserialize_zero_minor_amount_as_none<'de, D>( deserializer: D, ) -> Result<Option<MinorUnit>, D::Error> where D: serde::de::Deserializer<'de>, { let amount = Option::<MinorUnit>::deserialize(deserializer)?; match amount { Some(value) if value.get_amount_as_i64() == 0 => Ok(None), _ => Ok(amount), } }
crates/hyperswitch_connectors/src/utils.rs
hyperswitch_connectors::src::utils
82,372
true
// File: crates/hyperswitch_connectors/src/connectors/nexinets.rs // Module: hyperswitch_connectors::src::connectors::nexinets pub mod transformers; use std::sync::LazyLock; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::ByteSliceExt, request::{Method, Request, RequestBuilder, RequestContent}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ errors::api_error_response::ApiErrorResponse, payment_method_data::PaymentMethodData, payments::payment_attempt::PaymentAttempt, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorTransactionId, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response, }, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; use masking::Mask; #[cfg(feature = "v2")] use masking::PeekInterface; use transformers as nexinets; use crate::{ constants::headers, types::ResponseRouterData, utils::{ is_mandate_supported, to_connector_meta, PaymentMethodDataType, PaymentsSyncRequestData, }, }; #[derive(Debug, Clone)] pub struct Nexinets; impl api::Payment for Nexinets {} impl api::PaymentSession for Nexinets {} impl api::ConnectorAccessToken for Nexinets {} impl api::MandateSetup for Nexinets {} impl api::PaymentAuthorize for Nexinets {} impl api::PaymentSync for Nexinets {} impl api::PaymentCapture for Nexinets {} impl api::PaymentVoid for Nexinets {} impl api::Refund for Nexinets {} impl api::RefundExecute for Nexinets {} impl api::RefundSync for Nexinets {} impl Nexinets { pub fn connector_transaction_id( &self, connector_meta: Option<&serde_json::Value>, ) -> CustomResult<Option<String>, errors::ConnectorError> { let meta: nexinets::NexinetsPaymentsMetadata = to_connector_meta(connector_meta.cloned())?; Ok(meta.transaction_id) } } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nexinets where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Nexinets { fn id(&self) -> &'static str { "nexinets" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.nexinets.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = nexinets::NexinetsAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: nexinets::NexinetsErrorResponse = res .response .parse_struct("NexinetsErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); let errors = response.errors; let mut message = String::new(); let mut static_message = String::new(); for error in errors.iter() { let field = error.field.to_owned().unwrap_or_default(); let mut msg = String::new(); if !field.is_empty() { msg.push_str(format!("{} : {}", field, error.message).as_str()); } else { error.message.clone_into(&mut msg) } if message.is_empty() { message.push_str(&msg); static_message.push_str(&msg); } else { message.push_str(format!(", {msg}").as_str()); } } let connector_reason = format!("reason : {} , message : {}", response.message, message); Ok(ErrorResponse { status_code: response.status, code: response.code.to_string(), message: static_message, reason: Some(connector_reason), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Nexinets { fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([ PaymentMethodDataType::Card, PaymentMethodDataType::PaypalRedirect, PaymentMethodDataType::ApplePay, PaymentMethodDataType::Eps, PaymentMethodDataType::Giropay, PaymentMethodDataType::Ideal, ]); is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nexinets {} impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nexinets {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nexinets { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Nexinets".to_string()) .into(), ) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nexinets { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let url = if matches!( req.request.capture_method, Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic) ) { format!("{}/orders/debit", self.base_url(connectors)) } else { format!("{}/orders/preauth", self.base_url(connectors)) }; Ok(url) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nexinets::NexinetsPaymentsRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: nexinets::NexinetsPreAuthOrDebitResponse = res .response .parse_struct("Nexinets PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nexinets { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let meta: nexinets::NexinetsPaymentsMetadata = to_connector_meta(req.request.connector_meta.clone())?; let order_id = nexinets::get_order_id(&meta)?; let transaction_id = match meta.psync_flow { transformers::NexinetsTransactionType::Debit | transformers::NexinetsTransactionType::Capture => { req.request.get_connector_transaction_id()? } _ => nexinets::get_transaction_id(&meta)?, }; Ok(format!( "{}/orders/{order_id}/transactions/{transaction_id}", self.base_url(connectors) )) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: nexinets::NexinetsPaymentResponse = res .response .parse_struct("nexinets NexinetsPaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nexinets { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let meta: nexinets::NexinetsPaymentsMetadata = to_connector_meta(req.request.connector_meta.clone())?; let order_id = nexinets::get_order_id(&meta)?; let transaction_id = nexinets::get_transaction_id(&meta)?; Ok(format!( "{}/orders/{order_id}/transactions/{transaction_id}/capture", self.base_url(connectors) )) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nexinets::NexinetsCaptureOrVoidRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: nexinets::NexinetsPaymentResponse = res .response .parse_struct("NexinetsPaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nexinets { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let meta: nexinets::NexinetsPaymentsMetadata = to_connector_meta(req.request.connector_meta.clone())?; let order_id = nexinets::get_order_id(&meta)?; let transaction_id = nexinets::get_transaction_id(&meta)?; Ok(format!( "{}/orders/{order_id}/transactions/{transaction_id}/cancel", self.base_url(connectors), )) } fn get_request_body( &self, req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nexinets::NexinetsCaptureOrVoidRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&PaymentsVoidType::get_url(self, req, connectors)?) .headers(PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: nexinets::NexinetsPaymentResponse = res .response .parse_struct("NexinetsPaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nexinets { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let meta: nexinets::NexinetsPaymentsMetadata = to_connector_meta(req.request.connector_metadata.clone())?; let order_id = nexinets::get_order_id(&meta)?; Ok(format!( "{}/orders/{order_id}/transactions/{}/refund", self.base_url(connectors), req.request.connector_transaction_id )) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nexinets::NexinetsRefundRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundExecuteType::get_headers(self, req, connectors)?) .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: nexinets::NexinetsRefundResponse = res .response .parse_struct("nexinets RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nexinets { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let transaction_id = req .request .connector_refund_id .clone() .ok_or(errors::ConnectorError::MissingConnectorRefundID)?; let meta: nexinets::NexinetsPaymentsMetadata = to_connector_meta(req.request.connector_metadata.clone())?; let order_id = nexinets::get_order_id(&meta)?; Ok(format!( "{}/orders/{order_id}/transactions/{transaction_id}", self.base_url(connectors) )) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: nexinets::NexinetsRefundResponse = res .response .parse_struct("nexinets RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl IncomingWebhook for Nexinets { fn get_webhook_object_reference_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { Ok(IncomingWebhookEvent::EventNotSupported) } fn get_webhook_resource_object( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } impl api::PaymentToken for Nexinets {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Nexinets { // Not Implemented (R) } static NEXINETS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, enums::CaptureMethod::SequentialAutomatic, ]; let supported_card_network = vec![ common_enums::CardNetwork::Visa, common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::DinersClub, common_enums::CardNetwork::Discover, common_enums::CardNetwork::Interac, common_enums::CardNetwork::JCB, common_enums::CardNetwork::CartesBancaires, common_enums::CardNetwork::UnionPay, ]; let mut nexinets_supported_payment_methods = SupportedPaymentMethods::new(); nexinets_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); nexinets_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); nexinets_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Ideal, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); nexinets_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Giropay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); nexinets_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Sofort, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); nexinets_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Eps, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); nexinets_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); nexinets_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::Paypal, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); nexinets_supported_payment_methods }); static NEXINETS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Nexinets", description: "Nexi and Nets join forces to create The European PayTech leader, a strategic combination to offer future-proof innovative payment solutions.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Sandbox, }; static NEXINETS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Nexinets { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&NEXINETS_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*NEXINETS_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&NEXINETS_SUPPORTED_WEBHOOK_FLOWS) } } impl ConnectorTransactionId for Nexinets { #[cfg(feature = "v1")] fn connector_transaction_id( &self, payment_attempt: &PaymentAttempt, ) -> Result<Option<String>, ApiErrorResponse> { let metadata = Self::connector_transaction_id(self, payment_attempt.connector_metadata.as_ref()); metadata.map_err(|_| ApiErrorResponse::ResourceIdNotFound) } #[cfg(feature = "v2")] fn connector_transaction_id( &self, payment_attempt: &PaymentAttempt, ) -> Result<Option<String>, ApiErrorResponse> { use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; let metadata = Self::connector_transaction_id( self, payment_attempt .connector_metadata .as_ref() .map(|connector_metadata| connector_metadata.peek()), ); metadata.map_err(|_| ApiErrorResponse::ResourceIdNotFound) } }
crates/hyperswitch_connectors/src/connectors/nexinets.rs
hyperswitch_connectors::src::connectors::nexinets
6,944
true
// File: crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs // Module: hyperswitch_connectors::src::connectors::hyperswitch_vault pub mod transformers; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{ Authorize, Capture, CreateConnectorCustomer, PSync, PaymentMethodToken, Session, SetupMandate, Void, }, refunds::{Execute, RSync}, vault::ExternalVaultCreateFlow, }, router_request_types::{ AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, VaultRequestData, }, router_response_types::{PaymentsResponseData, RefundsResponseData, VaultResponseData}, types::{ ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSessionRouterData, PaymentsSyncRouterData, RefreshTokenRouterData, RefundsRouterData, SetupMandateRouterData, TokenizationRouterData, VaultRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use masking::{ExposeInterface, Mask}; use transformers as hyperswitch_vault; use crate::{constants::headers, types::ResponseRouterData}; #[derive(Clone)] pub struct HyperswitchVault; impl api::Payment for HyperswitchVault {} impl api::PaymentSession for HyperswitchVault {} impl api::ConnectorAccessToken for HyperswitchVault {} impl api::MandateSetup for HyperswitchVault {} impl api::PaymentAuthorize for HyperswitchVault {} impl api::PaymentSync for HyperswitchVault {} impl api::PaymentCapture for HyperswitchVault {} impl api::PaymentVoid for HyperswitchVault {} impl api::Refund for HyperswitchVault {} impl api::RefundExecute for HyperswitchVault {} impl api::RefundSync for HyperswitchVault {} impl api::PaymentToken for HyperswitchVault {} impl api::ExternalVaultCreate for HyperswitchVault {} impl api::ConnectorCustomer for HyperswitchVault {} impl ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData, VaultResponseData> for HyperswitchVault { fn get_headers( &self, req: &VaultRouterData<ExternalVaultCreateFlow>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &VaultRouterData<ExternalVaultCreateFlow>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/v2/payment-method-sessions", self.base_url(connectors) )) } fn get_request_body( &self, req: &VaultRouterData<ExternalVaultCreateFlow>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = hyperswitch_vault::HyperswitchVaultCreateRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &VaultRouterData<ExternalVaultCreateFlow>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::ExternalVaultCreateType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::ExternalVaultCreateType::get_headers( self, req, connectors, )?) .set_body(types::ExternalVaultCreateType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &VaultRouterData<ExternalVaultCreateFlow>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<VaultRouterData<ExternalVaultCreateFlow>, errors::ConnectorError> { let response: hyperswitch_vault::HyperswitchVaultCreateResponse = res .response .parse_struct("HyperswitchVault HyperswitchVaultCreateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for HyperswitchVault { fn build_request( &self, _req: &TokenizationRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "PaymentMethodTokenization".to_string(), connector: self.id().to_string(), } .into()) } } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for HyperswitchVault where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = hyperswitch_vault::HyperswitchVaultAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let api_key = auth.api_key.expose(); let header = vec![ ( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), ), ( headers::AUTHORIZATION.to_string(), format!("api-key={api_key}").into_masked(), ), ( headers::X_PROFILE_ID.to_string(), auth.profile_id.expose().into_masked(), ), ]; Ok(header) } } impl ConnectorCommon for HyperswitchVault { fn id(&self) -> &'static str { "hyperswitch_vault" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.hyperswitch_vault.base_url.as_ref() } fn get_auth_header( &self, _auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { Ok(vec![]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: hyperswitch_vault::HyperswitchVaultErrorResponse = res .response .parse_struct("HyperswitchVaultErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.error.code, message: response.error.error_type, reason: response.error.message, attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> for HyperswitchVault { fn get_headers( &self, req: &ConnectorCustomerRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &ConnectorCustomerRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/v2/customers", self.base_url(connectors))) } fn get_request_body( &self, req: &ConnectorCustomerRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = hyperswitch_vault::HyperswitchVaultCustomerCreateRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &ConnectorCustomerRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::ConnectorCustomerType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::ConnectorCustomerType::get_headers( self, req, connectors, )?) .set_body(types::ConnectorCustomerType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &ConnectorCustomerRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<ConnectorCustomerRouterData, errors::ConnectorError> { let response: hyperswitch_vault::HyperswitchVaultCustomerCreateResponse = res .response .parse_struct("HyperswitchVault HyperswitchVaultCustomerCreateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorValidation for HyperswitchVault {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for HyperswitchVault { fn build_request( &self, _req: &PaymentsSessionRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "PaymentsSession".to_string(), connector: self.id().to_string(), } .into()) } } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for HyperswitchVault { fn build_request( &self, _req: &RefreshTokenRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "AccessTokenAuthorize".to_string(), connector: self.id().to_string(), } .into()) } } impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for HyperswitchVault { fn build_request( &self, _req: &SetupMandateRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "SetupMandate".to_string(), connector: self.id().to_string(), } .into()) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for HyperswitchVault { fn build_request( &self, _req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "PaymentsAuthorize".to_string(), connector: self.id().to_string(), } .into()) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for HyperswitchVault { fn build_request( &self, _req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "PaymentsSync".to_string(), connector: self.id().to_string(), } .into()) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for HyperswitchVault { fn build_request( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "PaymentsCapture".to_string(), connector: self.id().to_string(), } .into()) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for HyperswitchVault { fn build_request( &self, _req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "PaymentsCapture".to_string(), connector: self.id().to_string(), } .into()) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for HyperswitchVault { fn build_request( &self, _req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Refunds".to_string(), connector: self.id().to_string(), } .into()) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for HyperswitchVault { fn build_request( &self, _req: &RefundsRouterData<RSync>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "RefundsSync".to_string(), connector: self.id().to_string(), } .into()) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for HyperswitchVault { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } impl ConnectorSpecifications for HyperswitchVault { fn should_call_connector_customer( &self, _payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> bool { true } }
crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
hyperswitch_connectors::src::connectors::hyperswitch_vault
3,716
true
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo.rs // Module: hyperswitch_connectors::src::connectors::wellsfargo pub mod transformers; use std::sync::LazyLock; use base64::Engine; use common_enums::enums; use common_utils::{ consts, errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{report, Report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, mandate_revoke::MandateRevoke, payments::{ Authorize, Capture, IncrementalAuthorization, PSync, PaymentMethodToken, Session, SetupMandate, Void, }, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsIncrementalAuthorizationRouterData, PaymentsSyncRouterData, RefundExecuteRouterData, RefundSyncRouterData, SetupMandateRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, refunds::{Refund, RefundExecute, RefundSync}, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{ IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response, SetupMandateType, }, webhooks, }; use masking::{ExposeInterface, Mask, Maskable, PeekInterface}; use ring::{digest, hmac}; use time::OffsetDateTime; use transformers as wellsfargo; use url::Url; use crate::{ constants::{self, headers}, types::ResponseRouterData, utils::{self, convert_amount, PaymentMethodDataType, RefundsRequestData}, }; #[derive(Clone)] pub struct Wellsfargo { amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Wellsfargo { pub fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, } } pub fn generate_digest(&self, payload: &[u8]) -> String { let payload_digest = digest::digest(&digest::SHA256, payload); consts::BASE64_ENGINE.encode(payload_digest) } pub fn generate_signature( &self, auth: wellsfargo::WellsfargoAuthType, host: String, resource: &str, payload: &String, date: OffsetDateTime, http_method: Method, ) -> CustomResult<String, errors::ConnectorError> { let wellsfargo::WellsfargoAuthType { api_key, merchant_account, api_secret, } = auth; let is_post_method = matches!(http_method, Method::Post); let is_patch_method = matches!(http_method, Method::Patch); let is_delete_method = matches!(http_method, Method::Delete); let digest_str = if is_post_method || is_patch_method { "digest " } else { "" }; let headers = format!("host date (request-target) {digest_str}v-c-merchant-id"); let request_target = if is_post_method { format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n") } else if is_patch_method { format!("(request-target): patch {resource}\ndigest: SHA-256={payload}\n") } else if is_delete_method { format!("(request-target): delete {resource}\n") } else { format!("(request-target): get {resource}\n") }; let signature_string = format!( "host: {host}\ndate: {date}\n{request_target}v-c-merchant-id: {}", merchant_account.peek() ); let key_value = consts::BASE64_ENGINE .decode(api_secret.expose()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "connector_account_details.api_secret", })?; let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value); let signature_value = consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref()); let signature_header = format!( r#"keyid="{}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""#, api_key.peek() ); Ok(signature_header) } } impl ConnectorCommon for Wellsfargo { fn id(&self) -> &'static str { "wellsfargo" } fn common_get_content_type(&self) -> &'static str { "application/json;charset=utf-8" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.wellsfargo.base_url.as_ref() } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: Result< wellsfargo::WellsfargoErrorResponse, Report<common_utils::errors::ParsingError>, > = res.response.parse_struct("Wellsfargo ErrorResponse"); let error_message = if res.status_code == 401 { constants::CONNECTOR_UNAUTHORIZED_ERROR } else { hyperswitch_interfaces::consts::NO_ERROR_MESSAGE }; match response { Ok(transformers::WellsfargoErrorResponse::StandardError(response)) => { event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); let (code, message, reason) = match response.error_information { Some(ref error_info) => { let detailed_error_info = error_info.details.as_ref().map(|details| { details .iter() .map(|det| format!("{} : {}", det.field, det.reason)) .collect::<Vec<_>>() .join(", ") }); ( error_info.reason.clone(), error_info.reason.clone(), transformers::get_error_reason( Some(error_info.message.clone()), detailed_error_info, None, ), ) } None => { let detailed_error_info = response.details.map(|details| { details .iter() .map(|det| format!("{} : {}", det.field, det.reason)) .collect::<Vec<_>>() .join(", ") }); ( response.reason.clone().map_or( hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(), |reason| reason.to_string(), ), response .reason .map_or(error_message.to_string(), |reason| reason.to_string()), transformers::get_error_reason( response.message, detailed_error_info, None, ), ) } }; Ok(ErrorResponse { status_code: res.status_code, code, message, reason, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } Ok(transformers::WellsfargoErrorResponse::AuthenticationError(response)) => { event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(), message: response.response.rmsg.clone(), reason: Some(response.response.rmsg), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } Ok(transformers::WellsfargoErrorResponse::NotAvailableError(response)) => { event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); let error_response = response .errors .iter() .map(|error_info| { format!( "{}: {}", error_info.error_type.clone().unwrap_or("".to_string()), error_info.message.clone().unwrap_or("".to_string()) ) }) .collect::<Vec<String>>() .join(" & "); Ok(ErrorResponse { status_code: res.status_code, code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(), message: error_response.clone(), reason: Some(error_response), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } Err(error_msg) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); router_env::logger::error!(deserialization_error =? error_msg); utils::handle_json_response_deserialization_failure(res, "wellsfargo") } } } } impl ConnectorValidation for Wellsfargo { fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([ PaymentMethodDataType::Card, PaymentMethodDataType::ApplePay, PaymentMethodDataType::GooglePay, ]); utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Wellsfargo where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let date = OffsetDateTime::now_utc(); let wellsfargo_req = self.get_request_body(req, connectors)?; let auth = wellsfargo::WellsfargoAuthType::try_from(&req.connector_auth_type)?; let merchant_account = auth.merchant_account.clone(); let base_url = connectors.wellsfargo.base_url.as_str(); let wellsfargo_host = Url::parse(base_url).change_context(errors::ConnectorError::RequestEncodingFailed)?; let host = wellsfargo_host .host_str() .ok_or(errors::ConnectorError::RequestEncodingFailed)?; let path: String = self .get_url(req, connectors)? .chars() .skip(base_url.len() - 1) .collect(); let sha256 = self.generate_digest(wellsfargo_req.get_inner_value().expose().as_bytes()); let http_method = self.get_http_method(); let signature = self.generate_signature( auth, host.to_string(), path.as_str(), &sha256, date, http_method, )?; let mut headers = vec![ ( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), ), ( headers::ACCEPT.to_string(), "application/hal+json;charset=utf-8".to_string().into(), ), ( "v-c-merchant-id".to_string(), merchant_account.into_masked(), ), ("Date".to_string(), date.to_string().into()), ("Host".to_string(), host.to_string().into()), ("Signature".to_string(), signature.into_masked()), ]; if matches!(http_method, Method::Post | Method::Put | Method::Patch) { headers.push(( "Digest".to_string(), format!("SHA-256={sha256}").into_masked(), )); } Ok(headers) } } impl api::Payment for Wellsfargo {} impl api::PaymentAuthorize for Wellsfargo {} impl api::PaymentSync for Wellsfargo {} impl api::PaymentVoid for Wellsfargo {} impl api::PaymentCapture for Wellsfargo {} impl api::PaymentIncrementalAuthorization for Wellsfargo {} impl api::MandateSetup for Wellsfargo {} impl api::ConnectorAccessToken for Wellsfargo {} impl api::PaymentToken for Wellsfargo {} impl api::ConnectorMandateRevoke for Wellsfargo {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Wellsfargo { // Not Implemented (R) } impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Wellsfargo { fn get_headers( &self, req: &SetupMandateRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &SetupMandateRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}pts/v2/payments/", self.base_url(connectors))) } fn get_request_body( &self, req: &SetupMandateRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = wellsfargo::WellsfargoZeroMandateRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &SetupMandateRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&SetupMandateType::get_url(self, req, connectors)?) .attach_default_headers() .headers(SetupMandateType::get_headers(self, req, connectors)?) .set_body(SetupMandateType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &SetupMandateRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> { let response: wellsfargo::WellsfargoPaymentsResponse = res .response .parse_struct("WellsfargoSetupMandatesResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: wellsfargo::WellsfargoServerErrorResponse = res .response .parse_struct("WellsfargoServerErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|event| event.set_response_body(&response)); router_env::logger::info!(error_response=?response); let attempt_status = match response.reason { Some(reason) => match reason { transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None, }, None => None, }; Ok(ErrorResponse { status_code: res.status_code, reason: response.status.clone(), code: response .status .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: response .message .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData> for Wellsfargo { fn get_headers( &self, req: &MandateRevokeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_http_method(&self) -> Method { Method::Delete } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &MandateRevokeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}tms/v1/paymentinstruments/{}", self.base_url(connectors), utils::RevokeMandateRequestData::get_connector_mandate_id(&req.request)? )) } fn build_request( &self, req: &MandateRevokeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Delete) .url(&MandateRevokeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(MandateRevokeType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &MandateRevokeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<MandateRevokeRouterData, errors::ConnectorError> { if matches!(res.status_code, 204) { event_builder.map(|i| i.set_response_body(&serde_json::json!({"mandate_status": common_enums::MandateStatus::Revoked.to_string()}))); Ok(MandateRevokeRouterData { response: Ok(MandateRevokeResponseData { mandate_status: common_enums::MandateStatus::Revoked, }), ..data.clone() }) } else { // If http_code != 204 || http_code != 4xx, we dont know any other response scenario yet. let response_value: serde_json::Value = serde_json::from_slice(&res.response) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let response_string = response_value.to_string(); event_builder.map(|i| { i.set_response_body( &serde_json::json!({"response_string": response_string.clone()}), ) }); router_env::logger::info!(connector_response=?response_string); Ok(MandateRevokeRouterData { response: Err(ErrorResponse { code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(), message: response_string.clone(), reason: Some(response_string), status_code: res.status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..data.clone() }) } } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Wellsfargo { // Not Implemented (R) } impl api::PaymentSession for Wellsfargo {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Wellsfargo {} impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Wellsfargo { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}pts/v2/payments/{}/captures", self.base_url(connectors), connector_payment_id )) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, MinorUnit::new(req.request.amount_to_capture), req.request.currency, )?; let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req)); let connector_req = wellsfargo::WellsfargoPaymentsCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>, errors::ConnectorError, > { let response: wellsfargo::WellsfargoPaymentsResponse = res .response .parse_struct("Wellsfargo PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: wellsfargo::WellsfargoServerErrorResponse = res .response .parse_struct("WellsfargoServerErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|event| event.set_response_body(&response)); router_env::logger::info!(error_response=?response); Ok(ErrorResponse { status_code: res.status_code, reason: response.status.clone(), code: response .status .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: response .message .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Wellsfargo { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_http_method(&self) -> Method { Method::Get } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; Ok(format!( "{}tss/v2/transactions/{}", self.base_url(connectors), connector_payment_id )) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: wellsfargo::WellsfargoTransactionResponse = res .response .parse_struct("Wellsfargo PaymentSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Wellsfargo { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}pts/v2/payments/", ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, MinorUnit::new(req.request.amount), req.request.currency, )?; let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req)); let connector_req = wellsfargo::WellsfargoPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) .set_body(self.get_request_body(req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: wellsfargo::WellsfargoPaymentsResponse = res .response .parse_struct("Wellsfargo PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: wellsfargo::WellsfargoServerErrorResponse = res .response .parse_struct("WellsfargoServerErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|event| event.set_response_body(&response)); router_env::logger::info!(error_response=?response); let attempt_status = match response.reason { Some(reason) => match reason { transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None, }, None => None, }; Ok(ErrorResponse { status_code: res.status_code, reason: response.status.clone(), code: response .status .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: response .message .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Wellsfargo { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}pts/v2/payments/{connector_payment_id}/reversals", self.base_url(connectors) )) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_request_body( &self, req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, MinorUnit::new(req.request.amount.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "Amount", }, )?), req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "Currency", })?, )?; let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req)); let connector_req = wellsfargo::WellsfargoVoidRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(self.get_request_body(req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: wellsfargo::WellsfargoPaymentsResponse = res .response .parse_struct("Wellsfargo PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: wellsfargo::WellsfargoServerErrorResponse = res .response .parse_struct("WellsfargoServerErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|event| event.set_response_body(&response)); router_env::logger::info!(error_response=?response); Ok(ErrorResponse { status_code: res.status_code, reason: response.status.clone(), code: response .status .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: response .message .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl Refund for Wellsfargo {} impl RefundExecute for Wellsfargo {} impl RefundSync for Wellsfargo {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Wellsfargo { fn get_headers( &self, req: &RefundExecuteRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundExecuteRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}pts/v2/payments/{}/refunds", self.base_url(connectors), connector_payment_id )) } fn get_request_body( &self, req: &RefundExecuteRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, MinorUnit::new(req.request.refund_amount), req.request.currency, )?; let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req)); let connector_req = wellsfargo::WellsfargoRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundExecuteRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundExecuteType::get_headers(self, req, connectors)?) .set_body(self.get_request_body(req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundExecuteRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundExecuteRouterData, errors::ConnectorError> { let response: wellsfargo::WellsfargoRefundResponse = res .response .parse_struct("Wellsfargo RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Wellsfargo { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_http_method(&self) -> Method { Method::Get } fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let refund_id = req.request.get_connector_refund_id()?; Ok(format!( "{}tss/v2/transactions/{}", self.base_url(connectors), refund_id )) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: wellsfargo::WellsfargoRsyncResponse = res .response .parse_struct("Wellsfargo RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, > for Wellsfargo { fn get_headers( &self, req: &PaymentsIncrementalAuthorizationRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_http_method(&self) -> Method { Method::Patch } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsIncrementalAuthorizationRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}pts/v2/payments/{}", self.base_url(connectors), connector_payment_id )) } fn get_request_body( &self, req: &PaymentsIncrementalAuthorizationRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, MinorUnit::new(req.request.additional_amount), req.request.currency, )?; let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req)); let connector_request = wellsfargo::WellsfargoPaymentsIncrementalAuthorizationRequest::try_from( &connector_router_data, )?; Ok(RequestContent::Json(Box::new(connector_request))) } fn build_request( &self, req: &PaymentsIncrementalAuthorizationRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Patch) .url(&IncrementalAuthorizationType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(IncrementalAuthorizationType::get_headers( self, req, connectors, )?) .set_body(IncrementalAuthorizationType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsIncrementalAuthorizationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< RouterData< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >, errors::ConnectorError, > { let response: wellsfargo::WellsfargoPaymentsIncrementalAuthorizationResponse = res .response .parse_struct("Wellsfargo PaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Wellsfargo { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } static WELLSFARGO_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, enums::CaptureMethod::SequentialAutomatic, ]; let supported_card_network = vec![ common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::Discover, common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::Visa, ]; let mut wellsfargo_supported_payment_methods = SupportedPaymentMethods::new(); wellsfargo_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); wellsfargo_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); wellsfargo_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::GooglePay, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); wellsfargo_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); wellsfargo_supported_payment_methods.add( enums::PaymentMethod::BankDebit, enums::PaymentMethodType::Ach, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); wellsfargo_supported_payment_methods }); static WELLSFARGO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Wells Fargo", description: "Wells Fargo is a major bank offering retail, commercial, and wealth management services", connector_type: enums::HyperswitchConnectorCategory::BankAcquirer, integration_status: enums::ConnectorIntegrationStatus::Beta, }; static WELLSFARGO_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Wellsfargo { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&WELLSFARGO_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*WELLSFARGO_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&WELLSFARGO_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
hyperswitch_connectors::src::connectors::wellsfargo
10,987
true
// File: crates/hyperswitch_connectors/src/connectors/zsl.rs // Module: hyperswitch_connectors::src::connectors::zsl pub mod transformers; use std::fmt::Debug; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::{BytesExt, ValueExt}, request::{Method, Request, RequestBuilder, RequestContent}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ api::ApplicationResponse, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSessionRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails}, }; use lazy_static::lazy_static; use masking::{ExposeInterface, Secret}; use transformers::{self as zsl, get_status}; use crate::{ constants::headers, types::{RefreshTokenRouterData, ResponseRouterData}, }; #[derive(Debug, Clone)] pub struct Zsl; impl api::Payment for Zsl {} impl api::PaymentSession for Zsl {} impl api::ConnectorAccessToken for Zsl {} impl api::MandateSetup for Zsl {} impl api::PaymentAuthorize for Zsl {} impl api::PaymentSync for Zsl {} impl api::PaymentCapture for Zsl {} impl api::PaymentVoid for Zsl {} impl api::Refund for Zsl {} impl api::RefundExecute for Zsl {} impl api::RefundSync for Zsl {} impl api::PaymentToken for Zsl {} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Zsl where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, _req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; Ok(header) } } impl ConnectorCommon for Zsl { fn id(&self) -> &'static str { "zsl" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "application/x-www-form-urlencoded" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.zsl.base_url.as_ref() } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response = serde_urlencoded::from_bytes::<zsl::ZslErrorResponse>(&res.response) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let error_reason = zsl::ZslResponseStatus::try_from(response.status.clone())?.to_string(); Ok(ErrorResponse { status_code: res.status_code, code: response.status, message: error_reason.clone(), reason: Some(error_reason), attempt_status: Some(common_enums::AttemptStatus::Failure), connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Zsl { fn is_webhook_source_verification_mandatory(&self) -> bool { true } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Zsl { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}ecp", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = zsl::ZslRouterData::try_from(( &self.get_currency_unit(), req.request.currency, req.request.amount, req, ))?; let connector_req = zsl::ZslPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response = serde_urlencoded::from_bytes::<zsl::ZslPaymentsResponse>(&res.response) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i: &mut ConnectorEvent| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Zsl { fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: zsl::ZslWebhookResponse = res .response .parse_struct("ZslWebhookResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i: &mut ConnectorEvent| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Zsl { fn build_request( &self, _req: &PaymentsSessionRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotSupported { message: "Session flow".to_owned(), connector: "Zsl", } .into()) } } impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Zsl { fn build_request( &self, _req: &TokenizationRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotSupported { message: "PaymentMethod Tokenization flow ".to_owned(), connector: "Zsl", } .into()) } } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Zsl { fn build_request( &self, _req: &RefreshTokenRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotSupported { message: "AccessTokenAuth flow".to_owned(), connector: "Zsl", } .into()) } } impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Zsl { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotSupported { message: "SetupMandate flow".to_owned(), connector: "Zsl", } .into()) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Zsl { fn build_request( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotSupported { message: "Capture flow".to_owned(), connector: "Zsl", } .into()) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Zsl { fn build_request( &self, _req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotSupported { message: "Void flow ".to_owned(), connector: "Zsl", } .into()) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Zsl { fn build_request( &self, _req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotSupported { message: "Refund flow".to_owned(), connector: "Zsl", } .into()) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Zsl { fn build_request( &self, _req: &RefundSyncRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotSupported { message: "Rsync flow ".to_owned(), connector: "Zsl", } .into()) } } #[async_trait::async_trait] impl IncomingWebhook for Zsl { fn get_webhook_object_reference_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(notif.mer_ref), )) } fn get_webhook_event_type( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; Ok(get_status(notif.status)) } fn get_webhook_resource_object( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let response = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; Ok(Box::new(response)) } async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>, _connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_account_details = connector_account_details .parse_value::<ConnectorAuthType>("ConnectorAuthType") .change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed)?; let auth_type = zsl::ZslAuthType::try_from(&connector_account_details)?; let key = auth_type.api_key.expose(); let mer_id = auth_type.merchant_id.expose(); let webhook_response = get_webhook_object_from_body(request.body)?; let signature = zsl::calculate_signature( webhook_response.enctype, zsl::ZslSignatureType::WebhookSignature { status: webhook_response.status, txn_id: webhook_response.txn_id, txn_date: webhook_response.txn_date, paid_ccy: webhook_response.paid_ccy.to_string(), paid_amt: webhook_response.paid_amt, mer_ref: webhook_response.mer_ref, mer_id, key, }, )?; Ok(signature.eq(&webhook_response.signature)) } fn get_webhook_api_response( &self, _request: &IncomingWebhookRequestDetails<'_>, _error_kind: Option<IncomingWebhookFlowError>, ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> { Ok(ApplicationResponse::TextPlain("CALLBACK-OK".to_string())) } } fn get_webhook_object_from_body( body: &[u8], ) -> CustomResult<zsl::ZslWebhookResponse, errors::ConnectorError> { let response: zsl::ZslWebhookResponse = serde_urlencoded::from_bytes::<zsl::ZslWebhookResponse>(body) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; Ok(response) } lazy_static! { static ref ZSL_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { let supported_capture_methods = vec![enums::CaptureMethod::Automatic]; let mut zsl_supported_payment_methods = SupportedPaymentMethods::new(); zsl_supported_payment_methods.add( enums::PaymentMethod::BankTransfer, enums::PaymentMethodType::LocalBankTransfer, PaymentMethodDetails{ mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::NotSupported, supported_capture_methods, specific_features: None, }, ); zsl_supported_payment_methods }; static ref ZSL_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "ZSL", description: "Zsl is a payment gateway operating in China, specializing in facilitating local bank transfers", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Live, }; static ref ZSL_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); } impl ConnectorSpecifications for Zsl { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&*ZSL_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*ZSL_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&*ZSL_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/zsl.rs
hyperswitch_connectors::src::connectors::zsl
3,779
true
// File: crates/hyperswitch_connectors/src/connectors/braintree.rs // Module: hyperswitch_connectors::src::connectors::braintree pub mod transformers; use std::sync::LazyLock; use api_models::webhooks::IncomingWebhookEvent; use base64::Engine; use common_enums::{enums, CallConnectorAction, PaymentAction}; use common_utils::{ consts::BASE64_ENGINE, crypto, errors::{CustomResult, ParsingError}, ext_traits::{BytesExt, XmlExt}, request::{Method, Request, RequestBuilder, RequestContent}, types::{ AmountConvertor, StringMajorUnit, StringMajorUnitForConnector, StringMinorUnit, StringMinorUnitForConnector, }, }; use error_stack::{report, Report, ResultExt}; use hyperswitch_domain_models::{ api::ApplicationResponse, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, mandate_revoke::MandateRevoke, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, CompleteAuthorize, }, router_request_types::{ AccessTokenRequestData, CompleteAuthorizeData, MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsSessionRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, disputes::DisputePayload, errors, events::connector_api_logs::ConnectorEvent, types::{ MandateRevokeType, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsSessionType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response, TokenizationType, }, webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails}, }; use masking::{ExposeInterface, Mask, PeekInterface, Secret}; use ring::hmac; use router_env::logger; use sha1::{Digest, Sha1}; use transformers::{self as braintree, get_status}; use crate::{ constants::headers, types::ResponseRouterData, utils::{ self, convert_amount, is_mandate_supported, PaymentMethodDataType, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, }, }; #[derive(Clone)] pub struct Braintree { amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), amount_converter_webhooks: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), } impl Braintree { pub const fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, amount_converter_webhooks: &StringMinorUnitForConnector, } } } pub const BRAINTREE_VERSION: &str = "Braintree-Version"; pub const BRAINTREE_VERSION_VALUE: &str = "2019-01-01"; impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Braintree where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), ), ( BRAINTREE_VERSION.to_string(), BRAINTREE_VERSION_VALUE.to_string().into(), ), ]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Braintree { fn id(&self) -> &'static str { "braintree" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.braintree.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = braintree::BraintreeAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let auth_key = format!("{}:{}", auth.public_key.peek(), auth.private_key.peek()); let auth_header = format!("Basic {}", BASE64_ENGINE.encode(auth_key)); Ok(vec![( headers::AUTHORIZATION.to_string(), auth_header.into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: Result<braintree::ErrorResponses, Report<ParsingError>> = res.response.parse_struct("Braintree Error Response"); match response { Ok(braintree::ErrorResponses::BraintreeApiErrorResponse(response)) => { event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); let error_object = response.api_error_response.errors; let error = error_object.errors.first().or(error_object .transaction .as_ref() .and_then(|transaction_error| { transaction_error.errors.first().or(transaction_error .credit_card .as_ref() .and_then(|credit_card_error| credit_card_error.errors.first())) })); let (code, message) = error.map_or( (NO_ERROR_CODE.to_string(), NO_ERROR_MESSAGE.to_string()), |error| (error.code.clone(), error.message.clone()), ); Ok(ErrorResponse { status_code: res.status_code, code, message, reason: Some(response.api_error_response.message), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } Ok(braintree::ErrorResponses::BraintreeErrorResponse(response)) => { event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: NO_ERROR_CODE.to_string(), message: NO_ERROR_MESSAGE.to_string(), reason: Some(response.errors), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } Err(error_msg) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); logger::error!(deserialization_error =? error_msg); utils::handle_json_response_deserialization_failure(res, "braintree") } } } } impl ConnectorValidation for Braintree { fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, pm_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]); is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } impl api::Payment for Braintree {} impl api::PaymentAuthorize for Braintree {} impl api::PaymentSync for Braintree {} impl api::PaymentVoid for Braintree {} impl api::PaymentCapture for Braintree {} impl api::PaymentsCompleteAuthorize for Braintree {} impl api::PaymentSession for Braintree {} impl api::ConnectorAccessToken for Braintree {} impl api::ConnectorMandateRevoke for Braintree {} impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Braintree { // Not Implemented (R) } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Braintree { fn get_headers( &self, req: &PaymentsSessionRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsSessionRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn get_request_body( &self, req: &PaymentsSessionRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let metadata: braintree::BraintreeMeta = braintree::BraintreeMeta::try_from(&req.connector_meta_data)?; let connector_req = braintree::BraintreeClientTokenRequest::try_from(metadata)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsSessionRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsSessionType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsSessionType::get_headers(self, req, connectors)?) .set_body(PaymentsSessionType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsSessionRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSessionRouterData, errors::ConnectorError> where PaymentsResponseData: Clone, { let response: braintree::BraintreeSessionResponse = res .response .parse_struct("BraintreeSessionResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); utils::ForeignTryFrom::foreign_try_from(( crate::types::PaymentsSessionResponseRouterData { response, data: data.clone(), http_code: res.status_code, }, data.clone(), )) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::PaymentToken for Braintree {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Braintree { fn get_headers( &self, req: &TokenizationRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &TokenizationRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn get_request_body( &self, req: &TokenizationRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = transformers::BraintreeTokenRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &TokenizationRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&TokenizationType::get_url(self, req, connectors)?) .attach_default_headers() .headers(TokenizationType::get_headers(self, req, connectors)?) .set_body(TokenizationType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &TokenizationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<TokenizationRouterData, errors::ConnectorError> where PaymentsResponseData: Clone, { let response: transformers::BraintreeTokenResponse = res .response .parse_struct("BraintreeTokenResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::MandateSetup for Braintree {} #[allow(dead_code)] impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Braintree { // Not Implemented (R) fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Braintree".to_string()) .into(), ) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Braintree { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, )?; let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?; let connector_req = transformers::BraintreeCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: transformers::BraintreeCaptureResponse = res .response .parse_struct("Braintree PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Braintree { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn get_request_body( &self, req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = transformers::BraintreePSyncRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .set_body(PaymentsSyncType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: transformers::BraintreePSyncResponse = res .response .parse_struct("Braintree PaymentSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Braintree { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?; let connector_req: transformers::BraintreePaymentsRequest = transformers::BraintreePaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { match data.request.is_auto_capture()? { true => { let response: transformers::BraintreePaymentsResponse = res .response .parse_struct("Braintree PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } false => { let response: transformers::BraintreeAuthResponse = res .response .parse_struct("Braintree AuthResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } } } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData> for Braintree { fn get_headers( &self, req: &MandateRevokeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, _req: &MandateRevokeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn build_request( &self, req: &MandateRevokeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&MandateRevokeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(MandateRevokeType::get_headers(self, req, connectors)?) .set_body(MandateRevokeType::get_request_body(self, req, connectors)?) .build(), )) } fn get_request_body( &self, req: &MandateRevokeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = transformers::BraintreeRevokeMandateRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn handle_response( &self, data: &MandateRevokeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<MandateRevokeRouterData, errors::ConnectorError> { let response: transformers::BraintreeRevokeMandateResponse = res .response .parse_struct("BraintreeRevokeMandateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Braintree { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?) .build(), )) } fn get_request_body( &self, req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = transformers::BraintreeCancelRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: transformers::BraintreeCancelResponse = res .response .parse_struct("Braintree VoidResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::Refund for Braintree {} impl api::RefundExecute for Braintree {} impl api::RefundSync for Braintree {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Braintree { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?; let connector_req = transformers::BraintreeRefundRequest::try_from(connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundExecuteType::get_headers(self, req, connectors)?) .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: transformers::BraintreeRefundResponse = res .response .parse_struct("Braintree RefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Braintree { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn get_request_body( &self, req: &RefundSyncRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = transformers::BraintreeRSyncRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundSyncType::get_headers(self, req, connectors)?) .set_body(RefundSyncType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RouterData<RSync, RefundsData, RefundsResponseData>, errors::ConnectorError> { let response: transformers::BraintreeRSyncResponse = res .response .parse_struct("Braintree RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl IncomingWebhook for Braintree { fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha1)) } fn get_webhook_source_verification_signature( &self, request: &IncomingWebhookRequestDetails<'_>, connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let notif_item = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let signature_pairs: Vec<(&str, &str)> = notif_item .bt_signature .split('&') .collect::<Vec<&str>>() .into_iter() .map(|pair| pair.split_once('|').unwrap_or(("", ""))) .collect::<Vec<(_, _)>>(); let merchant_secret = connector_webhook_secrets .additional_secret //public key .clone() .ok_or(errors::ConnectorError::WebhookVerificationSecretNotFound)?; let signature = get_matching_webhook_signature(signature_pairs, merchant_secret.expose()) .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; Ok(signature.as_bytes().to_vec()) } fn get_webhook_source_verification_message( &self, request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let notify = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let message = notify.bt_payload.to_string(); Ok(message.into_bytes()) } async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_label, connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(errors::ConnectorError::WebhookSignatureNotFound)?; let message = self .get_webhook_source_verification_message( request, merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let sha1_hash_key = Sha1::digest(&connector_webhook_secrets.secret); let signing_key = hmac::Key::new( hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, sha1_hash_key.as_slice(), ); let signed_messaged = hmac::sign(&signing_key, &message); let payload_sign: String = hex::encode(signed_messaged); Ok(payload_sign.as_bytes().eq(&signature)) } fn get_webhook_object_reference_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let notif = get_webhook_object_from_body(_request.body) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?; match response.dispute { Some(dispute_data) => Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( dispute_data.transaction.id, ), )), None => Err(report!(errors::ConnectorError::WebhookReferenceIdNotFound)), } } fn get_webhook_event_type( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?; Ok(get_status(response.kind.as_str())) } fn get_webhook_resource_object( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?; Ok(Box::new(response)) } fn get_webhook_api_response( &self, _request: &IncomingWebhookRequestDetails<'_>, _error_kind: Option<IncomingWebhookFlowError>, ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> { Ok(ApplicationResponse::TextPlain("[accepted]".to_string())) } fn get_dispute_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<DisputePayload, errors::ConnectorError> { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?; match response.dispute { Some(dispute_data) => Ok(DisputePayload { amount: convert_amount( self.amount_converter_webhooks, dispute_data.amount_disputed, dispute_data.currency_iso_code, )?, currency: dispute_data.currency_iso_code, dispute_stage: transformers::get_dispute_stage(dispute_data.kind.as_str())?, connector_dispute_id: dispute_data.id, connector_reason: dispute_data.reason, connector_reason_code: dispute_data.reason_code, challenge_required_by: dispute_data.reply_by_date, connector_status: dispute_data.status, created_at: dispute_data.created_at, updated_at: dispute_data.updated_at, }), None => Err(errors::ConnectorError::WebhookResourceObjectNotFound)?, } } } fn get_matching_webhook_signature( signature_pairs: Vec<(&str, &str)>, secret: String, ) -> Option<String> { for (public_key, signature) in signature_pairs { if *public_key == secret { return Some(signature.to_string()); } } None } fn get_webhook_object_from_body( body: &[u8], ) -> CustomResult<transformers::BraintreeWebhookResponse, ParsingError> { serde_urlencoded::from_bytes::<transformers::BraintreeWebhookResponse>(body) .change_context(ParsingError::StructParseFailure("BraintreeWebhookResponse")) } fn decode_webhook_payload( payload: &[u8], ) -> CustomResult<transformers::Notification, errors::ConnectorError> { let decoded_response = BASE64_ENGINE .decode(payload) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let xml_response = String::from_utf8(decoded_response) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; xml_response .parse_xml::<transformers::Notification>() .change_context(errors::ConnectorError::WebhookBodyDecodingFailed) } impl ConnectorRedirectResponse for Braintree { fn get_flow_type( &self, _query_params: &str, json_payload: Option<serde_json::Value>, action: PaymentAction, ) -> CustomResult<CallConnectorAction, errors::ConnectorError> { match action { PaymentAction::PSync => match json_payload { Some(payload) => { let redirection_response: transformers::BraintreeRedirectionResponse = serde_json::from_value(payload).change_context( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "redirection_response", }, )?; let braintree_payload = serde_json::from_str::<transformers::BraintreeThreeDsErrorResponse>( &redirection_response.authentication_response, ); let (error_code, error_message) = match braintree_payload { Ok(braintree_response_payload) => ( braintree_response_payload.code, braintree_response_payload.message, ), Err(_) => ( NO_ERROR_CODE.to_string(), redirection_response.authentication_response, ), }; Ok(CallConnectorAction::StatusUpdate { status: enums::AttemptStatus::AuthenticationFailed, error_code: Some(error_code), error_message: Some(error_message), }) } None => Ok(CallConnectorAction::Avoid), }, PaymentAction::CompleteAuthorize | PaymentAction::PaymentAuthenticateCompleteAuthorize => { Ok(CallConnectorAction::Trigger) } } } } impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> for Braintree { fn get_headers( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_string()) } fn get_request_body( &self, req: &PaymentsCompleteAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?; let connector_req = transformers::BraintreePaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCompleteAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(PaymentsCompleteAuthorizeType::get_headers( self, req, connectors, )?) .set_body(PaymentsCompleteAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCompleteAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { match PaymentsCompleteAuthorizeRequestData::is_auto_capture(&data.request)? { true => { let response: transformers::BraintreeCompleteChargeResponse = res .response .parse_struct("Braintree PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } false => { let response: transformers::BraintreeCompleteAuthResponse = res .response .parse_struct("Braintree AuthResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } } } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } static BRAINTREE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, enums::CaptureMethod::SequentialAutomatic, ]; let supported_card_network = vec![ common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::Discover, common_enums::CardNetwork::JCB, common_enums::CardNetwork::UnionPay, common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::Visa, ]; let mut braintree_supported_payment_methods = SupportedPaymentMethods::new(); braintree_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); braintree_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); braintree_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::GooglePay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); braintree_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); braintree_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::Paypal, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); braintree_supported_payment_methods }); static BRAINTREE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Braintree", description: "Braintree, a PayPal service, offers a full-stack payment platform that simplifies accepting payments in your app or website, supporting various payment methods including credit cards and PayPal.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Live, }; static BRAINTREE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] = [enums::EventClass::Payments, enums::EventClass::Refunds]; impl ConnectorSpecifications for Braintree { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&BRAINTREE_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*BRAINTREE_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&BRAINTREE_SUPPORTED_WEBHOOK_FLOWS) } fn is_sdk_client_token_generation_enabled(&self) -> bool { true } fn supported_payment_method_types_for_sdk_client_token_generation( &self, ) -> Vec<enums::PaymentMethodType> { vec![ enums::PaymentMethodType::ApplePay, enums::PaymentMethodType::GooglePay, enums::PaymentMethodType::Paypal, ] } }
crates/hyperswitch_connectors/src/connectors/braintree.rs
hyperswitch_connectors::src::connectors::braintree
11,299
true
// File: crates/hyperswitch_connectors/src/connectors/noon.rs // Module: hyperswitch_connectors::src::connectors::noon pub mod transformers; use std::sync::LazyLock; use api_models::webhooks::{ConnectorWebhookSecrets, IncomingWebhookEvent, ObjectReferenceId}; use base64::Engine; use common_enums::enums; use common_utils::{ crypto, errors::CustomResult, ext_traits::ByteSliceExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{Report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, mandate_revoke::MandateRevoke, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{ MandateRevokeType, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response, }, webhooks, }; use masking::{Mask, PeekInterface}; use router_env::logger; use transformers as noon; use crate::{ constants::headers, types::ResponseRouterData, utils::{self as connector_utils, PaymentMethodDataType}, }; #[derive(Clone)] pub struct Noon { amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Noon { pub const fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, } } } impl api::Payment for Noon {} impl api::PaymentSession for Noon {} impl api::ConnectorAccessToken for Noon {} impl api::MandateSetup for Noon {} impl api::PaymentAuthorize for Noon {} impl api::PaymentSync for Noon {} impl api::PaymentCapture for Noon {} impl api::PaymentVoid for Noon {} impl api::Refund for Noon {} impl api::RefundExecute for Noon {} impl api::RefundSync for Noon {} impl api::PaymentToken for Noon {} impl api::ConnectorMandateRevoke for Noon {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Noon { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Noon where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), PaymentsAuthorizeType::get_content_type(self) .to_string() .into(), )]; let mut api_key = get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } fn get_auth_header( auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = noon::NoonAuthType::try_from(auth_type)?; let encoded_api_key = auth .business_identifier .zip(auth.application_identifier) .zip(auth.api_key) .map(|((business_identifier, application_identifier), api_key)| { common_utils::consts::BASE64_ENGINE.encode(format!( "{business_identifier}.{application_identifier}:{api_key}", )) }); Ok(vec![( headers::AUTHORIZATION.to_string(), format!("Key {}", encoded_api_key.peek()).into_masked(), )]) } impl ConnectorCommon for Noon { fn id(&self) -> &'static str { "noon" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.noon.base_url.as_ref() } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: Result<noon::NoonErrorResponse, Report<common_utils::errors::ParsingError>> = res.response.parse_struct("NoonErrorResponse"); match response { Ok(noon_error_response) => { event_builder.map(|i| i.set_error_response_body(&noon_error_response)); router_env::logger::info!(connector_response=?noon_error_response); // Adding in case of timeouts, if psync gives 4xx with this code, fail the payment let attempt_status = if noon_error_response.result_code == 19001 { Some(enums::AttemptStatus::Failure) } else { None }; Ok(ErrorResponse { status_code: res.status_code, code: noon_error_response.result_code.to_string(), message: noon_error_response.class_description, reason: Some(noon_error_response.message), attempt_status, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } Err(error_message) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); logger::error!(deserialization_error =? error_message); connector_utils::handle_json_response_deserialization_failure(res, "noon") } } } } impl ConnectorValidation for Noon { fn validate_connector_against_payment_request( &self, capture_method: Option<enums::CaptureMethod>, _payment_method: enums::PaymentMethod, _pmt: Option<enums::PaymentMethodType>, ) -> CustomResult<(), errors::ConnectorError> { let capture_method = capture_method.unwrap_or_default(); match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual | enums::CaptureMethod::SequentialAutomatic => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( connector_utils::construct_not_implemented_error_report(capture_method, self.id()), ), } } fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([ PaymentMethodDataType::Card, PaymentMethodDataType::ApplePay, PaymentMethodDataType::GooglePay, ]); connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } fn validate_psync_reference_id( &self, _data: &PaymentsSyncData, _is_three_ds: bool, _status: enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { // since we can make psync call with our reference_id, having connector_transaction_id is not an mandatory criteria Ok(()) } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Noon { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Noon {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Noon { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Noon".to_string()) .into(), ) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Noon { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}payment/v1/order", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let mandate_details = connector_utils::get_mandate_details(req.request.setup_mandate_details.clone())?; let mandate_amount = mandate_details .map(|mandate| { connector_utils::convert_amount( self.amount_converter, mandate.amount, mandate.currency, ) }) .transpose()?; let connector_router_data = noon::NoonRouterData::from((amount, req, mandate_amount)); let connector_req = noon::NoonPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: noon::NoonPaymentsResponse = res .response .parse_struct("Noon PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Noon { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}payment/v1/order/getbyreference/{}", self.base_url(connectors), req.connector_request_reference_id )) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: noon::NoonPaymentsResponse = res .response .parse_struct("noon PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Noon { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}payment/v1/order", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, )?; let connector_router_data = noon::NoonRouterData::from((amount, req, None)); let connector_req = noon::NoonPaymentsActionRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: noon::NoonPaymentsResponse = res .response .parse_struct("Noon PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Noon { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}payment/v1/order", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = noon::NoonPaymentsCancelRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: noon::NoonPaymentsResponse = res .response .parse_struct("Noon PaymentsCancelResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData> for Noon { fn get_headers( &self, req: &MandateRevokeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &MandateRevokeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}payment/v1/order", self.base_url(connectors))) } fn build_request( &self, req: &MandateRevokeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&MandateRevokeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(MandateRevokeType::get_headers(self, req, connectors)?) .set_body(MandateRevokeType::get_request_body(self, req, connectors)?) .build(), )) } fn get_request_body( &self, req: &MandateRevokeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = noon::NoonRevokeMandateRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn handle_response( &self, data: &MandateRevokeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<MandateRevokeRouterData, errors::ConnectorError> { let response: noon::NoonRevokeMandateResponse = res .response .parse_struct("Noon NoonRevokeMandateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Noon { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}payment/v1/order", self.base_url(connectors))) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = noon::NoonRouterData::from((refund_amount, req, None)); let connector_req = noon::NoonPaymentsActionRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundExecuteType::get_headers(self, req, connectors)?) .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: noon::RefundResponse = res .response .parse_struct("noon RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Noon { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}payment/v1/order/getbyreference/{}", self.base_url(connectors), req.connector_request_reference_id )) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: noon::RefundSyncResponse = res .response .parse_struct("noon RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::ConnectorRedirectResponse for Noon { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, action: enums::PaymentAction, ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> { match action { enums::PaymentAction::PSync | enums::PaymentAction::CompleteAuthorize | enums::PaymentAction::PaymentAuthenticateCompleteAuthorize => { Ok(enums::CallConnectorAction::Trigger) } } } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Noon { fn get_webhook_source_verification_algorithm( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha512)) } fn get_webhook_source_verification_signature( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let webhook_body: noon::NoonWebhookSignature = request .body .parse_struct("NoonWebhookSignature") .change_context(errors::ConnectorError::WebhookSignatureNotFound)?; let signature = webhook_body.signature; common_utils::consts::BASE64_ENGINE .decode(signature) .change_context(errors::ConnectorError::WebhookSignatureNotFound) } fn get_webhook_source_verification_message( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let webhook_body: noon::NoonWebhookBody = request .body .parse_struct("NoonWebhookBody") .change_context(errors::ConnectorError::WebhookSignatureNotFound)?; let message = format!( "{},{},{},{},{}", webhook_body.order_id, webhook_body.order_status, webhook_body.event_id, webhook_body.event_type, webhook_body.time_stamp, ); Ok(message.into_bytes()) } fn get_webhook_object_reference_id( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> { let details: noon::NoonWebhookOrderId = request .body .parse_struct("NoonWebhookOrderId") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( details.order_id.to_string(), ), )) } fn get_webhook_event_type( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { let details: noon::NoonWebhookEvent = request .body .parse_struct("NoonWebhookEvent") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; Ok(match &details.event_type { noon::NoonWebhookEventTypes::Sale | noon::NoonWebhookEventTypes::Capture => { match &details.order_status { noon::NoonPaymentStatus::Captured => IncomingWebhookEvent::PaymentIntentSuccess, _ => Err(errors::ConnectorError::WebhookEventTypeNotFound)?, } } noon::NoonWebhookEventTypes::Fail => IncomingWebhookEvent::PaymentIntentFailure, noon::NoonWebhookEventTypes::Authorize | noon::NoonWebhookEventTypes::Authenticate | noon::NoonWebhookEventTypes::Refund | noon::NoonWebhookEventTypes::Unknown => IncomingWebhookEvent::EventNotSupported, }) } fn get_webhook_resource_object( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let resource: noon::NoonWebhookObject = request .body .parse_struct("NoonWebhookObject") .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; Ok(Box::new(noon::NoonPaymentsResponse::from(resource))) } } static NOON_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, enums::CaptureMethod::SequentialAutomatic, ]; let supported_card_network = vec![ common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::JCB, common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::Visa, ]; let mut noon_supported_payment_methods = SupportedPaymentMethods::new(); noon_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); noon_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); noon_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); noon_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::GooglePay, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); noon_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::Paypal, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); noon_supported_payment_methods }); static NOON_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Noon", description: "Noon is a payment gateway and PSP enabling secure online transactions", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Live, }; static NOON_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; impl ConnectorSpecifications for Noon { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&NOON_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*NOON_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&NOON_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/noon.rs
hyperswitch_connectors::src::connectors::noon
7,834
true
// File: crates/hyperswitch_connectors/src/connectors/breadpay.rs // Module: hyperswitch_connectors::src::connectors::breadpay pub mod transformers; use std::sync::LazyLock; use base64::Engine; use common_enums::{enums, CallConnectorAction, PaymentAction}; use common_utils::{ consts::BASE64_ENGINE, errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, CompleteAuthorize, }, router_request_types::{ AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use masking::{ExposeInterface, Mask, Maskable, PeekInterface}; use transformers::{ self as breadpay, BreadpayTransactionRequest, BreadpayTransactionResponse, BreadpayTransactionType, }; use crate::{ connectors::breadpay::transformers::CallBackResponse, constants::headers, types::ResponseRouterData, utils::{self, PaymentsCompleteAuthorizeRequestData}, }; #[derive(Clone)] pub struct Breadpay { amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), } impl Breadpay { pub fn new() -> &'static Self { &Self { amount_converter: &StringMinorUnitForConnector, } } } impl api::Payment for Breadpay {} impl api::PaymentSession for Breadpay {} impl api::PaymentsCompleteAuthorize for Breadpay {} impl api::ConnectorAccessToken for Breadpay {} impl api::MandateSetup for Breadpay {} impl api::PaymentAuthorize for Breadpay {} impl api::PaymentSync for Breadpay {} impl api::PaymentCapture for Breadpay {} impl api::PaymentVoid for Breadpay {} impl api::Refund for Breadpay {} impl api::RefundExecute for Breadpay {} impl api::RefundSync for Breadpay {} impl api::PaymentToken for Breadpay {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Breadpay { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Breadpay where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Breadpay { fn id(&self) -> &'static str { "breadpay" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor // TODO! Check connector documentation, on which unit they are processing the currency. // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.breadpay.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let auth = breadpay::BreadpayAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let encoded_api_key = BASE64_ENGINE.encode(format!( "{}:{}", auth.api_key.peek(), auth.api_secret.peek() )); Ok(vec![( headers::AUTHORIZATION.to_string(), format!("Basic {encoded_api_key}").into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: breadpay::BreadpayErrorResponse = res .response .parse_struct("BreadpayErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.error_type.clone(), message: response.description.clone(), reason: Some(response.description), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Breadpay {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Breadpay { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Breadpay {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Breadpay { } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Breadpay { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "/carts")) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = breadpay::BreadpayRouterData::from((amount, req)); let connector_req = breadpay::BreadpayCartRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: breadpay::BreadpayPaymentsResponse = res .response .parse_struct("Breadpay BreadpayPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> for Breadpay { fn get_headers( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_request_body( &self, req: &PaymentsCompleteAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let transaction_type = if req.request.is_auto_capture()? { BreadpayTransactionType::Settle } else { BreadpayTransactionType::Authorize }; let connector_req = BreadpayTransactionRequest { transaction_type }; Ok(RequestContent::Json(Box::new(connector_req))) } fn get_url( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let redirect_response = req.request.redirect_response.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "redirect_response", }, )?; let redirect_payload = redirect_response .payload .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.payload", })? .expose(); let call_back_response: CallBackResponse = serde_json::from_value::<CallBackResponse>( redirect_payload.clone(), ) .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "redirection_payload", })?; Ok(format!( "{}{}{}", self.base_url(connectors), "/transactions/actions", call_back_response.transaction_id )) } fn build_request( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCompleteAuthorizeType::get_url( self, req, connectors, )?) .headers(types::PaymentsCompleteAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCompleteAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: BreadpayTransactionResponse = res .response .parse_struct("BreadpayTransactionResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Breadpay { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}{}", self.base_url(connectors), "/transactions", req.request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)? )) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: BreadpayTransactionResponse = res .response .parse_struct("BreadpayTransactionResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Breadpay { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}{}", self.base_url(connectors), "/transactions/actions", req.request.connector_transaction_id )) } fn get_request_body( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = BreadpayTransactionRequest { transaction_type: BreadpayTransactionType::Settle, }; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: BreadpayTransactionResponse = res .response .parse_struct("BreadpayTransactionResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Breadpay { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}{}", self.base_url(connectors), "/transactions/actions", req.request.connector_transaction_id )) } fn get_request_body( &self, _req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = BreadpayTransactionRequest { transaction_type: BreadpayTransactionType::Cancel, }; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(types::PaymentsVoidType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: BreadpayTransactionResponse = res .response .parse_struct("BreadpayTransactionResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Breadpay { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = breadpay::BreadpayRouterData::from((refund_amount, req)); let connector_req = breadpay::BreadpayRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: breadpay::RefundResponse = res .response .parse_struct("breadpay RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Breadpay { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .set_body(types::RefundSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: breadpay::RefundResponse = res .response .parse_struct("breadpay RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Breadpay { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } static BREADPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, enums::CaptureMethod::SequentialAutomatic, ]; let mut breadpay_supported_payment_methods = SupportedPaymentMethods::new(); breadpay_supported_payment_methods.add( enums::PaymentMethod::PayLater, enums::PaymentMethodType::Breadpay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods, specific_features: None, }, ); breadpay_supported_payment_methods }); static BREADPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Breadpay", description: "Breadpay connector", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Alpha, }; static BREADPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Breadpay { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&BREADPAY_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*BREADPAY_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&BREADPAY_SUPPORTED_WEBHOOK_FLOWS) } } impl ConnectorRedirectResponse for Breadpay { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, action: PaymentAction, ) -> CustomResult<CallConnectorAction, errors::ConnectorError> { match action { PaymentAction::PSync | PaymentAction::CompleteAuthorize | PaymentAction::PaymentAuthenticateCompleteAuthorize => { Ok(CallConnectorAction::Trigger) } } } }
crates/hyperswitch_connectors/src/connectors/breadpay.rs
hyperswitch_connectors::src::connectors::breadpay
6,280
true
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs // Module: hyperswitch_connectors::src::connectors::worldpayvantiv pub mod transformers; use std::sync::LazyLock; use base64::Engine; use common_utils::{ consts::BASE64_ENGINE, errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{ Authorize, Capture, PSync, PaymentMethodToken, PostCaptureVoid, Session, SetupMandate, Void, }, refunds::{Execute, RSync}, Accept, Dsync, Evidence, Fetch, Retrieve, Upload, }, router_request_types::{ AcceptDisputeRequestData, AccessTokenRequestData, DisputeSyncData, FetchDisputesRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, RetrieveFileRequestData, SetupMandateRequestData, SubmitEvidenceRequestData, UploadFileRequestData, }, router_response_types::{ AcceptDisputeResponse, ConnectorInfo, DisputeSyncResponse, FetchDisputesResponse, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, SupportedPaymentMethods, SupportedPaymentMethodsExt, UploadFileResponse, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelPostCaptureRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, disputes::{AcceptDispute, Dispute, DisputeSync, FetchDisputes, SubmitEvidence}, files::{FilePurpose, FileUpload, RetrieveFile, UploadFile}, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, consts::NO_ERROR_CODE, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use masking::{Mask, PeekInterface}; use transformers as worldpayvantiv; use crate::{ constants::headers, types::{ AcceptDisputeRouterData, DisputeSyncRouterData, FetchDisputeRouterData, ResponseRouterData, RetrieveFileRouterData, SubmitEvidenceRouterData, UploadFileRouterData, }, utils as connector_utils, }; #[derive(Clone)] pub struct Worldpayvantiv { amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Worldpayvantiv { pub fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } } impl api::Payment for Worldpayvantiv {} impl api::PaymentSession for Worldpayvantiv {} impl api::ConnectorAccessToken for Worldpayvantiv {} impl api::MandateSetup for Worldpayvantiv {} impl api::PaymentAuthorize for Worldpayvantiv {} impl api::PaymentSync for Worldpayvantiv {} impl api::PaymentCapture for Worldpayvantiv {} impl api::PaymentVoid for Worldpayvantiv {} impl api::Refund for Worldpayvantiv {} impl api::RefundExecute for Worldpayvantiv {} impl api::RefundSync for Worldpayvantiv {} impl api::PaymentToken for Worldpayvantiv {} impl api::PaymentPostCaptureVoid for Worldpayvantiv {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Worldpayvantiv { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Worldpayvantiv where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, _req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; Ok(header) } } impl ConnectorCommon for Worldpayvantiv { fn id(&self) -> &'static str { "worldpayvantiv" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "text/xml" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.worldpayvantiv.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = worldpayvantiv::WorldpayvantivAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let auth_key = format!("{}:{}", auth.user.peek(), auth.password.peek()); let auth_header = format!("Basic {}", BASE64_ENGINE.encode(auth_key)); Ok(vec![( headers::AUTHORIZATION.to_string(), auth_header.into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: Result<worldpayvantiv::CnpOnlineResponse, _> = connector_utils::deserialize_xml_to_struct(&res.response); match response { Ok(response_data) => { event_builder.map(|i| i.set_response_body(&response_data)); router_env::logger::info!(connector_response=?response_data); Ok(ErrorResponse { status_code: res.status_code, code: response_data.response_code, message: response_data.message.clone(), reason: Some(response_data.message.clone()), attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }) } Err(error_msg) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); router_env::logger::error!(deserialization_error =? error_msg); connector_utils::handle_json_response_deserialization_failure(res, "worldpayvantiv") } } } } impl ConnectorValidation for Worldpayvantiv { fn validate_mandate_payment( &self, pm_type: Option<api_models::enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([ connector_utils::PaymentMethodDataType::Card, connector_utils::PaymentMethodDataType::ApplePay, connector_utils::PaymentMethodDataType::GooglePay, ]); connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Worldpayvantiv { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Worldpayvantiv {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Worldpayvantiv { fn get_headers( &self, req: &SetupMandateRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &SetupMandateRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_owned()) } fn get_request_body( &self, req: &SetupMandateRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req_object = worldpayvantiv::CnpOnlineRequest::try_from(req)?; router_env::logger::info!(raw_connector_request=?connector_req_object); let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes( &connector_req_object, worldpayvantiv::worldpayvantiv_constants::XML_VERSION, Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING), None, None, )?; Ok(RequestContent::RawBytes(connector_req)) } fn build_request( &self, req: &SetupMandateRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::SetupMandateType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::SetupMandateType::get_headers(self, req, connectors)?) .set_body(types::SetupMandateType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &SetupMandateRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> { let response: worldpayvantiv::CnpOnlineResponse = connector_utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Worldpayvantiv { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_owned()) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = worldpayvantiv::WorldpayvantivRouterData::from((amount, req)); let connector_req_object = worldpayvantiv::CnpOnlineRequest::try_from(&connector_router_data)?; router_env::logger::info!(raw_connector_request=?connector_req_object); let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes( &connector_req_object, worldpayvantiv::worldpayvantiv_constants::XML_VERSION, Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING), None, None, )?; Ok(RequestContent::RawBytes(connector_req)) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { // For certification purposes, to be removed later router_env::logger::info!(raw_connector_response=?res.response); let response: worldpayvantiv::CnpOnlineResponse = connector_utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Worldpayvantiv { fn get_headers( &self, req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.get_auth_header(&req.connector_auth_type) } fn get_content_type(&self) -> &'static str { "application/json" } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/reports/dtrPaymentStatus/{}", connectors.worldpayvantiv.secondary_base_url.to_owned(), req.request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)? )) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: worldpayvantiv::VantivSyncResponse = res .response .parse_struct("VantivSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { handle_vantiv_json_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Worldpayvantiv { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_owned()) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, )?; let connector_router_data = worldpayvantiv::WorldpayvantivRouterData::from((amount, req)); let connector_req_object = worldpayvantiv::CnpOnlineRequest::try_from(&connector_router_data)?; router_env::logger::info!(raw_connector_request=?connector_req_object); let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes( &connector_req_object, worldpayvantiv::worldpayvantiv_constants::XML_VERSION, Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING), None, None, )?; Ok(RequestContent::RawBytes(connector_req)) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: worldpayvantiv::CnpOnlineResponse = connector_utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Worldpayvantiv { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_owned()) } fn get_request_body( &self, req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req_object = worldpayvantiv::CnpOnlineRequest::try_from(req)?; router_env::logger::info!(raw_connector_request=?connector_req_object); let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes( &connector_req_object, worldpayvantiv::worldpayvantiv_constants::XML_VERSION, Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING), None, None, )?; Ok(RequestContent::RawBytes(connector_req)) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(types::PaymentsVoidType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: worldpayvantiv::CnpOnlineResponse = connector_utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData> for Worldpayvantiv { fn get_headers( &self, req: &PaymentsCancelPostCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCancelPostCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_owned()) } fn get_request_body( &self, req: &PaymentsCancelPostCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req_object = worldpayvantiv::CnpOnlineRequest::try_from(req)?; router_env::logger::info!(raw_connector_request=?connector_req_object); let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes( &connector_req_object, worldpayvantiv::worldpayvantiv_constants::XML_VERSION, Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING), None, None, )?; Ok(RequestContent::RawBytes(connector_req)) } fn build_request( &self, req: &PaymentsCancelPostCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsPostCaptureVoidType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsPostCaptureVoidType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsPostCaptureVoidType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCancelPostCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelPostCaptureRouterData, errors::ConnectorError> { let response: worldpayvantiv::CnpOnlineResponse = connector_utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Worldpayvantiv { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(self.base_url(connectors).to_owned()) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = worldpayvantiv::WorldpayvantivRouterData::from((refund_amount, req)); let connector_req_object = worldpayvantiv::CnpOnlineRequest::try_from(&connector_router_data)?; router_env::logger::info!(connector_request=?connector_req_object); let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes( &connector_req_object, worldpayvantiv::worldpayvantiv_constants::XML_VERSION, Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING), None, None, )?; Ok(RequestContent::RawBytes(connector_req)) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: worldpayvantiv::CnpOnlineResponse = connector_utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Worldpayvantiv { fn get_headers( &self, req: &RefundSyncRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.get_auth_header(&req.connector_auth_type) } fn get_content_type(&self) -> &'static str { "application/json" } fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/reports/dtrPaymentStatus/{}", connectors.worldpayvantiv.secondary_base_url.to_owned(), req.request.connector_transaction_id )) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: worldpayvantiv::VantivSyncResponse = res .response .parse_struct("VantivSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { handle_vantiv_json_error_response(res, event_builder) } } impl Dispute for Worldpayvantiv {} impl FetchDisputes for Worldpayvantiv {} impl DisputeSync for Worldpayvantiv {} impl SubmitEvidence for Worldpayvantiv {} impl AcceptDispute for Worldpayvantiv {} impl ConnectorIntegration<Fetch, FetchDisputesRequestData, FetchDisputesResponse> for Worldpayvantiv { fn get_headers( &self, req: &FetchDisputeRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut headers = vec![ ( headers::CONTENT_TYPE.to_string(), types::FetchDisputesType::get_content_type(self) .to_string() .into(), ), ( headers::ACCEPT.to_string(), types::FetchDisputesType::get_content_type(self) .to_string() .into(), ), ]; let mut auth_header = self.get_auth_header(&req.connector_auth_type)?; headers.append(&mut auth_header); Ok(headers) } fn get_content_type(&self) -> &'static str { "application/com.vantivcnp.services-v2+xml" } fn get_url( &self, req: &FetchDisputeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let date = req.request.created_from.date(); let day = date.day(); let month = u8::from(date.month()); let year = date.year(); Ok(format!( "{}/services/chargebacks/?date={year}-{month}-{day}", connectors.worldpayvantiv.third_base_url.to_owned() )) } fn build_request( &self, req: &FetchDisputeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Get) .url(&types::FetchDisputesType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::FetchDisputesType::get_headers( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &FetchDisputeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<FetchDisputeRouterData, errors::ConnectorError> { let response: worldpayvantiv::ChargebackRetrievalResponse = connector_utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { handle_vantiv_dispute_error_response(res, event_builder) } } impl ConnectorIntegration<Dsync, DisputeSyncData, DisputeSyncResponse> for Worldpayvantiv { fn get_headers( &self, req: &DisputeSyncRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut headers = vec![ ( headers::CONTENT_TYPE.to_string(), types::FetchDisputesType::get_content_type(self) .to_string() .into(), ), ( headers::ACCEPT.to_string(), types::FetchDisputesType::get_content_type(self) .to_string() .into(), ), ]; let mut auth_header = self.get_auth_header(&req.connector_auth_type)?; headers.append(&mut auth_header); Ok(headers) } fn get_url( &self, req: &DisputeSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/services/chargebacks/{}", connectors.worldpayvantiv.third_base_url.to_owned(), req.request.connector_dispute_id )) } fn build_request( &self, req: &DisputeSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Get) .url(&types::DisputeSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::DisputeSyncType::get_headers(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &DisputeSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<DisputeSyncRouterData, errors::ConnectorError> { let response: worldpayvantiv::ChargebackRetrievalResponse = connector_utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { handle_vantiv_dispute_error_response(res, event_builder) } } impl ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse> for Worldpayvantiv { fn get_headers( &self, req: &SubmitEvidenceRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut headers = vec![ ( headers::CONTENT_TYPE.to_string(), types::FetchDisputesType::get_content_type(self) .to_string() .into(), ), ( headers::ACCEPT.to_string(), types::FetchDisputesType::get_content_type(self) .to_string() .into(), ), ]; let mut auth_header = self.get_auth_header(&req.connector_auth_type)?; headers.append(&mut auth_header); Ok(headers) } fn get_url( &self, req: &SubmitEvidenceRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/services/chargebacks/{}", connectors.worldpayvantiv.third_base_url.to_owned(), req.request.connector_dispute_id )) } fn get_request_body( &self, req: &SubmitEvidenceRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req_object = worldpayvantiv::ChargebackUpdateRequest::from(req); router_env::logger::info!(raw_connector_request=?connector_req_object); let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes( &connector_req_object, worldpayvantiv::worldpayvantiv_constants::XML_VERSION, Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING), None, None, )?; Ok(RequestContent::RawBytes(connector_req)) } fn build_request( &self, req: &SubmitEvidenceRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Put) .url(&types::SubmitEvidenceType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::SubmitEvidenceType::get_headers( self, req, connectors, )?) .set_body(types::SubmitEvidenceType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &SubmitEvidenceRouterData, _event_builder: Option<&mut ConnectorEvent>, _res: Response, ) -> CustomResult<SubmitEvidenceRouterData, errors::ConnectorError> { Ok(SubmitEvidenceRouterData { response: Ok(SubmitEvidenceResponse { dispute_status: data.request.dispute_status, connector_status: None, }), ..data.clone() }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { handle_vantiv_dispute_error_response(res, event_builder) } } impl ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse> for Worldpayvantiv { fn get_headers( &self, req: &AcceptDisputeRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut headers = vec![ ( headers::CONTENT_TYPE.to_string(), types::FetchDisputesType::get_content_type(self) .to_string() .into(), ), ( headers::ACCEPT.to_string(), types::FetchDisputesType::get_content_type(self) .to_string() .into(), ), ]; let mut auth_header = self.get_auth_header(&req.connector_auth_type)?; headers.append(&mut auth_header); Ok(headers) } fn get_url( &self, req: &AcceptDisputeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/services/chargebacks/{}", connectors.worldpayvantiv.third_base_url.to_owned(), req.request.connector_dispute_id )) } fn get_request_body( &self, req: &AcceptDisputeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req_object = worldpayvantiv::ChargebackUpdateRequest::from(req); router_env::logger::info!(raw_connector_request=?connector_req_object); let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes( &connector_req_object, worldpayvantiv::worldpayvantiv_constants::XML_VERSION, Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING), Some(worldpayvantiv::worldpayvantiv_constants::XML_STANDALONE), None, )?; Ok(RequestContent::RawBytes(connector_req)) } fn build_request( &self, req: &AcceptDisputeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Put) .url(&types::AcceptDisputeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::AcceptDisputeType::get_headers( self, req, connectors, )?) .set_body(types::AcceptDisputeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &AcceptDisputeRouterData, _event_builder: Option<&mut ConnectorEvent>, _res: Response, ) -> CustomResult<AcceptDisputeRouterData, errors::ConnectorError> { Ok(AcceptDisputeRouterData { response: Ok(AcceptDisputeResponse { dispute_status: data.request.dispute_status, connector_status: None, }), ..data.clone() }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { handle_vantiv_dispute_error_response(res, event_builder) } } impl UploadFile for Worldpayvantiv {} impl ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse> for Worldpayvantiv { fn get_headers( &self, req: &RouterData<Upload, UploadFileRequestData, UploadFileResponse>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut headers = vec![( headers::CONTENT_TYPE.to_string(), req.request.file_type.to_string().into(), )]; let mut auth_header = self.get_auth_header(&req.connector_auth_type)?; headers.append(&mut auth_header); Ok(headers) } fn get_url( &self, req: &UploadFileRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let file_type = if req.request.file_type == mime::IMAGE_GIF { "gif" } else if req.request.file_type == mime::IMAGE_JPEG { "jpeg" } else if req.request.file_type == mime::IMAGE_PNG { "png" } else if req.request.file_type == mime::APPLICATION_PDF { "pdf" } else { return Err(errors::ConnectorError::FileValidationFailed { reason: "file_type does not match JPEG, JPG, PNG, or PDF format".to_owned(), })?; }; let file_name = req.request.file_key.split('/').next_back().ok_or( errors::ConnectorError::RequestEncodingFailedWithReason( "Failed fetching file_id from file_key".to_string(), ), )?; Ok(format!( "{}/services/chargebacks/upload/{}/{file_name}.{file_type}", connectors.worldpayvantiv.third_base_url.to_owned(), req.request.connector_dispute_id, )) } fn get_request_body( &self, req: &UploadFileRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { Ok(RequestContent::RawBytes(req.request.file.clone())) } fn build_request( &self, req: &UploadFileRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::UploadFileType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::UploadFileType::get_headers(self, req, connectors)?) .set_body(types::UploadFileType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &UploadFileRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< RouterData<Upload, UploadFileRequestData, UploadFileResponse>, errors::ConnectorError, > { let response: worldpayvantiv::ChargebackDocumentUploadResponse = connector_utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { handle_vantiv_dispute_error_response(res, event_builder) } } impl RetrieveFile for Worldpayvantiv {} impl ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse> for Worldpayvantiv { fn get_headers( &self, req: &RouterData<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.get_auth_header(&req.connector_auth_type) } fn get_url( &self, req: &RetrieveFileRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_dispute_id = req.request.connector_dispute_id.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "dispute_id", }, )?; Ok(format!( "{}/services/chargebacks/retrieve/{connector_dispute_id}/{}", connectors.worldpayvantiv.third_base_url.to_owned(), req.request.provider_file_id, )) } fn build_request( &self, req: &RetrieveFileRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RetrieveFileType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RetrieveFileType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RetrieveFileRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RetrieveFileRouterData, errors::ConnectorError> { let response: Result<worldpayvantiv::ChargebackDocumentUploadResponse, _> = connector_utils::deserialize_xml_to_struct(&res.response); match response { Ok(response) => { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } Err(_) => { event_builder.map(|event| event.set_response_body(&serde_json::json!({"connector_response_type": "file", "status_code": res.status_code}))); router_env::logger::info!(connector_response_type=?"file"); let response = res.response; Ok(RetrieveFileRouterData { response: Ok(RetrieveFileResponse { file_data: response.to_vec(), }), ..data.clone() }) } } } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { handle_vantiv_dispute_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Worldpayvantiv { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } fn handle_vantiv_json_error_response( res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: Result<worldpayvantiv::VantivSyncErrorResponse, _> = res .response .parse_struct("VantivSyncErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed); match response { Ok(response_data) => { event_builder.map(|i| i.set_response_body(&response_data)); router_env::logger::info!(connector_response=?response_data); let error_reason = response_data.error_messages.join(" & "); Ok(ErrorResponse { status_code: res.status_code, code: NO_ERROR_CODE.to_string(), message: error_reason.clone(), reason: Some(error_reason.clone()), attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }) } Err(error_msg) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); router_env::logger::error!(deserialization_error =? error_msg); connector_utils::handle_json_response_deserialization_failure(res, "worldpayvantiv") } } } fn handle_vantiv_dispute_error_response( res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: Result<worldpayvantiv::VantivDisputeErrorResponse, _> = connector_utils::deserialize_xml_to_struct::<worldpayvantiv::VantivDisputeErrorResponse>( &res.response, ); match response { Ok(response_data) => { event_builder.map(|i| i.set_response_body(&response_data)); router_env::logger::info!(connector_response=?response_data); let error_reason = response_data .errors .iter() .map(|error_info| error_info.error.clone()) .collect::<Vec<String>>() .join(" & "); Ok(ErrorResponse { status_code: res.status_code, code: NO_ERROR_CODE.to_string(), message: error_reason.clone(), reason: Some(error_reason.clone()), attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }) } Err(error_msg) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); router_env::logger::error!(deserialization_error =? error_msg); connector_utils::handle_json_response_deserialization_failure(res, "worldpayvantiv") } } } #[async_trait::async_trait] impl FileUpload for Worldpayvantiv { fn validate_file_upload( &self, purpose: FilePurpose, file_size: i32, file_type: mime::Mime, ) -> CustomResult<(), errors::ConnectorError> { match purpose { FilePurpose::DisputeEvidence => { let supported_file_types = [ "image/gif", "image/jpeg", "image/jpg", "application/pdf", "image/png", "image/tiff", ]; if file_size > 2000000 { Err(errors::ConnectorError::FileValidationFailed { reason: "file_size exceeded the max file size of 2MB".to_owned(), })? } if !supported_file_types.contains(&file_type.to_string().as_str()) { Err(errors::ConnectorError::FileValidationFailed { reason: "file_type does not match JPEG, JPG, PNG, or PDF format".to_owned(), })? } } } Ok(()) } } static WORLDPAYVANTIV_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ common_enums::CaptureMethod::Automatic, common_enums::CaptureMethod::Manual, common_enums::CaptureMethod::SequentialAutomatic, ]; let supported_card_network = vec![ common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::DinersClub, common_enums::CardNetwork::JCB, common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::Visa, common_enums::CardNetwork::Discover, ]; let mut worldpayvantiv_supported_payment_methods = SupportedPaymentMethods::new(); worldpayvantiv_supported_payment_methods.add( common_enums::PaymentMethod::Card, common_enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: common_enums::FeatureStatus::Supported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::NotSupported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); worldpayvantiv_supported_payment_methods.add( common_enums::PaymentMethod::Card, common_enums::PaymentMethodType::Debit, PaymentMethodDetails { mandates: common_enums::FeatureStatus::Supported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::NotSupported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); #[cfg(feature = "v2")] worldpayvantiv_supported_payment_methods.add( common_enums::PaymentMethod::Card, common_enums::PaymentMethodType::Card, PaymentMethodDetails { mandates: common_enums::FeatureStatus::Supported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::NotSupported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); worldpayvantiv_supported_payment_methods.add( common_enums::PaymentMethod::Wallet, common_enums::PaymentMethodType::ApplePay, PaymentMethodDetails { mandates: common_enums::FeatureStatus::Supported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); worldpayvantiv_supported_payment_methods.add( common_enums::PaymentMethod::Wallet, common_enums::PaymentMethodType::GooglePay, PaymentMethodDetails { mandates: common_enums::FeatureStatus::Supported, refunds: common_enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); worldpayvantiv_supported_payment_methods }); static WORLDPAYVANTIV_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Worldpay Vantiv", description: "Worldpay Vantiv, also known as the Worldpay CNP API, is a robust XML-based interface used to process online (card-not-present) transactions such as e-commerce purchases, subscription billing, and digital payments", connector_type: common_enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: common_enums::ConnectorIntegrationStatus::Sandbox, }; static WORLDPAYVANTIV_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 0] = []; impl ConnectorSpecifications for Worldpayvantiv { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&WORLDPAYVANTIV_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*WORLDPAYVANTIV_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::EventClass]> { Some(&WORLDPAYVANTIV_SUPPORTED_WEBHOOK_FLOWS) } #[cfg(feature = "v1")] fn generate_connector_request_reference_id( &self, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, is_config_enabled_to_send_payment_id_as_connector_request_id: bool, ) -> String { if is_config_enabled_to_send_payment_id_as_connector_request_id && payment_intent.is_payment_id_from_merchant.unwrap_or(false) { payment_attempt.payment_id.get_string_repr().to_owned() } else { let max_payment_reference_id_length = worldpayvantiv::worldpayvantiv_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH; nanoid::nanoid!(max_payment_reference_id_length) } } #[cfg(feature = "v2")] fn generate_connector_request_reference_id( &self, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> String { if payment_intent.is_payment_id_from_merchant.unwrap_or(false) { payment_attempt.payment_id.get_string_repr().to_owned() } else { connector_utils::generate_12_digit_number().to_string() } } }
crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
hyperswitch_connectors::src::connectors::worldpayvantiv
13,289
true
// File: crates/hyperswitch_connectors/src/connectors/thunes.rs // Module: hyperswitch_connectors::src::connectors::thunes pub mod transformers; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use masking::{ExposeInterface, Mask}; use transformers as thunes; use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Thunes { amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), } impl Thunes { pub fn new() -> &'static Self { &Self { amount_converter: &StringMinorUnitForConnector, } } } impl api::Payment for Thunes {} impl api::PaymentSession for Thunes {} impl api::ConnectorAccessToken for Thunes {} impl api::MandateSetup for Thunes {} impl api::PaymentAuthorize for Thunes {} impl api::PaymentSync for Thunes {} impl api::PaymentCapture for Thunes {} impl api::PaymentVoid for Thunes {} impl api::Refund for Thunes {} impl api::RefundExecute for Thunes {} impl api::RefundSync for Thunes {} impl api::PaymentToken for Thunes {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Thunes { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Thunes where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Thunes { fn id(&self) -> &'static str { "thunes" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base // TODO! Check connector documentation, on which unit they are processing the currency. // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.thunes.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = thunes::ThunesAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.expose().into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: thunes::ThunesErrorResponse = res .response .parse_struct("ThunesErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.code, message: response.message, reason: response.reason, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Thunes { //TODO: implement functions when support enabled } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Thunes { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Thunes {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Thunes {} impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Thunes { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = thunes::ThunesRouterData::from((amount, req)); let connector_req = thunes::ThunesPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: thunes::ThunesPaymentsResponse = res .response .parse_struct("Thunes PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Thunes { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: thunes::ThunesPaymentsResponse = res .response .parse_struct("thunes PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Thunes { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: thunes::ThunesPaymentsResponse = res .response .parse_struct("Thunes PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Thunes {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Thunes { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = thunes::ThunesRouterData::from((refund_amount, req)); let connector_req = thunes::ThunesRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: thunes::RefundResponse = res.response .parse_struct("thunes RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Thunes { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .set_body(types::RefundSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: thunes::RefundResponse = res .response .parse_struct("thunes RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Thunes { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } static THUNES_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Thunes", description: "Thunes Payouts is a global payment solution that enables businesses to send instant, secure, and cost-effective cross-border payments to bank accounts, mobile wallets, and cards in over 130 countries using a single API", connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor, integration_status: common_enums::ConnectorIntegrationStatus::Sandbox, }; impl ConnectorSpecifications for Thunes { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&THUNES_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { None } fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> { None } }
crates/hyperswitch_connectors/src/connectors/thunes.rs
hyperswitch_connectors::src::connectors::thunes
4,512
true
// File: crates/hyperswitch_connectors/src/connectors/paysafe.rs // Module: hyperswitch_connectors::src::connectors::paysafe pub mod transformers; use std::sync::LazyLock; use base64::Engine; use common_enums::enums; use common_utils::{ consts, errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{ Authorize, Capture, CompleteAuthorize, CreateConnectorCustomer, PSync, PaymentMethodToken, PreProcessing, Session, SetupMandate, Void, }, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, CompleteAuthorizeData, ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use masking::{Mask, PeekInterface}; use transformers as paysafe; use crate::{ constants::headers, types::ResponseRouterData, utils::{ self, PaymentMethodDataType, PaymentsAuthorizeRequestData, PaymentsPreProcessingRequestData, PaymentsSyncRequestData, RefundsRequestData as OtherRefundsRequestData, RouterData as _, }, }; #[derive(Clone)] pub struct Paysafe { amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Paysafe { pub fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } } impl api::Payment for Paysafe {} impl api::PaymentSession for Paysafe {} impl api::ConnectorAccessToken for Paysafe {} impl api::MandateSetup for Paysafe {} impl api::PaymentAuthorize for Paysafe {} impl api::PaymentSync for Paysafe {} impl api::PaymentCapture for Paysafe {} impl api::PaymentVoid for Paysafe {} impl api::Refund for Paysafe {} impl api::RefundExecute for Paysafe {} impl api::RefundSync for Paysafe {} impl api::PaymentToken for Paysafe {} impl api::ConnectorCustomer for Paysafe {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Paysafe { } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paysafe where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Paysafe { fn id(&self) -> &'static str { "paysafe" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.paysafe.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = paysafe::PaysafeAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let auth_key = format!("{}:{}", auth.username.peek(), auth.password.peek()); let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key)); Ok(vec![( headers::AUTHORIZATION.to_string(), auth_header.into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: paysafe::PaysafeErrorResponse = res .response .parse_struct("PaysafeErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let detail_message = response .error .details .as_ref() .and_then(|d| d.first().cloned()); let field_error_message = response .error .field_errors .as_ref() .and_then(|f| f.first().map(|fe| fe.error.clone())); let reason = match (detail_message, field_error_message) { (Some(detail), Some(field)) => Some(format!("{detail}, {field}")), (Some(detail), None) => Some(detail), (None, Some(field)) => Some(field), (None, None) => Some(response.error.message.clone()), }; Ok(ErrorResponse { status_code: res.status_code, code: response.error.code, message: response.error.message, reason, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Paysafe { fn validate_psync_reference_id( &self, _data: &PaymentsSyncData, _is_three_ds: bool, _status: enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { Ok(()) } fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]); utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paysafe { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paysafe {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Paysafe { // Not Implemented (R) fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Paysafe".to_string()) .into(), ) } } impl api::PaymentsPreProcessing for Paysafe {} impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> for Paysafe { fn get_headers( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let base_url = self.base_url(connectors); if req.request.is_customer_initiated_mandate_payment() { let customer_id = req.get_connector_customer_id()?.to_string(); Ok(format!( "{base_url}v1/customers/{customer_id}/paymenthandles" )) } else { Ok(format!("{}v1/paymenthandles", self.base_url(connectors))) } } fn get_request_body( &self, req: &PaymentsPreProcessingRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let minor_amount = req.request .minor_amount .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "minor_amount", })?; let currency = req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?; let amount = utils::convert_amount(self.amount_converter, minor_amount, currency)?; let connector_router_data = paysafe::PaysafeRouterData::from((amount, req)); let connector_req = paysafe::PaysafePaymentHandleRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsPreProcessingType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsPreProcessingType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsPreProcessingType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsPreProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: paysafe::PaysafePaymentHandleResponse = res .response .parse_struct("PaysafePaymentHandleResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> for Paysafe { fn get_headers( &self, req: &ConnectorCustomerRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &ConnectorCustomerRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v1/customers", self.base_url(connectors))) } fn get_request_body( &self, req: &ConnectorCustomerRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = paysafe::PaysafeCustomerDetails::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &ConnectorCustomerRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::ConnectorCustomerType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::ConnectorCustomerType::get_headers( self, req, connectors, )?) .set_body(types::ConnectorCustomerType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &ConnectorCustomerRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<ConnectorCustomerRouterData, errors::ConnectorError> where PaymentsResponseData: Clone, { let response: paysafe::PaysafeCustomerResponse = res .response .parse_struct("Paysafe PaysafeCustomerResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paysafe { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { match req.payment_method { enums::PaymentMethod::Card if !req.is_three_ds() => { Ok(format!("{}v1/payments", self.base_url(connectors))) } enums::PaymentMethod::Wallet if req.request.payment_method_type == Some(enums::PaymentMethodType::ApplePay) => { Ok(format!("{}v1/payments", self.base_url(connectors))) } _ => Ok(format!("{}v1/paymenthandles", self.base_url(connectors),)), } } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = paysafe::PaysafeRouterData::from((amount, req)); match req.payment_method { //Card No 3DS enums::PaymentMethod::Card if !req.is_three_ds() || req.request.get_connector_mandate_id().is_ok() => { let connector_req = paysafe::PaysafePaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } enums::PaymentMethod::Wallet if req.request.payment_method_type == Some(enums::PaymentMethodType::ApplePay) => { let connector_req = paysafe::PaysafePaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } _ => { let connector_req = paysafe::PaysafePaymentHandleRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } } } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { match data.payment_method { enums::PaymentMethod::Card if !data.is_three_ds() => { let response: paysafe::PaysafePaymentsResponse = res .response .parse_struct("Paysafe PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } enums::PaymentMethod::Wallet if data.request.payment_method_type == Some(enums::PaymentMethodType::ApplePay) => { let response: paysafe::PaysafePaymentsResponse = res .response .parse_struct("Paysafe PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } _ => { let response: paysafe::PaysafePaymentHandleResponse = res .response .parse_struct("Paysafe PaymentHandleResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } } } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::PaymentsCompleteAuthorize for Paysafe {} impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> for Paysafe { fn get_headers( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v1/payments", self.base_url(connectors),)) } fn get_request_body( &self, req: &PaymentsCompleteAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = paysafe::PaysafeRouterData::from((amount, req)); let connector_req = paysafe::PaysafePaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCompleteAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsCompleteAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCompleteAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: paysafe::PaysafePaymentsResponse = res .response .parse_struct("Paysafe PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Paysafe { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.connector_request_reference_id.clone(); let connector_transaction_id = req.request.get_optional_connector_transaction_id(); let base_url = self.base_url(connectors); let url = if connector_transaction_id.is_some() { format!("{base_url}v1/payments?merchantRefNum={connector_payment_id}") } else { format!("{base_url}v1/paymenthandles?merchantRefNum={connector_payment_id}") }; Ok(url) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: paysafe::PaysafeSyncResponse = res .response .parse_struct("paysafe PaysafeSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Paysafe { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}v1/payments/{}/settlements", self.base_url(connectors), connector_payment_id )) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, )?; let connector_router_data = paysafe::PaysafeRouterData::from((amount, req)); let connector_req = paysafe::PaysafeCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: paysafe::PaysafeSettlementResponse = res .response .parse_struct("PaysafeSettlementResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Paysafe { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}v1/payments/{}/voidauths", self.base_url(connectors), connector_payment_id )) } fn get_request_body( &self, req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let minor_amount = req.request .minor_amount .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "minor_amount", })?; let currency = req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?; let amount = utils::convert_amount(self.amount_converter, minor_amount, currency)?; let connector_router_data = paysafe::PaysafeRouterData::from((amount, req)); let connector_req = paysafe::PaysafeCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(types::PaymentsVoidType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: paysafe::VoidResponse = res .response .parse_struct("PaysafeVoidResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paysafe { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}v1/settlements/{}/refunds", self.base_url(connectors), connector_payment_id )) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = paysafe::PaysafeRouterData::from((refund_amount, req)); let connector_req = paysafe::PaysafeRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: paysafe::RefundResponse = res .response .parse_struct("paysafe RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Paysafe { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_refund_id = req.request.get_connector_refund_id()?; Ok(format!( "{}v1/refunds/{}", self.base_url(connectors), connector_refund_id )) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .set_body(types::RefundSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: paysafe::RefundResponse = res .response .parse_struct("paysafe RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Paysafe { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } static PAYSAFE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, ]; let supported_capture_methods2 = vec![enums::CaptureMethod::Automatic]; let supported_card_network = vec![ common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::Visa, common_enums::CardNetwork::Interac, common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::JCB, common_enums::CardNetwork::DinersClub, common_enums::CardNetwork::Discover, common_enums::CardNetwork::CartesBancaires, common_enums::CardNetwork::UnionPay, ]; let mut paysafe_supported_payment_methods = SupportedPaymentMethods::new(); paysafe_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::NotSupported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); paysafe_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::NotSupported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); paysafe_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); paysafe_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::Skrill, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods2.clone(), specific_features: None, }, ); paysafe_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Interac, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods2.clone(), specific_features: None, }, ); paysafe_supported_payment_methods.add( enums::PaymentMethod::GiftCard, enums::PaymentMethodType::PaySafeCard, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods2.clone(), specific_features: None, }, ); paysafe_supported_payment_methods }); static PAYSAFE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Paysafe", description: "Paysafe gives ambitious businesses a launchpad with safe, secure online payment solutions, and gives consumers the ability to turn their transactions into meaningful experiences.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Sandbox, }; static PAYSAFE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Paysafe { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&PAYSAFE_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*PAYSAFE_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&PAYSAFE_SUPPORTED_WEBHOOK_FLOWS) } #[cfg(feature = "v1")] fn should_call_connector_customer( &self, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> bool { matches!( payment_attempt.setup_future_usage_applied, Some(enums::FutureUsage::OffSession) ) && payment_attempt.customer_acceptance.is_some() && matches!( payment_attempt.payment_method, Some(enums::PaymentMethod::Card) ) && matches!( payment_attempt.authentication_type, Some(enums::AuthenticationType::NoThreeDs) | None ) } }
crates/hyperswitch_connectors/src/connectors/paysafe.rs
hyperswitch_connectors::src::connectors::paysafe
9,383
true
// File: crates/hyperswitch_connectors/src/connectors/nordea.rs // Module: hyperswitch_connectors::src::connectors::nordea mod requests; mod responses; pub mod transformers; use base64::Engine; use common_enums::enums; use common_utils::{ consts, date_time, errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::{AccessToken, AccessTokenAuthenticationResponse, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, AccessTokenAuthentication, PreProcessing, }, router_request_types::{ AccessTokenAuthenticationRequestData, AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ AccessTokenAuthenticationRouterData, PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefreshTokenRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors, events::connector_api_logs::ConnectorEvent, types::{self, AuthenticationTokenType, RefreshTokenType, Response}, webhooks, }; use lazy_static::lazy_static; use masking::{ExposeInterface, Mask, PeekInterface, Secret}; use ring::{ digest, signature::{RsaKeyPair, RSA_PKCS1_SHA256}, }; use transformers::{get_error_data, NordeaAuthType}; use url::Url; use crate::{ connectors::nordea::{ requests::{ NordeaOAuthExchangeRequest, NordeaOAuthRequest, NordeaPaymentsConfirmRequest, NordeaPaymentsRequest, NordeaRouterData, }, responses::{ NordeaOAuthExchangeResponse, NordeaPaymentsConfirmResponse, NordeaPaymentsInitiateResponse, }, }, constants::headers, types::ResponseRouterData, utils::{self, RouterData as OtherRouterData}, }; #[derive(Clone)] pub struct Nordea { amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } struct SignatureParams<'a> { content_type: &'a str, host: &'a str, path: &'a str, payload_digest: Option<&'a str>, date: &'a str, http_method: Method, } impl Nordea { pub fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, } } pub fn generate_digest(&self, payload: &[u8]) -> String { let payload_digest = digest::digest(&digest::SHA256, payload); format!("sha-256={}", consts::BASE64_ENGINE.encode(payload_digest)) } pub fn generate_digest_from_request(&self, payload: &RequestContent) -> String { let payload_bytes = match payload { RequestContent::RawBytes(bytes) => bytes.clone(), _ => payload.get_inner_value().expose().as_bytes().to_vec(), }; self.generate_digest(&payload_bytes) } fn format_private_key( &self, private_key_str: &str, ) -> CustomResult<String, errors::ConnectorError> { let key = private_key_str.to_string(); // Check if it already has PEM headers let pem_data = if key.contains("BEGIN") && key.contains("END") && key.contains("PRIVATE KEY") { key } else { // Remove whitespace and format with 64-char lines let cleaned_key = key .chars() .filter(|c| !c.is_whitespace()) .collect::<String>(); let formatted_key = cleaned_key .chars() .collect::<Vec<char>>() .chunks(64) .map(|chunk| chunk.iter().collect::<String>()) .collect::<Vec<String>>() .join("\n"); format!( "-----BEGIN RSA PRIVATE KEY-----\n{formatted_key}\n-----END RSA PRIVATE KEY-----", ) }; Ok(pem_data) } // For non-production environments, signature generation can be skipped and instead `SKIP_SIGNATURE_VALIDATION_FOR_SANDBOX` can be passed. fn generate_signature( &self, auth: &NordeaAuthType, signature_params: SignatureParams<'_>, ) -> CustomResult<String, errors::ConnectorError> { const REQUEST_WITHOUT_CONTENT_HEADERS: &str = "(request-target) x-nordea-originating-host x-nordea-originating-date"; const REQUEST_WITH_CONTENT_HEADERS: &str = "(request-target) x-nordea-originating-host x-nordea-originating-date content-type digest"; let method_string = signature_params.http_method.to_string().to_lowercase(); let mut normalized_string = format!( "(request-target): {} {}\nx-nordea-originating-host: {}\nx-nordea-originating-date: {}", method_string, signature_params.path, signature_params.host, signature_params.date ); let headers = if matches!( signature_params.http_method, Method::Post | Method::Put | Method::Patch ) { let digest = signature_params.payload_digest.unwrap_or(""); normalized_string.push_str(&format!( "\ncontent-type: {}\ndigest: {}", signature_params.content_type, digest )); REQUEST_WITH_CONTENT_HEADERS } else { REQUEST_WITHOUT_CONTENT_HEADERS }; let signature_base64 = { let private_key_pem = self.format_private_key(&auth.eidas_private_key.clone().expose())?; let private_key_der = pem::parse(&private_key_pem).change_context( errors::ConnectorError::InvalidConnectorConfig { config: "eIDAS Private Key", }, )?; let private_key_der_contents = private_key_der.contents(); let key_pair = RsaKeyPair::from_der(private_key_der_contents).change_context( errors::ConnectorError::InvalidConnectorConfig { config: "eIDAS Private Key", }, )?; let mut signature = vec![0u8; key_pair.public().modulus_len()]; key_pair .sign( &RSA_PKCS1_SHA256, &ring::rand::SystemRandom::new(), normalized_string.as_bytes(), &mut signature, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; consts::BASE64_ENGINE.encode(signature) }; Ok(format!( r#"keyId="{}",algorithm="rsa-sha256",headers="{}",signature="{}""#, auth.client_id.peek(), headers, signature_base64 )) } // This helper function correctly serializes a struct into the required // non-percent-encoded form URL string. fn get_form_urlencoded_payload<T: serde::Serialize>( &self, form_data: &T, ) -> Result<Vec<u8>, error_stack::Report<errors::ConnectorError>> { let json_value = serde_json::to_value(form_data) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let btree_map: std::collections::BTreeMap<String, serde_json::Value> = serde_json::from_value(json_value) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(btree_map .iter() .map(|(k, v)| { // Remove quotes from string values for proper form encoding let value = match v { serde_json::Value::String(s) => s.clone(), _ => v.to_string(), }; format!("{k}={value}") }) .collect::<Vec<_>>() .join("&") .into_bytes()) } } impl api::Payment for Nordea {} impl api::PaymentSession for Nordea {} impl api::ConnectorAuthenticationToken for Nordea {} impl api::ConnectorAccessToken for Nordea {} impl api::MandateSetup for Nordea {} impl api::PaymentAuthorize for Nordea {} impl api::PaymentSync for Nordea {} impl api::PaymentCapture for Nordea {} impl api::PaymentVoid for Nordea {} impl api::Refund for Nordea {} impl api::RefundExecute for Nordea {} impl api::RefundSync for Nordea {} impl api::PaymentToken for Nordea {} impl api::PaymentsPreProcessing for Nordea {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Nordea { } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nordea {} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nordea where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let access_token = req .access_token .clone() .ok_or(errors::ConnectorError::FailedToObtainAuthType)?; let auth = NordeaAuthType::try_from(&req.connector_auth_type)?; let content_type = self.get_content_type().to_string(); let http_method = self.get_http_method(); // Extract host from base URL let nordea_host = Url::parse(self.base_url(connectors)) .change_context(errors::ConnectorError::RequestEncodingFailed)? .host_str() .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(); let nordea_origin_date = date_time::now_rfc7231_http_date() .change_context(errors::ConnectorError::RequestEncodingFailed)?; let full_url = self.get_url(req, connectors)?; let url_parsed = Url::parse(&full_url).change_context(errors::ConnectorError::RequestEncodingFailed)?; let path = url_parsed.path(); let path_with_query = if let Some(query) = url_parsed.query() { format!("{path}?{query}") } else { path.to_string() }; let mut required_headers = vec![ ( headers::CONTENT_TYPE.to_string(), content_type.clone().into(), ), ( headers::AUTHORIZATION.to_string(), format!("Bearer {}", access_token.token.peek()).into_masked(), ), ( "X-IBM-Client-ID".to_string(), auth.client_id.clone().expose().into_masked(), ), ( "X-IBM-Client-Secret".to_string(), auth.client_secret.clone().expose().into_masked(), ), ( "X-Nordea-Originating-Date".to_string(), nordea_origin_date.clone().into_masked(), ), ( "X-Nordea-Originating-Host".to_string(), nordea_host.clone().into_masked(), ), ]; if matches!(http_method, Method::Post | Method::Put | Method::Patch) { let nordea_request = self.get_request_body(req, connectors)?; let sha256_digest = self.generate_digest_from_request(&nordea_request); // Add Digest header required_headers.push(( "Digest".to_string(), sha256_digest.to_string().into_masked(), )); let signature = self.generate_signature( &auth, SignatureParams { content_type: &content_type, host: &nordea_host, path, payload_digest: Some(&sha256_digest), date: &nordea_origin_date, http_method, }, )?; required_headers.push(("Signature".to_string(), signature.into_masked())); } else { // Generate signature without digest for GET requests let signature = self.generate_signature( &auth, SignatureParams { content_type: &content_type, host: &nordea_host, path: &path_with_query, payload_digest: None, date: &nordea_origin_date, http_method, }, )?; required_headers.push(("Signature".to_string(), signature.into_masked())); } Ok(required_headers) } } impl ConnectorCommon for Nordea { fn id(&self) -> &'static str { "nordea" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.nordea.base_url.as_ref() } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: responses::NordeaErrorResponse = res .response .parse_struct("NordeaErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: get_error_data(response.error.as_ref()) .and_then(|failure| failure.code.clone()) .unwrap_or(NO_ERROR_CODE.to_string()), message: get_error_data(response.error.as_ref()) .and_then(|failure| failure.description.clone()) .unwrap_or(NO_ERROR_MESSAGE.to_string()), reason: get_error_data(response.error.as_ref()) .and_then(|failure| failure.failure_type.clone()), attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Nordea {} impl ConnectorIntegration< AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, > for Nordea { fn get_url( &self, _req: &AccessTokenAuthenticationRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/personal/v5/authorize", self.base_url(connectors) )) } fn get_content_type(&self) -> &'static str { "application/json" } fn get_request_body( &self, req: &AccessTokenAuthenticationRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = NordeaOAuthRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &AccessTokenAuthenticationRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let auth = NordeaAuthType::try_from(&req.connector_auth_type)?; let content_type = self.common_get_content_type().to_string(); let http_method = Method::Post; // Extract host from base URL let nordea_host = Url::parse(self.base_url(connectors)) .change_context(errors::ConnectorError::RequestEncodingFailed)? .host_str() .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(); let nordea_origin_date = date_time::now_rfc7231_http_date() .change_context(errors::ConnectorError::RequestEncodingFailed)?; let full_url = self.get_url(req, connectors)?; let url_parsed = Url::parse(&full_url).change_context(errors::ConnectorError::RequestEncodingFailed)?; let path = url_parsed.path(); let request_body = self.get_request_body(req, connectors)?; let mut required_headers = vec![ ( headers::CONTENT_TYPE.to_string(), content_type.clone().into(), ), ( "X-IBM-Client-ID".to_string(), auth.client_id.clone().expose().into_masked(), ), ( "X-IBM-Client-Secret".to_string(), auth.client_secret.clone().expose().into_masked(), ), ( "X-Nordea-Originating-Date".to_string(), nordea_origin_date.clone().into_masked(), ), ( "X-Nordea-Originating-Host".to_string(), nordea_host.clone().into_masked(), ), ]; let sha256_digest = self.generate_digest_from_request(&request_body); // Add Digest header required_headers.push(( "Digest".to_string(), sha256_digest.to_string().into_masked(), )); let signature = self.generate_signature( &auth, SignatureParams { content_type: &content_type, host: &nordea_host, path, payload_digest: Some(&sha256_digest), date: &nordea_origin_date, http_method, }, )?; required_headers.push(("Signature".to_string(), signature.into_masked())); let request = Some( RequestBuilder::new() .method(http_method) .attach_default_headers() .headers(required_headers) .url(&AuthenticationTokenType::get_url(self, req, connectors)?) .set_body(request_body) .build(), ); Ok(request) } fn handle_response( &self, data: &AccessTokenAuthenticationRouterData, _event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<AccessTokenAuthenticationRouterData, errors::ConnectorError> { // Handle 302 redirect response if res.status_code == 302 { // Extract Location header let headers = res.headers .as_ref() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "headers", })?; let location_header = headers .get("Location") .map(|value| value.to_str()) .and_then(|location_value| location_value.ok()) .ok_or(errors::ConnectorError::ParsingFailed)?; // Parse auth code from query params let url = Url::parse(location_header) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let code = url .query_pairs() .find(|(key, _)| key == "code") .map(|(_, value)| value.to_string()) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "code" })?; // Return auth code as "token" with short expiry Ok(RouterData { response: Ok(AccessTokenAuthenticationResponse { code: Secret::new(code), expires: 60, // 60 seconds - auth code validity }), ..data.clone() }) } else { Err( errors::ConnectorError::UnexpectedResponseError("Expected 302 redirect".into()) .into(), ) } } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nordea { fn get_url( &self, _req: &RefreshTokenRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/personal/v5/authorize/token", self.base_url(connectors) )) } fn get_request_body( &self, req: &RefreshTokenRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = NordeaOAuthExchangeRequest::try_from(req)?; let body_bytes = self.get_form_urlencoded_payload(&Box::new(connector_req))?; Ok(RequestContent::RawBytes(body_bytes)) } fn build_request( &self, req: &RefreshTokenRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { // For the OAuth token exchange request, we don't have a bearer token yet // We're exchanging the auth code for an access token let auth = NordeaAuthType::try_from(&req.connector_auth_type)?; let content_type = "application/x-www-form-urlencoded".to_string(); let http_method = Method::Post; // Extract host from base URL let nordea_host = Url::parse(self.base_url(connectors)) .change_context(errors::ConnectorError::RequestEncodingFailed)? .host_str() .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(); let nordea_origin_date = date_time::now_rfc7231_http_date() .change_context(errors::ConnectorError::RequestEncodingFailed)?; let full_url = self.get_url(req, connectors)?; let url_parsed = Url::parse(&full_url).change_context(errors::ConnectorError::RequestEncodingFailed)?; let path = url_parsed.path(); let request_body = self.get_request_body(req, connectors)?; let mut required_headers = vec![ ( headers::CONTENT_TYPE.to_string(), content_type.clone().into(), ), ( "X-IBM-Client-ID".to_string(), auth.client_id.clone().expose().into_masked(), ), ( "X-IBM-Client-Secret".to_string(), auth.client_secret.clone().expose().into_masked(), ), ( "X-Nordea-Originating-Date".to_string(), nordea_origin_date.clone().into_masked(), ), ( "X-Nordea-Originating-Host".to_string(), nordea_host.clone().into_masked(), ), ]; let sha256_digest = self.generate_digest_from_request(&request_body); // Add Digest header required_headers.push(( "Digest".to_string(), sha256_digest.to_string().into_masked(), )); let signature = self.generate_signature( &auth, SignatureParams { content_type: &content_type, host: &nordea_host, path, payload_digest: Some(&sha256_digest), date: &nordea_origin_date, http_method, }, )?; required_headers.push(("Signature".to_string(), signature.into_masked())); let request = Some( RequestBuilder::new() .method(http_method) .attach_default_headers() .headers(required_headers) .url(&RefreshTokenType::get_url(self, req, connectors)?) .set_body(request_body) .build(), ); Ok(request) } fn handle_response( &self, data: &RefreshTokenRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> { let response: NordeaOAuthExchangeResponse = res .response .parse_struct("NordeaOAuthExchangeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nordea { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Nordea".to_string()) .into(), ) } } impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> for Nordea { fn get_headers( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { // Determine the payment endpoint based on country and currency let country = req.get_billing_country()?; let currency = req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?; let endpoint = match (country, currency) { (api_models::enums::CountryAlpha2::FI, api_models::enums::Currency::EUR) => { "/personal/v5/payments/sepa-credit-transfers" } (api_models::enums::CountryAlpha2::DK, api_models::enums::Currency::DKK) => { "/personal/v5/payments/domestic-credit-transfers" } ( api_models::enums::CountryAlpha2::FI | api_models::enums::CountryAlpha2::DK | api_models::enums::CountryAlpha2::SE | api_models::enums::CountryAlpha2::NO, _, ) => "/personal/v5/payments/cross-border-credit-transfers", _ => { return Err(errors::ConnectorError::NotSupported { message: format!("Country {country:?} is not supported by Nordea"), connector: "Nordea", } .into()) } }; Ok(format!("{}{}", self.base_url(connectors), endpoint)) } fn get_request_body( &self, req: &PaymentsPreProcessingRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let minor_amount = req.request .minor_amount .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "minor_amount", })?; let currency = req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?; let amount = utils::convert_amount(self.amount_converter, minor_amount, currency)?; let connector_router_data = NordeaRouterData::from((amount, req)); let connector_req = NordeaPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsPreProcessingType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsPreProcessingType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsPreProcessingType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsPreProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: NordeaPaymentsInitiateResponse = res .response .parse_struct("NordeaPaymentsInitiateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nordea { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_http_method(&self) -> Method { Method::Put } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(_connectors), "/personal/v5/payments" )) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = NordeaRouterData::from((amount, req)); let connector_req = NordeaPaymentsConfirmRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(types::PaymentsAuthorizeType::get_http_method(self)) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: NordeaPaymentsConfirmResponse = res .response .parse_struct("NordeaPaymentsConfirmResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nordea { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_http_method(&self) -> Method { Method::Get } fn get_url( &self, req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req.request.connector_transaction_id.clone(); let connector_transaction_id = id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; Ok(format!( "{}{}{}", self.base_url(_connectors), "/personal/v5/payments/", connector_transaction_id )) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(types::PaymentsSyncType::get_http_method(self)) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: NordeaPaymentsInitiateResponse = res .response .parse_struct("NordeaPaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nordea { fn build_request( &self, _req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotSupported { message: "Capture".to_string(), connector: "Nordea", } .into()) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nordea { fn build_request( &self, _req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotSupported { message: "Payments Cancel".to_string(), connector: "Nordea", } .into()) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nordea { fn build_request( &self, _req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotSupported { message: "Personal API Refunds flow".to_string(), connector: "Nordea", } .into()) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nordea { // Default impl gets executed } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Nordea { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } lazy_static! { static ref NORDEA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Nordea", description: "Nordea is one of the leading financial services group in the Nordics and the preferred choice for millions across the region.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: common_enums::ConnectorIntegrationStatus::Beta, }; static ref NORDEA_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { let nordea_supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::SequentialAutomatic, ]; let mut nordea_supported_payment_methods = SupportedPaymentMethods::new(); nordea_supported_payment_methods.add( enums::PaymentMethod::BankDebit, enums::PaymentMethodType::Sepa, PaymentMethodDetails { mandates: common_enums::FeatureStatus::NotSupported, // Supported only in corporate API (corporate accounts) refunds: common_enums::FeatureStatus::NotSupported, supported_capture_methods: nordea_supported_capture_methods.clone(), specific_features: None, }, ); nordea_supported_payment_methods }; static ref NORDEA_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); } impl ConnectorSpecifications for Nordea { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&*NORDEA_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*NORDEA_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&*NORDEA_SUPPORTED_WEBHOOK_FLOWS) } fn authentication_token_for_token_creation(&self) -> bool { // Nordea requires authentication token for access token creation true } }
crates/hyperswitch_connectors/src/connectors/nordea.rs
hyperswitch_connectors::src::connectors::nordea
8,489
true
// File: crates/hyperswitch_connectors/src/connectors/adyenplatform.rs // Module: hyperswitch_connectors::src::connectors::adyenplatform pub mod transformers; use api_models::{self, webhooks::IncomingWebhookEvent}; #[cfg(feature = "payouts")] use base64::Engine; #[cfg(feature = "payouts")] use common_utils::crypto; use common_utils::errors::CustomResult; #[cfg(feature = "payouts")] use common_utils::ext_traits::{ByteSliceExt as _, BytesExt}; #[cfg(feature = "payouts")] use common_utils::request::RequestContent; #[cfg(feature = "payouts")] use common_utils::request::{Method, Request, RequestBuilder}; #[cfg(feature = "payouts")] use common_utils::types::MinorUnitForConnector; #[cfg(feature = "payouts")] use common_utils::types::{AmountConvertor, MinorUnit}; #[cfg(not(feature = "payouts"))] use error_stack::report; use error_stack::ResultExt; #[cfg(feature = "payouts")] use http::HeaderName; #[cfg(feature = "payouts")] use hyperswitch_domain_models::router_data::{ErrorResponse, RouterData}; #[cfg(feature = "payouts")] use hyperswitch_domain_models::router_flow_types::PoFulfill; #[cfg(feature = "payouts")] use hyperswitch_domain_models::types::{PayoutsData, PayoutsResponseData, PayoutsRouterData}; use hyperswitch_domain_models::{ api::ApplicationResponse, router_data::{AccessToken, ConnectorAuthType}, router_flow_types::{ AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, SetupMandate, Void, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, }, }; #[cfg(feature = "payouts")] use hyperswitch_interfaces::events::connector_api_logs::ConnectorEvent; #[cfg(feature = "payouts")] use hyperswitch_interfaces::types::{PayoutFulfillType, Response}; use hyperswitch_interfaces::{ api::{self, ConnectorCommon, ConnectorIntegration, ConnectorSpecifications}, configs::Connectors, errors::ConnectorError, webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails}, }; use masking::{Mask as _, Maskable, Secret}; #[cfg(feature = "payouts")] use ring::hmac; #[cfg(feature = "payouts")] use router_env::{instrument, tracing}; #[cfg(feature = "payouts")] use transformers::get_adyen_payout_webhook_event; use self::transformers as adyenplatform; use crate::constants::headers; #[cfg(feature = "payouts")] use crate::types::ResponseRouterData; #[cfg(feature = "payouts")] use crate::utils::convert_amount; #[derive(Clone)] pub struct Adyenplatform { #[cfg(feature = "payouts")] amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Adyenplatform { pub const fn new() -> &'static Self { &Self { #[cfg(feature = "payouts")] amount_converter: &MinorUnitForConnector, } } } impl ConnectorCommon for Adyenplatform { fn id(&self) -> &'static str { "adyenplatform" } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth = adyenplatform::AdyenplatformAuthType::try_from(auth_type) .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), )]) } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.adyenplatform.base_url.as_ref() } #[cfg(feature = "payouts")] fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { let response: adyenplatform::AdyenTransferErrorResponse = res .response .parse_struct("AdyenTransferErrorResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let message = if let Some(invalid_fields) = &response.invalid_fields { match serde_json::to_string(invalid_fields) { Ok(invalid_fields_json) => format!( "{}\nInvalid fields: {}", response.title, invalid_fields_json ), Err(_) => response.title.clone(), } } else if let Some(detail) = &response.detail { format!("{}\nDetail: {}", response.title, detail) } else { response.title.clone() }; Ok(ErrorResponse { status_code: res.status_code, code: response.error_code, message, reason: response.detail, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl api::Payment for Adyenplatform {} impl api::PaymentAuthorize for Adyenplatform {} impl api::PaymentSync for Adyenplatform {} impl api::PaymentVoid for Adyenplatform {} impl api::PaymentCapture for Adyenplatform {} impl api::MandateSetup for Adyenplatform {} impl api::ConnectorAccessToken for Adyenplatform {} impl api::PaymentToken for Adyenplatform {} impl api::ConnectorValidation for Adyenplatform {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Adyenplatform { } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Adyenplatform {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Adyenplatform { } impl api::PaymentSession for Adyenplatform {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Adyenplatform {} impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Adyenplatform {} impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Adyenplatform {} impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Adyenplatform { } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Adyenplatform {} impl api::Payouts for Adyenplatform {} #[cfg(feature = "payouts")] impl api::PayoutFulfill for Adyenplatform {} #[cfg(feature = "payouts")] impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Adyenplatform { fn get_url( &self, _req: &PayoutsRouterData<PoFulfill>, connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Ok(format!( "{}btl/v4/transfers", connectors.adyenplatform.base_url, )) } fn get_headers( &self, req: &PayoutsRouterData<PoFulfill>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), PayoutFulfillType::get_content_type(self).to_string().into(), )]; let auth = adyenplatform::AdyenplatformAuthType::try_from(&req.connector_auth_type) .change_context(ConnectorError::FailedToObtainAuthType)?; let mut api_key = vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), )]; header.append(&mut api_key); Ok(header) } fn get_request_body( &self, req: &PayoutsRouterData<PoFulfill>, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.destination_currency, )?; let connector_router_data = adyenplatform::AdyenPlatformRouterData::try_from((amount, req))?; let connector_req = adyenplatform::AdyenTransferRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PayoutsRouterData<PoFulfill>, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PayoutFulfillType::get_headers(self, req, connectors)?) .set_body(PayoutFulfillType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } #[instrument(skip_all)] fn handle_response( &self, data: &PayoutsRouterData<PoFulfill>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PayoutsRouterData<PoFulfill>, ConnectorError> { let response: adyenplatform::AdyenTransferResponse = res .response .parse_struct("AdyenTransferResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl api::Refund for Adyenplatform {} impl api::RefundExecute for Adyenplatform {} impl api::RefundSync for Adyenplatform {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Adyenplatform {} impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Adyenplatform {} #[async_trait::async_trait] impl IncomingWebhook for Adyenplatform { #[cfg(feature = "payouts")] fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } #[cfg(feature = "payouts")] fn get_webhook_source_verification_signature( &self, request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, ConnectorError> { let base64_signature = request .headers .get(HeaderName::from_static("hmacsignature")) .ok_or(ConnectorError::WebhookSourceVerificationFailed)?; Ok(base64_signature.as_bytes().to_vec()) } #[cfg(feature = "payouts")] fn get_webhook_source_verification_message( &self, request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, ConnectorError> { Ok(request.body.to_vec()) } #[cfg(feature = "payouts")] async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, ConnectorError> { use common_utils::consts; let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_label, connector_webhook_details, ) .await .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let message = self .get_webhook_source_verification_message( request, merchant_id, &connector_webhook_secrets, ) .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let raw_key = hex::decode(connector_webhook_secrets.secret) .change_context(ConnectorError::WebhookVerificationSecretInvalid)?; let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &raw_key); let signed_messaged = hmac::sign(&signing_key, &message); let payload_sign = consts::BASE64_ENGINE.encode(signed_messaged.as_ref()); Ok(payload_sign.as_bytes().eq(&signature)) } fn get_webhook_object_reference_id( &self, #[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>, #[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> { #[cfg(feature = "payouts")] { let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request .body .parse_struct("AdyenplatformIncomingWebhook") .change_context(ConnectorError::WebhookSourceVerificationFailed)?; Ok(api_models::webhooks::ObjectReferenceId::PayoutId( api_models::webhooks::PayoutIdType::PayoutAttemptId(webhook_body.data.reference), )) } #[cfg(not(feature = "payouts"))] { Err(report!(ConnectorError::WebhooksNotImplemented)) } } fn get_webhook_api_response( &self, _request: &IncomingWebhookRequestDetails<'_>, error_kind: Option<IncomingWebhookFlowError>, ) -> CustomResult<ApplicationResponse<serde_json::Value>, ConnectorError> { if error_kind.is_some() { Ok(ApplicationResponse::JsonWithHeaders(( serde_json::Value::Null, vec![( "x-http-code".to_string(), Maskable::Masked(Secret::new("404".to_string())), )], ))) } else { Ok(ApplicationResponse::StatusOk) } } fn get_webhook_event_type( &self, #[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>, #[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { #[cfg(feature = "payouts")] { let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request .body .parse_struct("AdyenplatformIncomingWebhook") .change_context(ConnectorError::WebhookSourceVerificationFailed)?; Ok(get_adyen_payout_webhook_event( webhook_body.webhook_type, webhook_body.data.status, webhook_body.data.tracking, )) } #[cfg(not(feature = "payouts"))] { Err(report!(ConnectorError::WebhooksNotImplemented)) } } fn get_webhook_resource_object( &self, #[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>, #[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { #[cfg(feature = "payouts")] { let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request .body .parse_struct("AdyenplatformIncomingWebhook") .change_context(ConnectorError::WebhookSourceVerificationFailed)?; Ok(Box::new(webhook_body)) } #[cfg(not(feature = "payouts"))] { Err(report!(ConnectorError::WebhooksNotImplemented)) } } } static ADYENPLATFORM_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Adyen Platform", description: "Adyen Platform for marketplace payouts and disbursements", connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor, integration_status: common_enums::ConnectorIntegrationStatus::Sandbox, }; impl ConnectorSpecifications for Adyenplatform { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&ADYENPLATFORM_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { None } fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> { None } }
crates/hyperswitch_connectors/src/connectors/adyenplatform.rs
hyperswitch_connectors::src::connectors::adyenplatform
3,877
true
// File: crates/hyperswitch_connectors/src/connectors/amazonpay.rs // Module: hyperswitch_connectors::src::connectors::amazonpay pub mod transformers; use std::sync::LazyLock; use base64::{engine::general_purpose::STANDARD, Engine}; use chrono::Utc; use common_enums::enums; use common_utils::{ crypto::{RsaPssSha256, SignMessage}, errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hex; use hyperswitch_domain_models::{ payment_method_data::{PaymentMethodData, WalletData as WalletDataPaymentMethod}, router_data::{AccessToken, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use masking::{ExposeInterface, Mask, Maskable, PeekInterface, Secret}; use sha2::{Digest, Sha256}; use transformers as amazonpay; use crate::{ constants::headers, types::ResponseRouterData, utils::{self, PaymentsSyncRequestData}, }; const SIGNING_ALGO: &str = "AMZN-PAY-RSASSA-PSS-V2"; const HEADER_ACCEPT: &str = "accept"; const HEADER_CONTENT_TYPE: &str = "content-type"; const HEADER_DATE: &str = "x-amz-pay-date"; const HEADER_HOST: &str = "x-amz-pay-host"; const HEADER_IDEMPOTENCY_KEY: &str = "x-amz-pay-idempotency-key"; const HEADER_REGION: &str = "x-amz-pay-region"; const FINALIZE_SEGMENT: &str = "finalize"; const AMAZON_PAY_API_BASE_URL: &str = "https://pay-api.amazon.com"; const AMAZON_PAY_HOST: &str = "pay-api.amazon.com"; #[derive(Clone)] pub struct Amazonpay { amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Amazonpay { pub fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, } } fn get_last_segment(canonical_uri: &str) -> String { canonical_uri .chars() .rev() .take_while(|&c| c != '/') .collect::<Vec<_>>() .into_iter() .rev() .collect() } pub fn create_authorization_header( &self, auth: amazonpay::AmazonpayAuthType, canonical_uri: &str, http_method: &Method, hashed_payload: &str, header: &[(String, Maskable<String>)], ) -> String { let amazonpay::AmazonpayAuthType { public_key, private_key, } = auth; let mut signed_headers = format!("{HEADER_ACCEPT};{HEADER_CONTENT_TYPE};{HEADER_DATE};{HEADER_HOST};",); if *http_method == Method::Post && Self::get_last_segment(canonical_uri) != *FINALIZE_SEGMENT.to_string() { signed_headers.push_str(HEADER_IDEMPOTENCY_KEY); signed_headers.push(';'); } signed_headers.push_str(HEADER_REGION); format!( "{} PublicKeyId={}, SignedHeaders={}, Signature={}", SIGNING_ALGO, public_key.expose().clone(), signed_headers, Self::create_signature( &private_key, *http_method, canonical_uri, &signed_headers, hashed_payload, header ) .unwrap_or_else(|_| "Invalid signature".to_string()) ) } fn create_signature( private_key: &Secret<String>, http_method: Method, canonical_uri: &str, signed_headers: &str, hashed_payload: &str, header: &[(String, Maskable<String>)], ) -> Result<String, String> { let mut canonical_request = http_method.to_string() + "\n" + canonical_uri + "\n\n"; let mut lowercase_sorted_header_keys: Vec<String> = header.iter().map(|(key, _)| key.to_lowercase()).collect(); lowercase_sorted_header_keys.sort(); for key in lowercase_sorted_header_keys { if let Some((_, maskable_value)) = header.iter().find(|(k, _)| k.to_lowercase() == key) { let value: String = match maskable_value { Maskable::Normal(v) => v.clone(), Maskable::Masked(secret) => secret.clone().expose(), }; canonical_request.push_str(&format!("{key}:{value}\n")); } } canonical_request.push_str(&("\n".to_owned() + signed_headers + "\n" + hashed_payload)); let string_to_sign = format!( "{}\n{}", SIGNING_ALGO, hex::encode(Sha256::digest(canonical_request.as_bytes())) ); Self::sign(private_key, &string_to_sign) .map_err(|e| format!("Failed to create signature: {e}")) } fn sign( private_key_pem_str: &Secret<String>, string_to_sign: &String, ) -> Result<String, String> { let rsa_pss_sha256_signer = RsaPssSha256; let signature_bytes = rsa_pss_sha256_signer .sign_message( private_key_pem_str.peek().as_bytes(), string_to_sign.as_bytes(), ) .change_context(errors::ConnectorError::RequestEncodingFailed) .map_err(|e| format!("Crypto operation failed: {e:?}"))?; Ok(STANDARD.encode(signature_bytes)) } } impl api::Payment for Amazonpay {} impl api::PaymentSession for Amazonpay {} impl api::ConnectorAccessToken for Amazonpay {} impl api::MandateSetup for Amazonpay {} impl api::PaymentAuthorize for Amazonpay {} impl api::PaymentSync for Amazonpay {} impl api::PaymentCapture for Amazonpay {} impl api::PaymentVoid for Amazonpay {} impl api::Refund for Amazonpay {} impl api::RefundExecute for Amazonpay {} impl api::RefundSync for Amazonpay {} impl api::PaymentToken for Amazonpay {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Amazonpay { } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Amazonpay where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let http_method = self.get_http_method(); let canonical_uri: String = self.get_url(req, connectors)? .replacen(AMAZON_PAY_API_BASE_URL, "", 1); let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), ), ( headers::ACCEPT.to_string(), "application/json".to_string().into(), ), ( HEADER_DATE.to_string(), Utc::now() .format("%Y-%m-%dT%H:%M:%SZ") .to_string() .into_masked(), ), ( HEADER_HOST.to_string(), AMAZON_PAY_HOST.to_string().into_masked(), ), (HEADER_REGION.to_string(), "na".to_string().into_masked()), ]; if http_method == Method::Post && Self::get_last_segment(&canonical_uri) != *FINALIZE_SEGMENT.to_string() { header.push(( HEADER_IDEMPOTENCY_KEY.to_string(), req.connector_request_reference_id.clone().into_masked(), )); } let hashed_payload = if http_method == Method::Get { hex::encode(Sha256::digest("".as_bytes())) } else { hex::encode(Sha256::digest( self.get_request_body(req, connectors)? .get_inner_value() .expose() .as_bytes(), )) }; let authorization = self.create_authorization_header( amazonpay::AmazonpayAuthType::try_from(&req.connector_auth_type)?, &canonical_uri, &http_method, &hashed_payload, &header, ); header.push(( headers::AUTHORIZATION.to_string(), authorization.clone().into_masked(), )); Ok(header) } } impl ConnectorCommon for Amazonpay { fn id(&self) -> &'static str { "amazonpay" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.amazonpay.base_url.as_ref() } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: amazonpay::AmazonpayErrorResponse = res .response .parse_struct("AmazonpayErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.reason_code.clone(), message: response.message.clone(), attempt_status: None, connector_transaction_id: None, reason: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Amazonpay {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Amazonpay {} impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Amazonpay {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Amazonpay { } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Amazonpay { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { match req.request.payment_method_data.clone() { PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { WalletDataPaymentMethod::AmazonPay(ref req_wallet) => Ok(format!( "{}/checkoutSessions/{}/finalize", self.base_url(connectors), req_wallet.checkout_session_id.clone() )), WalletDataPaymentMethod::AliPayQr(_) | WalletDataPaymentMethod::AliPayRedirect(_) | WalletDataPaymentMethod::AliPayHkRedirect(_) | WalletDataPaymentMethod::AmazonPayRedirect(_) | WalletDataPaymentMethod::MomoRedirect(_) | WalletDataPaymentMethod::KakaoPayRedirect(_) | WalletDataPaymentMethod::GoPayRedirect(_) | WalletDataPaymentMethod::GcashRedirect(_) | WalletDataPaymentMethod::ApplePay(_) | WalletDataPaymentMethod::ApplePayRedirect(_) | WalletDataPaymentMethod::ApplePayThirdPartySdk(_) | WalletDataPaymentMethod::DanaRedirect {} | WalletDataPaymentMethod::GooglePay(_) | WalletDataPaymentMethod::GooglePayRedirect(_) | WalletDataPaymentMethod::GooglePayThirdPartySdk(_) | WalletDataPaymentMethod::MbWayRedirect(_) | WalletDataPaymentMethod::MobilePayRedirect(_) | WalletDataPaymentMethod::PaypalRedirect(_) | WalletDataPaymentMethod::PaypalSdk(_) | WalletDataPaymentMethod::Paze(_) | WalletDataPaymentMethod::SamsungPay(_) | WalletDataPaymentMethod::TwintRedirect {} | WalletDataPaymentMethod::VippsRedirect {} | WalletDataPaymentMethod::BluecodeRedirect {} | WalletDataPaymentMethod::TouchNGoRedirect(_) | WalletDataPaymentMethod::WeChatPayRedirect(_) | WalletDataPaymentMethod::WeChatPayQr(_) | WalletDataPaymentMethod::CashappQr(_) | WalletDataPaymentMethod::SwishQr(_) | WalletDataPaymentMethod::RevolutPay(_) | WalletDataPaymentMethod::Paysera(_) | WalletDataPaymentMethod::Skrill(_) | WalletDataPaymentMethod::Mifinity(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("amazonpay"), ) .into()) } }, _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = amazonpay::AmazonpayRouterData::from((amount, req)); let connector_req = amazonpay::AmazonpayFinalizeRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: amazonpay::AmazonpayFinalizeResponse = res .response .parse_struct("Amazonpay PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Amazonpay { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/charges/{}", self.base_url(connectors), req.request.get_connector_transaction_id()? )) } fn get_http_method(&self) -> Method { Method::Get } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: amazonpay::AmazonpayPaymentsResponse = res .response .parse_struct("Amazonpay PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Amazonpay { fn build_request( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("Capture".to_string()).into()) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Amazonpay { fn build_request( &self, _req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("Void".to_string()).into()) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Amazonpay { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/refunds", self.base_url(connectors))) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = amazonpay::AmazonpayRouterData::from((refund_amount, req)); let connector_req = amazonpay::AmazonpayRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: amazonpay::RefundResponse = res .response .parse_struct("amazonpay RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Amazonpay { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/refunds/{}", self.base_url(connectors), req.request.connector_refund_id.clone().unwrap_or_default() )) } fn get_http_method(&self) -> Method { Method::Get } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .set_body(types::RefundSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: amazonpay::RefundResponse = res .response .parse_struct("amazonpay RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Amazonpay { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } static AMAZONPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![enums::CaptureMethod::Automatic]; let mut amazonpay_supported_payment_methods = SupportedPaymentMethods::new(); amazonpay_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::AmazonPay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); amazonpay_supported_payment_methods }); static AMAZONPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Amazon Pay", description: "Amazon Pay is an Alternative Payment Method (APM) connector that allows merchants to accept payments using customers' stored Amazon account details, providing a seamless checkout experience.", connector_type: enums::HyperswitchConnectorCategory::AlternativePaymentMethod, integration_status: enums::ConnectorIntegrationStatus::Alpha, }; static AMAZONPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Amazonpay { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&AMAZONPAY_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&AMAZONPAY_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&AMAZONPAY_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/amazonpay.rs
hyperswitch_connectors::src::connectors::amazonpay
5,953
true
// File: crates/hyperswitch_connectors/src/connectors/signifyd.rs // Module: hyperswitch_connectors::src::connectors::signifyd pub mod transformers; use std::fmt::Debug; #[cfg(feature = "frm")] use api_models::webhooks::IncomingWebhookEvent; #[cfg(feature = "frm")] use base64::Engine; #[cfg(feature = "frm")] use common_utils::{ consts, request::{Method, RequestBuilder}, }; #[cfg(feature = "frm")] use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; use common_utils::{errors::CustomResult, request::Request}; #[cfg(feature = "frm")] use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{AccessToken, RouterData}, router_flow_types::{ AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, SetupMandate, Void, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, }, }; #[cfg(feature = "frm")] use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, ErrorResponse}, router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, }, router_response_types::fraud_check::FraudCheckResponseData, }; use hyperswitch_interfaces::{ api::{ ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, MandateSetup, Payment, PaymentAuthorize, PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, Refund, RefundExecute, RefundSync, }, configs::Connectors, errors::ConnectorError, }; #[cfg(feature = "frm")] use hyperswitch_interfaces::{ api::{ FraudCheck, FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale, FraudCheckTransaction, }, consts::NO_ERROR_CODE, events::connector_api_logs::ConnectorEvent, types::Response, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; #[cfg(feature = "frm")] use masking::Mask; use masking::Maskable; #[cfg(feature = "frm")] use masking::{PeekInterface, Secret}; #[cfg(feature = "frm")] use ring::hmac; #[cfg(feature = "frm")] use transformers as signifyd; use crate::constants::headers; #[cfg(feature = "frm")] use crate::{ types::{ FrmCheckoutRouterData, FrmCheckoutType, FrmFulfillmentRouterData, FrmFulfillmentType, FrmRecordReturnRouterData, FrmRecordReturnType, FrmSaleRouterData, FrmSaleType, FrmTransactionRouterData, FrmTransactionType, ResponseRouterData, }, utils::get_header_key_value, }; #[derive(Debug, Clone)] pub struct Signifyd; impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Signifyd where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Signifyd { fn id(&self) -> &'static str { "signifyd" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.signifyd.base_url.as_ref() } #[cfg(feature = "frm")] fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth = signifyd::SignifydAuthType::try_from(auth_type) .change_context(ConnectorError::FailedToObtainAuthType)?; let auth_api_key = format!( "Basic {}", consts::BASE64_ENGINE.encode(auth.api_key.peek()) ); Ok(vec![( headers::AUTHORIZATION.to_string(), Mask::into_masked(auth_api_key), )]) } #[cfg(feature = "frm")] fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { let response: signifyd::SignifydErrorResponse = res .response .parse_struct("SignifydErrorResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: NO_ERROR_CODE.to_string(), message: response.messages.join(" &"), reason: Some(response.errors.to_string()), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl Payment for Signifyd {} impl PaymentAuthorize for Signifyd {} impl PaymentSync for Signifyd {} impl PaymentVoid for Signifyd {} impl PaymentCapture for Signifyd {} impl MandateSetup for Signifyd {} impl ConnectorAccessToken for Signifyd {} impl PaymentToken for Signifyd {} impl Refund for Signifyd {} impl RefundExecute for Signifyd {} impl RefundSync for Signifyd {} impl ConnectorValidation for Signifyd {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Signifyd { } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Signifyd {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Signifyd { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Err(ConnectorError::NotImplemented("Setup Mandate flow for Signifyd".to_string()).into()) } } impl PaymentSession for Signifyd {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Signifyd {} impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Signifyd {} impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Signifyd {} impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Signifyd {} impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Signifyd {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Signifyd {} impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Signifyd {} #[cfg(feature = "frm")] impl FraudCheck for Signifyd {} #[cfg(feature = "frm")] impl FraudCheckSale for Signifyd {} #[cfg(feature = "frm")] impl FraudCheckCheckout for Signifyd {} #[cfg(feature = "frm")] impl FraudCheckTransaction for Signifyd {} #[cfg(feature = "frm")] impl FraudCheckFulfillment for Signifyd {} #[cfg(feature = "frm")] impl FraudCheckRecordReturn for Signifyd {} #[cfg(feature = "frm")] impl ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> for Signifyd { fn get_headers( &self, req: &FrmSaleRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &FrmSaleRouterData, connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/sales" )) } fn get_request_body( &self, req: &FrmSaleRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let req_obj = signifyd::SignifydPaymentsSaleRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &FrmSaleRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&FrmSaleType::get_url(self, req, connectors)?) .attach_default_headers() .headers(FrmSaleType::get_headers(self, req, connectors)?) .set_body(FrmSaleType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &FrmSaleRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<FrmSaleRouterData, ConnectorError> { let response: signifyd::SignifydPaymentsResponse = res .response .parse_struct("SignifydPaymentsResponse Sale") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <FrmSaleRouterData>::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] impl ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> for Signifyd { fn get_headers( &self, req: &FrmCheckoutRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &FrmCheckoutRouterData, connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/checkouts" )) } fn get_request_body( &self, req: &FrmCheckoutRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let req_obj = signifyd::SignifydPaymentsCheckoutRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &FrmCheckoutRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&FrmCheckoutType::get_url(self, req, connectors)?) .attach_default_headers() .headers(FrmCheckoutType::get_headers(self, req, connectors)?) .set_body(FrmCheckoutType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &FrmCheckoutRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<FrmCheckoutRouterData, ConnectorError> { let response: signifyd::SignifydPaymentsResponse = res .response .parse_struct("SignifydPaymentsResponse Checkout") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <FrmCheckoutRouterData>::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] impl ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData> for Signifyd { fn get_headers( &self, req: &FrmTransactionRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &FrmTransactionRouterData, connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/transactions" )) } fn get_request_body( &self, req: &FrmTransactionRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let req_obj = signifyd::SignifydPaymentsTransactionRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &FrmTransactionRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&FrmTransactionType::get_url(self, req, connectors)?) .attach_default_headers() .headers(FrmTransactionType::get_headers(self, req, connectors)?) .set_body(FrmTransactionType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &FrmTransactionRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<FrmTransactionRouterData, ConnectorError> { let response: signifyd::SignifydPaymentsResponse = res .response .parse_struct("SignifydPaymentsResponse Transaction") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <FrmTransactionRouterData>::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] impl ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> for Signifyd { fn get_headers( &self, req: &FrmFulfillmentRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &FrmFulfillmentRouterData, connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/fulfillments" )) } fn get_request_body( &self, req: &FrmFulfillmentRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let req_obj = signifyd::FrmFulfillmentSignifydRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj.clone()))) } fn build_request( &self, req: &FrmFulfillmentRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&FrmFulfillmentType::get_url(self, req, connectors)?) .attach_default_headers() .headers(FrmFulfillmentType::get_headers(self, req, connectors)?) .set_body(FrmFulfillmentType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &FrmFulfillmentRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<FrmFulfillmentRouterData, ConnectorError> { let response: signifyd::FrmFulfillmentSignifydApiResponse = res .response .parse_struct("FrmFulfillmentSignifydApiResponse Sale") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); FrmFulfillmentRouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] impl ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData> for Signifyd { fn get_headers( &self, req: &FrmRecordReturnRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &FrmRecordReturnRouterData, connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/returns/records" )) } fn get_request_body( &self, req: &FrmRecordReturnRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let req_obj = signifyd::SignifydPaymentsRecordReturnRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &FrmRecordReturnRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&FrmRecordReturnType::get_url(self, req, connectors)?) .attach_default_headers() .headers(FrmRecordReturnType::get_headers(self, req, connectors)?) .set_body(FrmRecordReturnType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &FrmRecordReturnRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<FrmRecordReturnRouterData, ConnectorError> { let response: signifyd::SignifydPaymentsRecordReturnResponse = res .response .parse_struct("SignifydPaymentsResponse Transaction") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <FrmRecordReturnRouterData>::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] #[async_trait::async_trait] impl IncomingWebhook for Signifyd { fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, ConnectorError> { let header_value = get_header_key_value("x-signifyd-sec-hmac-sha256", request.headers)?; Ok(header_value.as_bytes().to_vec()) } fn get_webhook_source_verification_message( &self, request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, ConnectorError> { Ok(request.body.to_vec()) } async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_label, connector_webhook_details, ) .await .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let message = self .get_webhook_source_verification_message( request, merchant_id, &connector_webhook_secrets, ) .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &connector_webhook_secrets.secret); let signed_message = hmac::sign(&signing_key, &message); let payload_sign = consts::BASE64_ENGINE.encode(signed_message.as_ref()); Ok(payload_sign.as_bytes().eq(&signature)) } fn get_webhook_object_reference_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> { let resource: signifyd::SignifydWebhookBody = request .body .parse_struct("SignifydWebhookBody") .change_context(ConnectorError::WebhookReferenceIdNotFound)?; Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(resource.order_id), )) } fn get_webhook_event_type( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { let resource: signifyd::SignifydWebhookBody = request .body .parse_struct("SignifydWebhookBody") .change_context(ConnectorError::WebhookEventTypeNotFound)?; Ok(IncomingWebhookEvent::from(resource.review_disposition)) } fn get_webhook_resource_object( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { let resource: signifyd::SignifydWebhookBody = request .body .parse_struct("SignifydWebhookBody") .change_context(ConnectorError::WebhookResourceObjectNotFound)?; Ok(Box::new(resource)) } } static SYGNIFYD_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Signifyd", description: "Signifyd fraud and risk management provider with AI-driven commerce protection platform for maximizing conversions and eliminating fraud risk with guaranteed fraud liability coverage", connector_type: common_enums::HyperswitchConnectorCategory::FraudAndRiskManagementProvider, integration_status: common_enums::ConnectorIntegrationStatus::Sandbox, }; impl ConnectorSpecifications for Signifyd { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&SYGNIFYD_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { None } fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> { None } }
crates/hyperswitch_connectors/src/connectors/signifyd.rs
hyperswitch_connectors::src::connectors::signifyd
5,771
true
// File: crates/hyperswitch_connectors/src/connectors/coinbase.rs // Module: hyperswitch_connectors::src::connectors::coinbase pub mod transformers; use common_enums::enums; use common_utils::{ crypto, errors::CustomResult, ext_traits::ByteSliceExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ connector_endpoints::Connectors, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, errors, events::connector_api_logs::ConnectorEvent, types::{PaymentsAuthorizeType, PaymentsSyncType, Response}, webhooks, }; use lazy_static::lazy_static; use masking::Mask; use transformers as coinbase; use self::coinbase::CoinbaseWebhookDetails; use crate::{ constants::headers, types::ResponseRouterData, utils::{self, convert_amount}, }; #[derive(Clone)] pub struct Coinbase { amount_convertor: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Coinbase { pub fn new() -> &'static Self { &Self { amount_convertor: &StringMajorUnitForConnector, } } } impl api::Payment for Coinbase {} impl api::PaymentToken for Coinbase {} impl api::PaymentSession for Coinbase {} impl api::ConnectorAccessToken for Coinbase {} impl api::MandateSetup for Coinbase {} impl api::PaymentAuthorize for Coinbase {} impl api::PaymentSync for Coinbase {} impl api::PaymentCapture for Coinbase {} impl api::PaymentVoid for Coinbase {} impl api::Refund for Coinbase {} impl api::RefundExecute for Coinbase {} impl api::RefundSync for Coinbase {} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Coinbase where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), self.common_get_content_type().to_string().into(), ), ( headers::X_CC_VERSION.to_string(), "2018-03-22".to_string().into(), ), ]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Coinbase { fn id(&self) -> &'static str { "coinbase" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.coinbase.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth: coinbase::CoinbaseAuthType = coinbase::CoinbaseAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::X_CC_API_KEY.to_string(), auth.api_key.into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: coinbase::CoinbaseErrorResponse = res .response .parse_struct("CoinbaseErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.error.error_type, message: response.error.message, reason: response.error.code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Coinbase {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Coinbase { // Not Implemented (R) } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coinbase { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coinbase {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Coinbase { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Coinbase".to_string()) .into(), ) } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coinbase { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/charges", self.base_url(_connectors))) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_convertor, req.request.minor_amount, req.request.currency, )?; let connector_router_data = coinbase::CoinbaseRouterData::from((amount, req)); let connector_req = coinbase::CoinbasePaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: coinbase::CoinbasePaymentsResponse = res .response .parse_struct("Coinbase PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Coinbase { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_id = _req .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; Ok(format!( "{}/charges/{}", self.base_url(_connectors), connector_id )) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&PaymentsSyncType::get_url(self, req, connectors)?) .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: coinbase::CoinbasePaymentsResponse = res .response .parse_struct("coinbase PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Coinbase { fn build_request( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Capture".to_string(), connector: "Coinbase".to_string(), } .into()) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Coinbase {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coinbase { fn build_request( &self, _req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Refund".to_string(), connector: "Coinbase".to_string(), } .into()) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Coinbase { // default implementation of build_request method will be executed } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Coinbase { fn get_webhook_source_verification_algorithm( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let base64_signature = utils::get_header_key_value("X-CC-Webhook-Signature", request.headers)?; hex::decode(base64_signature) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) } fn get_webhook_source_verification_message( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let message = std::str::from_utf8(request.body) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; Ok(message.to_string().into_bytes()) } fn get_webhook_object_reference_id( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let notif: CoinbaseWebhookDetails = request .body .parse_struct("CoinbaseWebhookDetails") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId(notif.event.data.id), )) } fn get_webhook_event_type( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let notif: CoinbaseWebhookDetails = request .body .parse_struct("CoinbaseWebhookDetails") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; match notif.event.event_type { coinbase::WebhookEventType::Confirmed | coinbase::WebhookEventType::Resolved => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess) } coinbase::WebhookEventType::Failed => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired) } coinbase::WebhookEventType::Pending => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing) } coinbase::WebhookEventType::Unknown | coinbase::WebhookEventType::Created => { Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported) } } } fn get_webhook_resource_object( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let notif: CoinbaseWebhookDetails = request .body .parse_struct("CoinbaseWebhookDetails") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(Box::new(notif.event)) } } lazy_static! { static ref COINBASE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Coinbase", description: "Coinbase is a place for people and businesses to buy, sell, and manage crypto.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Beta, }; static ref COINBASE_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, enums::CaptureMethod::SequentialAutomatic, ]; let mut coinbase_supported_payment_methods = SupportedPaymentMethods::new(); coinbase_supported_payment_methods.add( enums::PaymentMethod::Crypto, enums::PaymentMethodType::CryptoCurrency, PaymentMethodDetails { mandates: common_enums::FeatureStatus::NotSupported, refunds: common_enums::FeatureStatus::NotSupported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); coinbase_supported_payment_methods }; static ref COINBASE_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = vec![enums::EventClass::Payments, enums::EventClass::Refunds,]; } impl ConnectorSpecifications for Coinbase { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&*COINBASE_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*COINBASE_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&*COINBASE_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/coinbase.rs
hyperswitch_connectors::src::connectors::coinbase
3,888
true
// File: crates/hyperswitch_connectors/src/connectors/payme.rs // Module: hyperswitch_connectors::src::connectors::payme pub mod transformers; use std::sync::LazyLock; use api_models::enums::AuthenticationType; use common_enums::enums; use common_utils::{ crypto, errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{ AmountConvertor, MinorUnit, MinorUnitForConnector, StringMajorUnit, StringMajorUnitForConnector, StringMinorUnit, StringMinorUnitForConnector, }, }; use error_stack::{Report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, CompleteAuthorize, InitPayment, PreProcessing, }, router_request_types::{ AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, RefundsRouterData, TokenizationRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation, PaymentsPreProcessing, }, configs::Connectors, disputes::DisputePayload, errors, events::connector_api_logs::ConnectorEvent, types::{ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsPreProcessingType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response, TokenizationType, }, webhooks, }; use masking::{ExposeInterface, Secret}; use transformers as payme; use crate::{ types::ResponseRouterData, utils::{self, ForeignTryFrom, PaymentsPreProcessingRequestData}, }; #[derive(Clone)] pub struct Payme { amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), apple_pay_google_pay_amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), amount_converter_webhooks: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), } impl Payme { pub const fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, apple_pay_google_pay_amount_converter: &StringMajorUnitForConnector, amount_converter_webhooks: &StringMinorUnitForConnector, } } } impl api::Payment for Payme {} impl api::PaymentSession for Payme {} impl api::PaymentsCompleteAuthorize for Payme {} impl api::ConnectorAccessToken for Payme {} impl api::MandateSetup for Payme {} impl api::PaymentAuthorize for Payme {} impl api::PaymentSync for Payme {} impl api::PaymentCapture for Payme {} impl api::PaymentVoid for Payme {} impl api::Refund for Payme {} impl api::RefundExecute for Payme {} impl api::RefundSync for Payme {} impl api::PaymentToken for Payme {} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Payme where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, _req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let header = vec![( crate::constants::headers::CONTENT_TYPE.to_string(), Self::get_content_type(self).to_string().into(), )]; Ok(header) } } impl ConnectorCommon for Payme { fn id(&self) -> &'static str { "payme" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.payme.base_url.as_ref() } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: Result< payme::PaymeErrorResponse, Report<common_utils::errors::ParsingError>, > = res.response.parse_struct("PaymeErrorResponse"); match response { Ok(response_data) => { event_builder.map(|i| i.set_error_response_body(&response_data)); router_env::logger::info!(connector_response=?response_data); let status_code = match res.status_code { 500..=511 => 200, _ => res.status_code, }; Ok(ErrorResponse { status_code, code: response_data.status_error_code.to_string(), message: response_data.status_error_details.clone(), reason: Some(format!( "{}, additional info: {}", response_data.status_error_details, response_data.status_additional_info )), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } Err(error_msg) => { event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code}))); router_env::logger::error!(deserialization_error =? error_msg); utils::handle_json_response_deserialization_failure(res, "payme") } } } } impl ConnectorValidation for Payme { fn validate_connector_against_payment_request( &self, capture_method: Option<enums::CaptureMethod>, _payment_method: enums::PaymentMethod, _pmt: Option<enums::PaymentMethodType>, ) -> CustomResult<(), errors::ConnectorError> { let capture_method = capture_method.unwrap_or_default(); match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual | enums::CaptureMethod::SequentialAutomatic => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( utils::construct_not_supported_error_report(capture_method, self.id()), ), } } fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([ utils::PaymentMethodDataType::Card, utils::PaymentMethodDataType::ApplePayThirdPartySdk, ]); utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Payme { fn get_headers( &self, req: &TokenizationRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &TokenizationRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}api/capture-buyer-token", self.base_url(connectors) )) } fn get_request_body( &self, req: &TokenizationRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = payme::CaptureBuyerRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &TokenizationRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(match req.auth_type { AuthenticationType::ThreeDs => Some( RequestBuilder::new() .method(Method::Post) .url(&TokenizationType::get_url(self, req, connectors)?) .attach_default_headers() .headers(TokenizationType::get_headers(self, req, connectors)?) .set_body(TokenizationType::get_request_body(self, req, connectors)?) .build(), ), AuthenticationType::NoThreeDs => None, }) } fn handle_response( &self, data: &TokenizationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<TokenizationRouterData, errors::ConnectorError> where PaymentsResponseData: Clone, { let response: payme::CaptureBuyerResponse = res .response .parse_struct("Payme CaptureBuyerResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Payme {} impl PaymentsPreProcessing for Payme {} impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> for Payme { fn get_headers( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/generate-sale", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsPreProcessingRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_amount = req.request.get_minor_amount()?; let req_currency = req.request.get_currency()?; let amount = utils::convert_amount(self.amount_converter, req_amount, req_currency)?; let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?; let connector_req = payme::GenerateSaleRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let req = Some( RequestBuilder::new() .method(Method::Post) .attach_default_headers() .headers(PaymentsPreProcessingType::get_headers( self, req, connectors, )?) .url(&PaymentsPreProcessingType::get_url(self, req, connectors)?) .set_body(PaymentsPreProcessingType::get_request_body( self, req, connectors, )?) .build(), ); Ok(req) } fn handle_response( &self, data: &PaymentsPreProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: payme::GenerateSaleResponse = res .response .parse_struct("Payme GenerateSaleResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let req_amount = data.request.get_minor_amount()?; let req_currency = data.request.get_currency()?; let apple_pay_amount = utils::convert_amount( self.apple_pay_google_pay_amount_converter, req_amount, req_currency, )?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::foreign_try_from(( ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }, apple_pay_amount, )) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios self.build_error_response(res, event_builder) } } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Payme {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Payme { fn build_request( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Payme".to_string()) .into(), ) } } impl ConnectorRedirectResponse for Payme { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, action: enums::PaymentAction, ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> { match action { enums::PaymentAction::PSync | enums::PaymentAction::CompleteAuthorize | enums::PaymentAction::PaymentAuthenticateCompleteAuthorize => { Ok(enums::CallConnectorAction::Trigger) } } } } impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> for Payme { fn get_headers( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/pay-sale", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsCompleteAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = payme::Pay3dsRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCompleteAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(PaymentsCompleteAuthorizeType::get_headers( self, req, connectors, )?) .set_body(PaymentsCompleteAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCompleteAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: payme::PaymePaySaleResponse = res .response .parse_struct("Payme PaymePaySaleResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData> for Payme {} impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Payme { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { if req.request.mandate_id.is_some() { // For recurring mandate payments Ok(format!("{}api/generate-sale", self.base_url(connectors))) } else { // For Normal & first mandate payments Ok(format!("{}api/pay-sale", self.base_url(connectors))) } } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?; let connector_req = payme::PaymePaymentRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: payme::PaymePaySaleResponse = res .response .parse_struct("Payme PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Payme { fn get_url( &self, _req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/get-sales", self.base_url(connectors))) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_headers( &self, req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = payme::PaymeQuerySaleRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .set_body(PaymentsSyncType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< RouterData<PSync, PaymentsSyncData, PaymentsResponseData>, errors::ConnectorError, > where PSync: Clone, PaymentsSyncData: Clone, PaymentsResponseData: Clone, { let response: payme::PaymePaymentsResponse = res .response .parse_struct("PaymePaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Payme { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/capture-sale", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, )?; let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?; let connector_req = payme::PaymentCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: payme::PaymePaySaleResponse = res .response .parse_struct("Payme PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Payme { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { // for void, same endpoint is used as refund for payme Ok(format!("{}api/refund-sale", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_amount = req.request .minor_amount .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "amount", })?; let req_currency = req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "amount", })?; let amount = utils::convert_amount(self.amount_converter, req_amount, req_currency)?; let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?; let connector_req = payme::PaymeVoidRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: payme::PaymeVoidResponse = res .response .parse_struct("PaymeVoidResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Payme { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/refund-sale", self.base_url(connectors))) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?; let connector_req = payme::PaymeRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundExecuteType::get_headers(self, req, connectors)?) .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: payme::PaymeRefundResponse = res .response .parse_struct("PaymeRefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Payme { fn get_url( &self, _req: &RouterData<RSync, RefundsData, RefundsResponseData>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/get-transactions", self.base_url(connectors))) } fn get_headers( &self, req: &RouterData<RSync, RefundsData, RefundsResponseData>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_request_body( &self, req: &RouterData<RSync, RefundsData, RefundsResponseData>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = payme::PaymeQueryTransactionRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RouterData<RSync, RefundsData, RefundsResponseData>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundSyncType::get_headers(self, req, connectors)?) .set_body(RefundSyncType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RouterData<RSync, RefundsData, RefundsResponseData>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RouterData<RSync, RefundsData, RefundsResponseData>, errors::ConnectorError> where RSync: Clone, RefundsData: Clone, RefundsResponseData: Clone, { let response: payme::PaymeQueryTransactionResponse = res .response .parse_struct("GetSalesResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn get_5xx_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { // we are always getting 500 in error scenarios self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Payme { fn get_webhook_source_verification_algorithm( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::Md5)) } fn get_webhook_source_verification_signature( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let resource = serde_urlencoded::from_bytes::<payme::WebhookEventDataResourceSignature>(request.body) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(resource.payme_signature.expose().into_bytes()) } fn get_webhook_source_verification_message( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let resource = serde_urlencoded::from_bytes::<payme::WebhookEventDataResource>(request.body) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(format!( "{}{}{}", String::from_utf8_lossy(&connector_webhook_secrets.secret), resource.payme_transaction_id, resource.payme_sale_id ) .as_bytes() .to_vec()) } async fn verify_webhook_source( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let algorithm = self .get_webhook_source_verification_algorithm(request) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_label, connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let mut message = self .get_webhook_source_verification_message( request, merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let mut message_to_verify = connector_webhook_secrets .additional_secret .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable("Failed to get additional secrets")? .expose() .as_bytes() .to_vec(); message_to_verify.append(&mut message); let signature_to_verify = hex::decode(signature) .change_context(errors::ConnectorError::WebhookResponseEncodingFailed)?; algorithm .verify_signature( &connector_webhook_secrets.secret, &signature_to_verify, &message_to_verify, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) } fn get_webhook_object_reference_id( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let resource = serde_urlencoded::from_bytes::<payme::WebhookEventDataResource>(request.body) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let id = match resource.notify_type { transformers::NotifyType::SaleComplete | transformers::NotifyType::SaleAuthorized | transformers::NotifyType::SaleFailure | transformers::NotifyType::SaleChargeback | transformers::NotifyType::SaleChargebackRefund => { api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( resource.payme_sale_id, ), ) } transformers::NotifyType::Refund => api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::ConnectorRefundId( resource.payme_transaction_id, ), ), }; Ok(id) } fn get_webhook_event_type( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let resource = serde_urlencoded::from_bytes::<payme::WebhookEventDataResourceEvent>(request.body) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(api_models::webhooks::IncomingWebhookEvent::from( resource.notify_type, )) } fn get_webhook_resource_object( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let resource = serde_urlencoded::from_bytes::<payme::WebhookEventDataResource>(request.body) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; match resource.notify_type { transformers::NotifyType::SaleComplete | transformers::NotifyType::SaleAuthorized | transformers::NotifyType::SaleFailure => { Ok(Box::new(payme::PaymePaySaleResponse::from(resource))) } transformers::NotifyType::Refund => Ok(Box::new( payme::PaymeQueryTransactionResponse::from(resource), )), transformers::NotifyType::SaleChargeback | transformers::NotifyType::SaleChargebackRefund => Ok(Box::new(resource)), } } fn get_dispute_details( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<DisputePayload, errors::ConnectorError> { let webhook_object = serde_urlencoded::from_bytes::<payme::WebhookEventDataResource>(request.body) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(DisputePayload { amount: utils::convert_amount( self.amount_converter_webhooks, webhook_object.price, webhook_object.currency, )?, currency: webhook_object.currency, dispute_stage: api_models::enums::DisputeStage::Dispute, connector_dispute_id: webhook_object.payme_transaction_id, connector_reason: None, connector_reason_code: None, challenge_required_by: None, connector_status: webhook_object.sale_status.to_string(), created_at: None, updated_at: None, }) } } static PAYME_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, enums::CaptureMethod::SequentialAutomatic, ]; let supported_card_network = vec![ common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::DinersClub, common_enums::CardNetwork::Discover, common_enums::CardNetwork::JCB, common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::Visa, ]; let mut payme_supported_payment_methods = SupportedPaymentMethods::new(); payme_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); payme_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); payme_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); payme_supported_payment_methods }); static PAYME_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Payme", description: "Payme is a payment gateway enabling secure online transactions", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Live, }; static PAYME_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [ enums::EventClass::Payments, enums::EventClass::Refunds, enums::EventClass::Disputes, ]; impl ConnectorSpecifications for Payme { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&PAYME_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*PAYME_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&PAYME_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/payme.rs
hyperswitch_connectors::src::connectors::payme
10,523
true
// File: crates/hyperswitch_connectors/src/connectors/xendit.rs // Module: hyperswitch_connectors::src::connectors::xendit pub mod transformers; use std::sync::LazyLock; use api_models::webhooks::IncomingWebhookEvent; use base64::Engine; use common_enums::{enums, CallConnectorAction, CaptureMethod, PaymentAction, PaymentMethodType}; use common_utils::{ consts::BASE64_ENGINE, crypto, errors::CustomResult, ext_traits::{ByteSliceExt, BytesExt}, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{ Authorize, Capture, PSync, PaymentMethodToken, PreProcessing, Session, SetupMandate, Void, }, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, SplitRefundsRequest, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, Response}, webhooks, }; use image::EncodableLayout; use masking::{Mask, PeekInterface}; use transformers::{self as xendit, XenditEventType, XenditWebhookEvent}; use crate::{ constants::headers, types::ResponseRouterData, utils as connector_utils, utils::{self, PaymentMethodDataType, RefundsRequestData}, }; #[derive(Clone)] pub struct Xendit { amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), } impl Xendit { pub fn new() -> &'static Self { &Self { amount_converter: &FloatMajorUnitForConnector, } } } impl api::Payment for Xendit {} impl api::PaymentsPreProcessing for Xendit {} impl api::PaymentSession for Xendit {} impl api::ConnectorAccessToken for Xendit {} impl api::MandateSetup for Xendit {} impl api::PaymentAuthorize for Xendit {} impl api::PaymentSync for Xendit {} impl api::PaymentCapture for Xendit {} impl api::PaymentVoid for Xendit {} impl api::Refund for Xendit {} impl api::RefundExecute for Xendit {} impl api::RefundSync for Xendit {} impl api::PaymentToken for Xendit {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Xendit { } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Xendit where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Xendit { fn id(&self) -> &'static str { "xendit" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.xendit.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = xendit::XenditAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let encoded_api_key = BASE64_ENGINE.encode(format!("{}:", auth.api_key.peek())); Ok(vec![( headers::AUTHORIZATION.to_string(), format!("Basic {encoded_api_key}").into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let error_response: xendit::XenditErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&error_response)); router_env::logger::info!(connector_response=?error_response); Ok(ErrorResponse { code: error_response.error_code.clone(), message: error_response.message.clone(), reason: Some(error_response.message.clone()), status_code: res.status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Xendit { fn build_request( &self, _req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotSupported { message: "Cancel/Void flow".to_string(), connector: "Xendit", } .into()) } } impl ConnectorValidation for Xendit { fn validate_mandate_payment( &self, pm_type: Option<PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]); utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Xendit {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Xendit { //TODO: implement sessions flow } impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Xendit {} impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Xendit { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut headers = self.build_headers(req, connectors)?; match &req.request.split_payments { Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::MultipleSplits(_), )) => { if let Ok(PaymentsResponseData::TransactionResponse { charges: Some(common_types::payments::ConnectorChargeResponseData::XenditSplitPayment( common_types::payments::XenditChargeResponseData::MultipleSplits( xendit_response, ), )), .. }) = req.response.as_ref() { headers.push(( xendit::auth_headers::WITH_SPLIT_RULE.to_string(), xendit_response.split_rule_id.clone().into(), )); if let Some(for_user_id) = &xendit_response.for_user_id { headers.push(( xendit::auth_headers::FOR_USER_ID.to_string(), for_user_id.clone().into(), )) }; }; } Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::SingleSplit(single_split_data), )) => { headers.push(( xendit::auth_headers::FOR_USER_ID.to_string(), single_split_data.for_user_id.clone().into(), )); } _ => (), }; Ok(headers) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/payment_requests", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = xendit::XenditRouterData::from((amount, req)); let connector_req = xendit::XenditPaymentsRequest::try_from(connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: xendit::XenditPaymentResponse = res .response .parse_struct("XenditPaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let response_integrity_object = connector_utils::get_authorise_integrity_object( self.amount_converter, response.amount, response.currency.to_string().clone(), )?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed); new_router_data.map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> for Xendit { fn get_headers( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/split_rules", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsPreProcessingRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = xendit::XenditSplitRequestData::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let req = Some( RequestBuilder::new() .method(Method::Post) .attach_default_headers() .headers(types::PaymentsPreProcessingType::get_headers( self, req, connectors, )?) .url(&types::PaymentsPreProcessingType::get_url( self, req, connectors, )?) .set_body(types::PaymentsPreProcessingType::get_request_body( self, req, connectors, )?) .build(), ); Ok(req) } fn handle_response( &self, data: &PaymentsPreProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: xendit::XenditSplitResponse = res .response .parse_struct("XenditSplitResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Xendit { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut headers = self.build_headers(req, connectors)?; match &req.request.split_payments { Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::MultipleSplits(xendit_request), )) => { if let Some(for_user_id) = &xendit_request.for_user_id { headers.push(( xendit::auth_headers::FOR_USER_ID.to_string(), for_user_id.clone().into(), )) }; } Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::SingleSplit(single_split_data), )) => { headers.push(( xendit::auth_headers::FOR_USER_ID.to_string(), single_split_data.for_user_id.clone().into(), )); } _ => (), }; Ok(headers) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; Ok(format!( "{}/payment_requests/{connector_payment_id}", self.base_url(connectors), )) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: xendit::XenditResponse = res .response .clone() .parse_struct("xendit XenditResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let response_integrity_object = match response.clone() { xendit::XenditResponse::Payment(p) => connector_utils::get_sync_integrity_object( self.amount_converter, p.amount, p.currency.to_string().clone(), ), xendit::XenditResponse::Webhook(p) => connector_utils::get_sync_integrity_object( self.amount_converter, p.data.amount, p.data.currency.to_string().clone(), ), }; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }); new_router_data.and_then(|mut router_data| { let integrity_object = response_integrity_object?; router_data.request.integrity_object = Some(integrity_object); Ok(router_data) }) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Xendit { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut headers = self.build_headers(req, connectors)?; match &req.request.split_payments { Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::MultipleSplits(xendit_request), )) => { if let Some(for_user_id) = &xendit_request.for_user_id { headers.push(( xendit::auth_headers::FOR_USER_ID.to_string(), for_user_id.clone().into(), )) }; } Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::SingleSplit(single_split_data), )) => { headers.push(( xendit::auth_headers::FOR_USER_ID.to_string(), single_split_data.for_user_id.clone().into(), )); } _ => (), }; Ok(headers) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}/payment_requests/{connector_payment_id}/captures", self.base_url(connectors), )) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount_to_capture = utils::convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, )?; let authorized_amount = utils::convert_amount( self.amount_converter, req.request.minor_payment_amount, req.request.currency, )?; if amount_to_capture != authorized_amount { Err(report!(errors::ConnectorError::NotSupported { message: "Partial Capture".to_string(), connector: "Xendit" })) } else { let connector_router_data = xendit::XenditRouterData::from((amount_to_capture, req)); let connector_req = xendit::XenditPaymentsCaptureRequest::try_from(connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) .set_body(self.get_request_body(req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: xendit::XenditCaptureResponse = res .response .parse_struct("Xendit PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Xendit { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut headers = self.build_headers(req, connectors)?; if let Some(SplitRefundsRequest::XenditSplitRefund(sub_merchant_data)) = &req.request.split_refunds { headers.push(( xendit::auth_headers::FOR_USER_ID.to_string(), sub_merchant_data.for_user_id.clone().into(), )); }; Ok(headers) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/refunds", self.base_url(connectors),)) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = xendit::XenditRouterData::from((amount, req)); let connector_req = xendit::XenditRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: xendit::RefundResponse = res.response .parse_struct("xendit RefundResponse") .change_context(errors::ConnectorError::RequestEncodingFailed)?; let response_integrity_object = connector_utils::get_refund_integrity_object( self.amount_converter, response.amount, response.currency.to_string().clone(), )?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }); new_router_data .map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Xendit { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut headers = self.build_headers(req, connectors)?; if let Some(SplitRefundsRequest::XenditSplitRefund(sub_merchant_data)) = &req.request.split_refunds { headers.push(( xendit::auth_headers::FOR_USER_ID.to_string(), sub_merchant_data.for_user_id.clone().into(), )); }; Ok(headers) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_refund_id = req.request.get_connector_refund_id()?; Ok(format!( "{}/refunds/{}", self.base_url(connectors), connector_refund_id )) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: xendit::RefundResponse = res .response .clone() .parse_struct("xendit RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let response_integrity_object = connector_utils::get_refund_integrity_object( self.amount_converter, response.amount, response.currency.to_string().clone(), )?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }); new_router_data .map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Xendit { fn get_webhook_source_verification_signature( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let header_value = utils::get_header_key_value("X-CALLBACK-TOKEN", request.headers)?; Ok(header_value.into()) } async fn verify_webhook_source( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<masking::Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_label, connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let secret_key = connector_webhook_secrets.secret; Ok(secret_key.as_bytes() == (signature).as_bytes()) } fn get_webhook_source_verification_message( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { Ok(request.body.to_vec()) } fn get_webhook_object_reference_id( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let details: XenditWebhookEvent = request .body .parse_struct("XenditWebhookEvent") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; match details.event { XenditEventType::PaymentSucceeded | XenditEventType::PaymentAwaitingCapture | XenditEventType::PaymentFailed | XenditEventType::CaptureSucceeded | XenditEventType::CaptureFailed => { Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( details .data .payment_request_id .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, ), )) } } } fn get_webhook_event_type( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { let body: XenditWebhookEvent = request .body .parse_struct("XenditWebhookEvent") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; match body.event { XenditEventType::PaymentSucceeded => Ok(IncomingWebhookEvent::PaymentIntentSuccess), XenditEventType::CaptureSucceeded => { Ok(IncomingWebhookEvent::PaymentIntentCaptureSuccess) } XenditEventType::PaymentAwaitingCapture => { Ok(IncomingWebhookEvent::PaymentIntentAuthorizationSuccess) } XenditEventType::PaymentFailed | XenditEventType::CaptureFailed => { Ok(IncomingWebhookEvent::PaymentIntentFailure) } } } fn get_webhook_resource_object( &self, request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let body: XenditWebhookEvent = request .body .parse_struct("XenditWebhookEvent") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(Box::new(body)) } } static XENDIT_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![CaptureMethod::Automatic, CaptureMethod::Manual]; let supported_card_network = vec![ common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::Visa, common_enums::CardNetwork::Interac, common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::JCB, common_enums::CardNetwork::DinersClub, common_enums::CardNetwork::Discover, common_enums::CardNetwork::CartesBancaires, common_enums::CardNetwork::UnionPay, ]; let mut xendit_supported_payment_methods = SupportedPaymentMethods::new(); xendit_supported_payment_methods.add( enums::PaymentMethod::Card, PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); xendit_supported_payment_methods.add( enums::PaymentMethod::Card, PaymentMethodType::Debit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); xendit_supported_payment_methods }); static XENDIT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Xendit", description: "Xendit is a financial technology company that provides payment solutions and simplifies the payment process for businesses in Indonesia, the Philippines and Southeast Asia, from SMEs and e-commerce startups to large enterprises.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Sandbox, }; static XENDIT_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; impl ConnectorSpecifications for Xendit { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&XENDIT_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*XENDIT_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&XENDIT_SUPPORTED_WEBHOOK_FLOWS) } } impl ConnectorRedirectResponse for Xendit { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, action: PaymentAction, ) -> CustomResult<CallConnectorAction, errors::ConnectorError> { match action { PaymentAction::PSync | PaymentAction::PaymentAuthenticateCompleteAuthorize | PaymentAction::CompleteAuthorize => Ok(CallConnectorAction::Trigger), } } }
crates/hyperswitch_connectors/src/connectors/xendit.rs
hyperswitch_connectors::src::connectors::xendit
8,125
true