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_connectors/src/connectors/nomupay/transformers.rs // Module: hyperswitch_connectors::src::connectors::nomupay::transformers #[cfg(feature = "payouts")] use common_enums::enums::PayoutEntityType; use common_enums::{enums, Currency, PayoutStatus}; use common_utils::{pii::Email, types::FloatMajorUnit}; use hyperswitch_domain_models::router_data::ConnectorAuthType; #[cfg(feature = "payouts")] use hyperswitch_domain_models::{ router_response_types::PayoutsResponseData, types::PayoutsRouterData, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; #[cfg(feature = "payouts")] use crate::utils::PayoutFulfillRequestData; #[cfg(feature = "payouts")] use crate::{types::PayoutsResponseRouterData, utils::RouterData as UtilsRouterData}; pub const PURPOSE_OF_PAYMENT_IS_OTHER: &str = "OTHER"; pub struct NomupayRouterData<T> { pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for NomupayRouterData<T> { fn from((amount, item): (FloatMajorUnit, T)) -> Self { //Todo : use utils to convert the amount to the type of amount that a connector accepts Self { amount, router_data: item, } } } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Address { pub country: enums::CountryAlpha2, pub state_province: Secret<String>, pub street: Secret<String>, pub city: String, pub postal_code: Secret<String>, } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum ProfileType { #[default] Individual, Businness, } #[cfg(feature = "payouts")] impl From<PayoutEntityType> for ProfileType { fn from(entity: PayoutEntityType) -> Self { match entity { PayoutEntityType::Personal | PayoutEntityType::NaturalPerson | PayoutEntityType::Individual => Self::Individual, _ => Self::Businness, } } } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] pub enum NomupayGender { Male, Female, #[default] Other, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Profile { pub profile_type: ProfileType, pub first_name: Secret<String>, pub last_name: Secret<String>, pub date_of_birth: Secret<String>, pub gender: NomupayGender, pub email_address: Email, pub phone_number_country_code: Option<String>, pub phone_number: Option<Secret<String>>, pub address: Address, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct OnboardSubAccountRequest { pub account_id: Secret<String>, pub client_sub_account_id: Secret<String>, pub profile: Profile, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct BankAccount { pub bank_id: Option<Secret<String>>, pub account_id: Secret<String>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct VirtualAccountsType { pub country_code: String, pub currency_code: String, pub bank_id: Secret<String>, pub bank_account_id: Secret<String>, } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TransferMethodType { #[default] BankAccount, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct OnboardTransferMethodRequest { pub country_code: enums::CountryAlpha2, pub currency_code: Currency, #[serde(rename = "type")] pub transfer_method_type: TransferMethodType, pub display_name: Secret<String>, pub bank_account: BankAccount, pub profile: Profile, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct NomupayPaymentRequest { pub source_id: Secret<String>, pub destination_id: Secret<String>, pub payment_reference: String, pub amount: FloatMajorUnit, pub currency_code: Currency, pub purpose: String, pub description: Option<String>, pub internal_memo: Option<String>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct QuoteRequest { pub source_id: Secret<String>, pub source_currency_code: Currency, pub destination_currency_code: Currency, pub amount: FloatMajorUnit, pub include_fee: String, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct CommitRequest { pub source_id: Secret<String>, pub id: String, pub destination_id: Secret<String>, pub payment_reference: String, pub amount: FloatMajorUnit, pub currency_code: Currency, pub purpose: String, pub description: String, pub internal_memo: String, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct OnboardSubAccountResponse { pub account_id: Secret<String>, pub id: String, pub client_sub_account_id: Secret<String>, pub profile: Profile, pub virtual_accounts: Vec<VirtualAccountsType>, pub status: String, pub created_on: String, pub last_updated: String, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct OnboardTransferMethodResponse { pub parent_id: Secret<String>, pub account_id: Secret<String>, pub sub_account_id: Secret<String>, pub id: String, pub status: String, pub created_on: String, pub last_updated: String, pub country_code: String, pub currency_code: Currency, pub display_name: String, #[serde(rename = "type")] pub transfer_method_type: String, pub profile: Profile, pub bank_account: BankAccount, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct NomupayPaymentResponse { pub id: String, pub status: NomupayPaymentStatus, pub created_on: String, pub last_updated: String, pub source_id: Secret<String>, pub destination_id: Secret<String>, pub payment_reference: String, pub amount: FloatMajorUnit, pub currency_code: String, pub purpose: String, pub description: String, pub internal_memo: String, pub release_on: String, pub expire_on: String, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct FeesType { #[serde(rename = "type")] pub fees_type: String, pub fees: FloatMajorUnit, pub currency_code: Currency, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct PayoutQuoteResponse { pub source_id: Secret<String>, pub destination_currency_code: Currency, pub amount: FloatMajorUnit, pub source_currency_code: Currency, pub include_fee: bool, pub fees: Vec<FeesType>, pub payment_reference: String, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct CommitResponse { pub id: String, pub status: String, pub created_on: String, pub last_updated: String, pub source_id: Secret<String>, pub destination_id: Secret<String>, pub payment_reference: String, pub amount: FloatMajorUnit, pub currency_code: Currency, pub purpose: String, pub description: String, pub internal_memo: String, pub release_on: String, pub expire_on: String, } #[derive(Serialize, Deserialize, Debug)] pub struct NomupayMetadata { pub private_key: Secret<String>, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct ValidationError { pub field: String, pub message: String, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DetailsType { pub loc: Vec<String>, #[serde(rename = "type")] pub error_type: String, } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct NomupayInnerError { pub error_code: String, pub error_description: Option<String>, pub validation_errors: Option<Vec<ValidationError>>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct NomupayErrorResponse { pub status: Option<String>, pub code: Option<u64>, pub error: Option<NomupayInnerError>, pub status_code: Option<u16>, pub detail: Option<Vec<DetailsType>>, } pub struct NomupayAuthType { pub(super) kid: Secret<String>, #[cfg(feature = "payouts")] pub(super) eid: Secret<String>, } impl TryFrom<&ConnectorAuthType> for NomupayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { #[cfg(feature = "payouts")] ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { kid: api_key.to_owned(), eid: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum NomupayPaymentStatus { Pending, Processed, Failed, #[default] Processing, Scheduled, PendingAccountActivation, PendingTransferMethodCreation, PendingAccountKyc, } impl From<NomupayPaymentStatus> for PayoutStatus { fn from(item: NomupayPaymentStatus) -> Self { match item { NomupayPaymentStatus::Processed => Self::Success, NomupayPaymentStatus::Failed => Self::Failed, NomupayPaymentStatus::Processing | NomupayPaymentStatus::Pending | NomupayPaymentStatus::Scheduled | NomupayPaymentStatus::PendingAccountActivation | NomupayPaymentStatus::PendingTransferMethodCreation | NomupayPaymentStatus::PendingAccountKyc => Self::Pending, } } } #[cfg(feature = "payouts")] fn get_profile<F>( item: &PayoutsRouterData<F>, entity_type: PayoutEntityType, ) -> Result<Profile, error_stack::Report<errors::ConnectorError>> { let my_address = Address { country: item.get_billing_country()?, state_province: item.get_billing_state()?, street: item.get_billing_line1()?, city: item.get_billing_city()?, postal_code: item.get_billing_zip()?, }; Ok(Profile { profile_type: ProfileType::from(entity_type), first_name: item.get_billing_first_name()?, last_name: item.get_billing_last_name()?, date_of_birth: Secret::new("1991-01-01".to_string()), // Query raised with Nomupay regarding why this field is required gender: NomupayGender::Other, // Query raised with Nomupay regarding why this field is required email_address: item.get_billing_email()?, phone_number_country_code: item .get_billing_phone() .map(|phone| phone.country_code.clone())?, phone_number: Some(item.get_billing_phone_number()?), address: my_address, }) } // PoRecipient Request #[cfg(feature = "payouts")] impl<F> TryFrom<&PayoutsRouterData<F>> for OnboardSubAccountRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let payout_type = request.payout_type; let profile = get_profile(item, request.entity_type)?; let nomupay_auth_type = NomupayAuthType::try_from(&item.connector_auth_type)?; match payout_type { Some(common_enums::PayoutType::Bank) => Ok(Self { account_id: nomupay_auth_type.eid, client_sub_account_id: Secret::new(item.connector_request_reference_id.clone()), profile, }), _ => Err(errors::ConnectorError::NotImplemented( "This payment method is not implemented for Nomupay".to_string(), ) .into()), } } } // PoRecipient Response #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, OnboardSubAccountResponse>> for PayoutsRouterData<F> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PayoutsResponseRouterData<F, OnboardSubAccountResponse>, ) -> Result<Self, Self::Error> { let response: OnboardSubAccountResponse = item.response; Ok(Self { response: Ok(PayoutsResponseData { status: Some(PayoutStatus::RequiresVendorAccountCreation), connector_payout_id: Some(response.id.to_string()), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } // PoRecipientAccount Request #[cfg(feature = "payouts")] impl<F> TryFrom<&PayoutsRouterData<F>> for OnboardTransferMethodRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let payout_method_data = item.get_payout_method_data()?; match payout_method_data { api_models::payouts::PayoutMethodData::Bank(bank) => match bank { api_models::payouts::Bank::Sepa(bank_details) => { let bank_account = BankAccount { bank_id: bank_details.bic, account_id: bank_details.iban, }; let country_iso2_code = item .get_billing_country() .unwrap_or(enums::CountryAlpha2::CA); let profile = get_profile(item, item.request.entity_type)?; Ok(Self { country_code: country_iso2_code, currency_code: item.request.destination_currency, transfer_method_type: TransferMethodType::BankAccount, display_name: item.get_billing_full_name()?, bank_account, profile, }) } other_bank => Err(errors::ConnectorError::NotSupported { message: format!("{other_bank:?} is not supported"), connector: "nomupay", } .into()), }, _ => Err(errors::ConnectorError::NotImplemented( "This payment method is not implemented for Nomupay".to_string(), ) .into()), } } } // PoRecipientAccount response #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, OnboardTransferMethodResponse>> for PayoutsRouterData<F> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PayoutsResponseRouterData<F, OnboardTransferMethodResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PayoutsResponseData { status: Some(PayoutStatus::RequiresCreation), connector_payout_id: Some(item.response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } // PoFulfill Request #[cfg(feature = "payouts")] impl<F> TryFrom<(&PayoutsRouterData<F>, FloatMajorUnit)> for NomupayPaymentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, amount): (&PayoutsRouterData<F>, FloatMajorUnit), ) -> Result<Self, Self::Error> { let nomupay_auth_type = NomupayAuthType::try_from(&item.connector_auth_type)?; let destination = item.request.clone().get_connector_transfer_method_id()?; Ok(Self { source_id: nomupay_auth_type.eid, destination_id: Secret::new(destination), payment_reference: item.connector_request_reference_id.clone(), amount, currency_code: item.request.destination_currency, purpose: PURPOSE_OF_PAYMENT_IS_OTHER.to_string(), description: item.description.clone(), internal_memo: item.description.clone(), }) } } // PoFulfill response #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, NomupayPaymentResponse>> for PayoutsRouterData<F> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PayoutsResponseRouterData<F, NomupayPaymentResponse>, ) -> Result<Self, Self::Error> { let response: NomupayPaymentResponse = item.response; Ok(Self { response: Ok(PayoutsResponseData { status: Some(PayoutStatus::from(response.status)), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } }
crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
hyperswitch_connectors::src::connectors::nomupay::transformers
3,959
true
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs // Module: hyperswitch_connectors::src::connectors::wellsfargo::transformers use api_models::payments; use base64::Engine; use common_enums::{enums, FutureUsage}; use common_types::payments::ApplePayPredecryptData; use common_utils::{ consts, pii, types::{SemanticVersion, StringMajorUnit}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{ ApplePayWalletData, BankDebitData, GooglePayWalletData, PaymentMethodData, WalletData, }, router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, ErrorResponse, PaymentMethodToken, RouterData, }, router_flow_types::{ payments::Authorize, refunds::{Execute, RSync}, SetupMandate, }, router_request_types::{ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, ResponseId, SetupMandateRequestData, }, router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsIncrementalAuthorizationRouterData, RefundsRouterData, SetupMandateRouterData, }, }; use hyperswitch_interfaces::{api, errors}; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::{ constants, types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, utils::{ self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData, RouterData as OtherRouterData, }, }; #[derive(Debug, Serialize)] pub struct WellsfargoRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for WellsfargoRouterData<T> { fn from((amount, router_data): (StringMajorUnit, T)) -> Self { Self { amount, router_data, } } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoZeroMandateRequest { processing_information: ProcessingInformation, payment_information: PaymentInformation, order_information: OrderInformationWithBill, client_reference_information: ClientReferenceInformation, } impl TryFrom<&SetupMandateRouterData> for WellsfargoZeroMandateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> { let email = item.request.get_email()?; let bill_to = build_bill_to(item.get_optional_billing(), email)?; let order_information = OrderInformationWithBill { amount_details: Amount { total_amount: StringMajorUnit::zero(), currency: item.request.currency, }, bill_to: Some(bill_to), }; let (action_list, action_token_types, authorization_options) = ( Some(vec![WellsfargoActionsList::TokenCreate]), Some(vec![ WellsfargoActionsTokenType::PaymentInstrument, WellsfargoActionsTokenType::Customer, ]), Some(WellsfargoAuthorizationOptions { initiator: Some(WellsfargoPaymentInitiator { initiator_type: Some(WellsfargoPaymentInitiatorTypes::Customer), credential_stored_on_file: Some(true), stored_credential_used: None, }), merchant_intitiated_transaction: None, }), ); let client_reference_information = ClientReferenceInformation { code: Some(item.connector_request_reference_id.clone()), }; let (payment_information, solution) = match item.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => { let card_issuer = ccard.get_card_issuer(); let card_type = match card_issuer { Ok(issuer) => Some(String::from(issuer)), Err(_) => None, }; ( PaymentInformation::Cards(Box::new(CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: Some(ccard.card_cvc), card_type, }, })), None, ) } PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::ApplePay(apple_pay_data) => match item.payment_method_token.clone() { Some(payment_method_token) => match payment_method_token { PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { let expiration_month = decrypt_data.get_expiry_month().change_context( errors::ConnectorError::InvalidDataFormat { field_name: "expiration_month", }, )?; let expiration_year = decrypt_data.get_four_digit_expiry_year(); ( PaymentInformation::ApplePay(Box::new( ApplePayPaymentInformation { tokenized_card: TokenizedCard { number: decrypt_data.application_primary_account_number, cryptogram: decrypt_data .payment_data .online_payment_cryptogram, transaction_type: TransactionType::ApplePay, expiration_year, expiration_month, }, }, )), Some(PaymentSolution::ApplePay), ) } PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!( "Apple Pay", "Manual", "Wellsfargo" ))?, PaymentMethodToken::PazeDecrypt(_) => { Err(unimplemented_payment_method!("Paze", "Wellsfargo"))? } PaymentMethodToken::GooglePayDecrypt(_) => { Err(unimplemented_payment_method!("Google Pay", "Wellsfargo"))? } }, None => { let apple_pay_encrypted_data = apple_pay_data .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", })?; ( PaymentInformation::ApplePayToken(Box::new( ApplePayTokenPaymentInformation { fluid_data: FluidData { value: Secret::from(apple_pay_encrypted_data.clone()), descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()), }, tokenized_card: ApplePayTokenizedCard { transaction_type: TransactionType::ApplePay, }, }, )), Some(PaymentSolution::ApplePay), ) } }, WalletData::GooglePay(google_pay_data) => ( PaymentInformation::GooglePay(Box::new(GooglePayPaymentInformation { fluid_data: FluidData { value: Secret::from( consts::BASE64_ENGINE.encode( google_pay_data .tokenization_data .get_encrypted_google_pay_token() .change_context( errors::ConnectorError::MissingRequiredField { field_name: "gpay wallet_token", }, )?, ), ), descriptor: None, }, })), Some(PaymentSolution::GooglePay), ), WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::BluecodeRedirect {} | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::AmazonPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wellsfargo"), ))?, }, PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wellsfargo"), ))? } }; let processing_information = ProcessingInformation { capture: Some(false), capture_options: None, action_list, action_token_types, authorization_options, commerce_indicator: String::from("internet"), payment_solution: solution.map(String::from), }; Ok(Self { processing_information, payment_information, order_information, client_reference_information, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoPaymentsRequest { processing_information: ProcessingInformation, payment_information: PaymentInformation, order_information: OrderInformationWithBill, client_reference_information: ClientReferenceInformation, #[serde(skip_serializing_if = "Option::is_none")] consumer_authentication_information: Option<WellsfargoConsumerAuthInformation>, #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProcessingInformation { action_list: Option<Vec<WellsfargoActionsList>>, action_token_types: Option<Vec<WellsfargoActionsTokenType>>, authorization_options: Option<WellsfargoAuthorizationOptions>, commerce_indicator: String, capture: Option<bool>, capture_options: Option<CaptureOptions>, payment_solution: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoConsumerAuthInformation { ucaf_collection_indicator: Option<String>, cavv: Option<Secret<String>>, ucaf_authentication_data: Option<Secret<String>>, xid: Option<String>, directory_server_transaction_id: Option<Secret<String>>, specification_version: Option<String>, /// This field specifies the 3ds version pa_specification_version: Option<SemanticVersion>, /// Verification response enrollment status. /// /// This field is supported only on Asia, Middle East, and Africa Gateway. /// /// For external authentication, this field will always be "Y" veres_enrolled: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantDefinedInformation { key: u8, value: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum WellsfargoActionsList { TokenCreate, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum WellsfargoActionsTokenType { Customer, PaymentInstrument, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoAuthorizationOptions { initiator: Option<WellsfargoPaymentInitiator>, merchant_intitiated_transaction: Option<MerchantInitiatedTransaction>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantInitiatedTransaction { reason: Option<String>, previous_transaction_id: Option<Secret<String>>, //Required for recurring mandates payment original_authorized_amount: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoPaymentInitiator { #[serde(rename = "type")] initiator_type: Option<WellsfargoPaymentInitiatorTypes>, credential_stored_on_file: Option<bool>, stored_credential_used: Option<bool>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum WellsfargoPaymentInitiatorTypes { Customer, Merchant, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CaptureOptions { capture_sequence_number: u32, total_capture_count: u32, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardPaymentInformation { card: Card, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCard { number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, cryptogram: Secret<String>, transaction_type: TransactionType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayTokenizedCard { transaction_type: TransactionType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayTokenPaymentInformation { fluid_data: FluidData, tokenized_card: ApplePayTokenizedCard, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayPaymentInformation { tokenized_card: TokenizedCard, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MandatePaymentInformation { payment_instrument: WellsfargoPaymentInstrument, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct AchBankAccount { account: Account, routing_number: Secret<String>, } #[derive(Debug, Deserialize, Serialize)] struct Account { #[serde(rename = "type")] account_type: AccountType, number: Secret<String>, } #[derive(Debug, Deserialize, Serialize)] enum AccountType { /// Checking account type. C, /// General ledger account type. Supported only on Wells Fargo ACH. G, /// Savings account type. S, /// Corporate checking account type. X, } #[derive(Debug, Serialize)] pub struct AchPaymentInformation { bank: AchBankAccount, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct FluidData { value: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] descriptor: Option<String>, } pub const FLUID_DATA_DESCRIPTOR: &str = "RklEPUNPTU1PTi5BUFBMRS5JTkFQUC5QQVlNRU5U"; #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayPaymentInformation { fluid_data: FluidData, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaymentInformation { Cards(Box<CardPaymentInformation>), GooglePay(Box<GooglePayPaymentInformation>), ApplePay(Box<ApplePayPaymentInformation>), ApplePayToken(Box<ApplePayTokenPaymentInformation>), MandatePayment(Box<MandatePaymentInformation>), AchDebitPayment(Box<AchPaymentInformation>), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct WellsfargoPaymentInstrument { id: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Card { number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, security_code: Option<Secret<String>>, #[serde(rename = "type")] card_type: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformationWithBill { amount_details: Amount, bill_to: Option<BillTo>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformationIncrementalAuthorization { amount_details: AdditionalAmount, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformation { amount_details: Amount, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Amount { total_amount: StringMajorUnit, currency: api_models::enums::Currency, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdditionalAmount { additional_amount: StringMajorUnit, currency: String, } #[derive(Debug, Serialize)] pub enum PaymentSolution { ApplePay, GooglePay, } #[derive(Debug, Serialize)] pub enum TransactionType { #[serde(rename = "1")] ApplePay, } impl From<PaymentSolution> for String { fn from(solution: PaymentSolution) -> Self { let payment_solution = match solution { PaymentSolution::ApplePay => "001", PaymentSolution::GooglePay => "012", }; payment_solution.to_string() } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BillTo { first_name: Option<Secret<String>>, last_name: Option<Secret<String>>, address1: Option<Secret<String>>, locality: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] administrative_area: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] postal_code: Option<Secret<String>>, country: Option<enums::CountryAlpha2>, email: pii::Email, phone_number: Option<Secret<String>>, } impl From<&WellsfargoRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation { fn from(item: &WellsfargoRouterData<&PaymentsAuthorizeRouterData>) -> Self { Self { code: Some(item.router_data.connector_request_reference_id.clone()), } } } impl TryFrom<( &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, Option<PaymentSolution>, Option<String>, )> for ProcessingInformation { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, solution, network): ( &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, Option<PaymentSolution>, Option<String>, ), ) -> Result<Self, Self::Error> { let mut commerce_indicator = solution .as_ref() .map(|pm_solution| match pm_solution { PaymentSolution::ApplePay => network .as_ref() .map(|card_network| match card_network.to_lowercase().as_str() { "amex" => "aesk", "discover" => "dipb", "mastercard" => "spa", "visa" => "internet", _ => "internet", }) .unwrap_or("internet"), PaymentSolution::GooglePay => "internet", }) .unwrap_or("internet") .to_string(); let (action_list, action_token_types, authorization_options) = if item .router_data .request .setup_future_usage == Some(FutureUsage::OffSession) && (item.router_data.request.customer_acceptance.is_some() || item .router_data .request .setup_mandate_details .clone() .is_some_and(|mandate_details| mandate_details.customer_acceptance.is_some())) { ( Some(vec![WellsfargoActionsList::TokenCreate]), Some(vec![ WellsfargoActionsTokenType::PaymentInstrument, WellsfargoActionsTokenType::Customer, ]), Some(WellsfargoAuthorizationOptions { initiator: Some(WellsfargoPaymentInitiator { initiator_type: Some(WellsfargoPaymentInitiatorTypes::Customer), credential_stored_on_file: Some(true), stored_credential_used: None, }), merchant_intitiated_transaction: None, }), ) } else if item.router_data.request.mandate_id.is_some() { match item .router_data .request .mandate_id .clone() .and_then(|mandate_id| mandate_id.mandate_reference_id) { Some(payments::MandateReferenceId::ConnectorMandateId(_)) => { let original_amount = item .router_data .get_recurring_mandate_payment_data()? .get_original_payment_amount()?; let original_currency = item .router_data .get_recurring_mandate_payment_data()? .get_original_payment_currency()?; ( None, None, Some(WellsfargoAuthorizationOptions { initiator: None, merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { reason: None, original_authorized_amount: Some(utils::get_amount_as_string( &api::CurrencyUnit::Base, original_amount, original_currency, )?), previous_transaction_id: None, }), }), ) } Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => { let (original_amount, original_currency) = match network .clone() .map(|network| network.to_lowercase()) .as_deref() { Some("discover") => { let original_amount = Some( item.router_data .get_recurring_mandate_payment_data()? .get_original_payment_amount()?, ); let original_currency = Some( item.router_data .get_recurring_mandate_payment_data()? .get_original_payment_currency()?, ); (original_amount, original_currency) } _ => { let original_amount = item .router_data .recurring_mandate_payment_data .as_ref() .and_then(|recurring_mandate_payment_data| { recurring_mandate_payment_data .original_payment_authorized_amount }); let original_currency = item .router_data .recurring_mandate_payment_data .as_ref() .and_then(|recurring_mandate_payment_data| { recurring_mandate_payment_data .original_payment_authorized_currency }); (original_amount, original_currency) } }; let original_authorized_amount = match (original_amount, original_currency) { (Some(original_amount), Some(original_currency)) => Some( utils::to_currency_base_unit(original_amount, original_currency)?, ), _ => None, }; commerce_indicator = "recurring".to_string(); ( None, None, Some(WellsfargoAuthorizationOptions { initiator: Some(WellsfargoPaymentInitiator { initiator_type: Some(WellsfargoPaymentInitiatorTypes::Merchant), credential_stored_on_file: None, stored_credential_used: Some(true), }), merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { reason: Some("7".to_string()), original_authorized_amount, previous_transaction_id: Some(Secret::new(network_transaction_id)), }), }), ) } Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) | None => { (None, None, None) } } } else { (None, None, None) }; // this logic is for external authenticated card let commerce_indicator_for_external_authentication = item .router_data .request .authentication_data .as_ref() .and_then(|authn_data| { authn_data .eci .clone() .map(|eci| get_commerce_indicator_for_external_authentication(network, eci)) }); Ok(Self { capture: Some(matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic) | None )), payment_solution: solution.map(String::from), action_list, action_token_types, authorization_options, capture_options: None, commerce_indicator: commerce_indicator_for_external_authentication .unwrap_or(commerce_indicator), }) } } fn get_commerce_indicator_for_external_authentication( card_network: Option<String>, eci: String, ) -> String { let card_network_lower_case = card_network .as_ref() .map(|card_network| card_network.to_lowercase()); match eci.as_str() { "00" | "01" | "02" => { if matches!( card_network_lower_case.as_deref(), Some("mastercard") | Some("maestro") ) { "spa" } else { "internet" } } "05" => match card_network_lower_case.as_deref() { Some("amex") => "aesk", Some("discover") => "dipb", Some("mastercard") => "spa", Some("visa") => "vbv", Some("diners") => "pb", Some("upi") => "up3ds", _ => "internet", }, "06" => match card_network_lower_case.as_deref() { Some("amex") => "aesk_attempted", Some("discover") => "dipb_attempted", Some("mastercard") => "spa", Some("visa") => "vbv_attempted", Some("diners") => "pb_attempted", Some("upi") => "up3ds_attempted", _ => "internet", }, "07" => match card_network_lower_case.as_deref() { Some("amex") => "internet", Some("discover") => "internet", Some("mastercard") => "spa", Some("visa") => "vbv_failure", Some("diners") => "internet", Some("upi") => "up3ds_failure", _ => "internet", }, _ => "vbv_failure", } .to_string() } impl From<( &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, Option<BillTo>, )> for OrderInformationWithBill { fn from( (item, bill_to): ( &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, Option<BillTo>, ), ) -> Self { Self { amount_details: Amount { total_amount: item.amount.to_owned(), currency: item.router_data.request.currency, }, bill_to, } } } fn get_phone_number( item: Option<&hyperswitch_domain_models::address::Address>, ) -> Option<Secret<String>> { item.as_ref() .and_then(|billing| billing.phone.as_ref()) .and_then(|phone| { phone.number.as_ref().and_then(|number| { phone .country_code .as_ref() .map(|cc| Secret::new(format!("{}{}", cc, number.peek()))) }) }) } fn build_bill_to( address_details: Option<&hyperswitch_domain_models::address::Address>, email: pii::Email, ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { let phone_number = get_phone_number(address_details); let default_address = BillTo { first_name: None, last_name: None, address1: None, locality: None, administrative_area: None, postal_code: None, country: None, email: email.clone(), phone_number: phone_number.clone(), }; let ad = Ok(address_details .and_then(|addr| { addr.address.as_ref().map(|addr| BillTo { first_name: addr.first_name.clone(), last_name: addr.last_name.clone(), address1: addr.line1.clone(), locality: addr.city.clone(), administrative_area: addr.to_state_code_as_optional().ok().flatten(), postal_code: addr.zip.clone(), country: addr.country, email, phone_number: phone_number.clone(), }) }) .unwrap_or(default_address)); ad } fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> { let hashmap: std::collections::BTreeMap<String, Value> = serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new()); let mut vector = Vec::new(); let mut iter = 1; for (key, value) in hashmap { vector.push(MerchantDefinedInformation { key: iter, value: format!("{key}={value}"), }); iter += 1; } vector } impl TryFrom<( &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, hyperswitch_domain_models::payment_method_data::Card, )> for WellsfargoPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, ccard): ( &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, hyperswitch_domain_models::payment_method_data::Card, ), ) -> Result<Self, Self::Error> { let email = item.router_data.request.get_email()?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let card_issuer = ccard.get_card_issuer(); let card_type = match card_issuer { Ok(issuer) => Some(String::from(issuer)), Err(_) => None, }; let payment_information = PaymentInformation::Cards(Box::new(CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: Some(ccard.card_cvc), card_type: card_type.clone(), }, })); let processing_information = ProcessingInformation::try_from((item, None, card_type))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); let consumer_authentication_information = item .router_data .request .authentication_data .as_ref() .map(|authn_data| { let (ucaf_authentication_data, cavv) = if ccard.card_network == Some(common_enums::CardNetwork::Mastercard) { (Some(authn_data.cavv.clone()), None) } else { (None, Some(authn_data.cavv.clone())) }; WellsfargoConsumerAuthInformation { ucaf_collection_indicator: None, cavv, ucaf_authentication_data, xid: authn_data.threeds_server_transaction_id.clone(), directory_server_transaction_id: authn_data .ds_trans_id .clone() .map(Secret::new), specification_version: None, pa_specification_version: authn_data.message_version.clone(), veres_enrolled: Some("Y".to_string()), } }); Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information, merchant_defined_information, }) } } impl TryFrom<( &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, Box<ApplePayPredecryptData>, ApplePayWalletData, )> for WellsfargoPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, apple_pay_data, apple_pay_wallet_data): ( &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, Box<ApplePayPredecryptData>, ApplePayWalletData, ), ) -> Result<Self, Self::Error> { let email = item.router_data.request.get_email()?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = ProcessingInformation::try_from(( item, Some(PaymentSolution::ApplePay), Some(apple_pay_wallet_data.payment_method.network.clone()), ))?; let client_reference_information = ClientReferenceInformation::from(item); let expiration_month = apple_pay_data.get_expiry_month().change_context( errors::ConnectorError::InvalidDataFormat { field_name: "expiration_month", }, )?; let expiration_year = apple_pay_data.get_four_digit_expiry_year(); let payment_information = PaymentInformation::ApplePay(Box::new(ApplePayPaymentInformation { tokenized_card: TokenizedCard { number: apple_pay_data.application_primary_account_number, cryptogram: apple_pay_data.payment_data.online_payment_cryptogram, transaction_type: TransactionType::ApplePay, expiration_year, expiration_month, }, })); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); let ucaf_collection_indicator = match apple_pay_wallet_data .payment_method .network .to_lowercase() .as_str() { "mastercard" => Some("2".to_string()), _ => None, }; Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information: Some(WellsfargoConsumerAuthInformation { ucaf_collection_indicator, cavv: None, ucaf_authentication_data: None, xid: None, directory_server_transaction_id: None, specification_version: None, pa_specification_version: None, veres_enrolled: None, }), merchant_defined_information, }) } } impl TryFrom<( &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, GooglePayWalletData, )> for WellsfargoPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, google_pay_data): ( &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, GooglePayWalletData, ), ) -> Result<Self, Self::Error> { let email = item.router_data.request.get_email()?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = PaymentInformation::GooglePay(Box::new(GooglePayPaymentInformation { fluid_data: FluidData { value: Secret::from( consts::BASE64_ENGINE.encode( google_pay_data .tokenization_data .get_encrypted_google_pay_token() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "gpay wallet_token", })?, ), ), descriptor: None, }, })); let processing_information = ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information: None, merchant_defined_information, }) } } impl TryFrom<Option<common_enums::BankType>> for AccountType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(optional_bank_type: Option<common_enums::BankType>) -> Result<Self, Self::Error> { match optional_bank_type { None => Err(errors::ConnectorError::MissingRequiredField { field_name: "bank_type", })?, Some(bank_type) => match bank_type { common_enums::BankType::Checking => Ok(Self::C), common_enums::BankType::Savings => Ok(Self::S), }, } } } impl TryFrom<( &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, BankDebitData, )> for WellsfargoPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, bank_debit_data): ( &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, BankDebitData, ), ) -> Result<Self, Self::Error> { let email = item.router_data.request.get_email()?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = match bank_debit_data { BankDebitData::AchBankDebit { account_number, routing_number, bank_type, .. } => Ok(PaymentInformation::AchDebitPayment(Box::new( AchPaymentInformation { bank: AchBankAccount { account: Account { account_type: AccountType::try_from(bank_type)?, number: account_number, }, routing_number, }, }, ))), BankDebitData::SepaBankDebit { .. } | BankDebitData::BacsBankDebit { .. } | BankDebitData::BecsBankDebit { .. } | BankDebitData::SepaGuarenteedBankDebit { .. } => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wellsfargo"), )) } }?; let processing_information = ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?; let client_reference_information = ClientReferenceInformation::from(item); Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information: None, merchant_defined_information: None, }) } } impl TryFrom<&WellsfargoRouterData<&PaymentsAuthorizeRouterData>> for WellsfargoPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &WellsfargoRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.connector_mandate_id() { Some(connector_mandate_id) => Self::try_from((item, connector_mandate_id)), None => { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::ApplePay(apple_pay_data) => { match item.router_data.payment_method_token.clone() { Some(payment_method_token) => match payment_method_token { PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { Self::try_from((item, decrypt_data, apple_pay_data)) } PaymentMethodToken::Token(_) => { Err(unimplemented_payment_method!( "Apple Pay", "Manual", "Wellsfargo" ))? } PaymentMethodToken::PazeDecrypt(_) => { Err(unimplemented_payment_method!("Paze", "Wellsfargo"))? } PaymentMethodToken::GooglePayDecrypt(_) => Err( unimplemented_payment_method!("Google Pay", "Wellsfargo"), )?, }, None => { let email = item.router_data.request.get_email()?; let bill_to = build_bill_to( item.router_data.get_optional_billing(), email, )?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = ProcessingInformation::try_from(( item, Some(PaymentSolution::ApplePay), Some(apple_pay_data.payment_method.network.clone()), ))?; let client_reference_information = ClientReferenceInformation::from(item); let apple_pay_encrypted_data = apple_pay_data .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context( errors::ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", }, )?; let payment_information = PaymentInformation::ApplePayToken( Box::new(ApplePayTokenPaymentInformation { fluid_data: FluidData { value: Secret::from( apple_pay_encrypted_data.to_string(), ), descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()), }, tokenized_card: ApplePayTokenizedCard { transaction_type: TransactionType::ApplePay, }, }), ); let merchant_defined_information = item.router_data.request.metadata.clone().map(|metadata| { convert_metadata_to_merchant_defined_info(metadata) }); let ucaf_collection_indicator = match apple_pay_data .payment_method .network .to_lowercase() .as_str() { "mastercard" => Some("2".to_string()), _ => None, }; Ok(Self { processing_information, payment_information, order_information, client_reference_information, merchant_defined_information, consumer_authentication_information: Some( WellsfargoConsumerAuthInformation { ucaf_collection_indicator, cavv: None, ucaf_authentication_data: None, xid: None, directory_server_transaction_id: None, specification_version: None, pa_specification_version: None, veres_enrolled: None, }, ), }) } } } WalletData::GooglePay(google_pay_data) => { Self::try_from((item, google_pay_data)) } WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::BluecodeRedirect {} | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::AmazonPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wellsfargo"), ) .into()), }, // If connector_mandate_id is present MandatePayment will be the PMD, the case will be handled in the first `if` clause. // This is a fallback implementation in the event of catastrophe. PaymentMethodData::MandatePayment => { let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "connector_mandate_id", }, )?; Self::try_from((item, connector_mandate_id)) } PaymentMethodData::BankDebit(bank_debit) => Self::try_from((item, bank_debit)), PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wellsfargo"), ) .into()) } } } } } } impl TryFrom<(&WellsfargoRouterData<&PaymentsAuthorizeRouterData>, String)> for WellsfargoPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, connector_mandate_id): (&WellsfargoRouterData<&PaymentsAuthorizeRouterData>, String), ) -> Result<Self, Self::Error> { let processing_information = ProcessingInformation::try_from((item, None, None))?; let payment_instrument = WellsfargoPaymentInstrument { id: connector_mandate_id.into(), }; let bill_to = item.router_data.request.get_email().ok().and_then(|email| { build_bill_to(item.router_data.get_optional_billing(), email).ok() }); let order_information = OrderInformationWithBill::from((item, bill_to)); let payment_information = PaymentInformation::MandatePayment(Box::new(MandatePaymentInformation { payment_instrument, })); let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { processing_information, payment_information, order_information, client_reference_information, merchant_defined_information, consumer_authentication_information: None, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoPaymentsCaptureRequest { processing_information: ProcessingInformation, order_information: OrderInformationWithBill, client_reference_information: ClientReferenceInformation, #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoPaymentsIncrementalAuthorizationRequest { processing_information: ProcessingInformation, order_information: OrderInformationIncrementalAuthorization, } impl TryFrom<&WellsfargoRouterData<&PaymentsCaptureRouterData>> for WellsfargoPaymentsCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &WellsfargoRouterData<&PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { processing_information: ProcessingInformation { capture_options: Some(CaptureOptions { capture_sequence_number: 1, total_capture_count: 1, }), action_list: None, action_token_types: None, authorization_options: None, capture: None, commerce_indicator: String::from("internet"), payment_solution: None, }, order_information: OrderInformationWithBill { amount_details: Amount { total_amount: item.amount.clone(), currency: item.router_data.request.currency, }, bill_to: None, }, client_reference_information: ClientReferenceInformation { code: Some(item.router_data.connector_request_reference_id.clone()), }, merchant_defined_information, }) } } impl TryFrom<&WellsfargoRouterData<&PaymentsIncrementalAuthorizationRouterData>> for WellsfargoPaymentsIncrementalAuthorizationRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &WellsfargoRouterData<&PaymentsIncrementalAuthorizationRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { processing_information: ProcessingInformation { action_list: None, action_token_types: None, authorization_options: Some(WellsfargoAuthorizationOptions { initiator: Some(WellsfargoPaymentInitiator { initiator_type: None, credential_stored_on_file: None, stored_credential_used: Some(true), }), merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { reason: Some("5".to_owned()), previous_transaction_id: None, original_authorized_amount: None, }), }), commerce_indicator: String::from("internet"), capture: None, capture_options: None, payment_solution: None, }, order_information: OrderInformationIncrementalAuthorization { amount_details: AdditionalAmount { additional_amount: item.amount.clone(), currency: item.router_data.request.currency.to_string(), }, }, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoVoidRequest { client_reference_information: ClientReferenceInformation, reversal_information: ReversalInformation, #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, // The connector documentation does not mention the merchantDefinedInformation field for Void requests. But this has been still added because it works! } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ReversalInformation { amount_details: Amount, reason: String, } impl TryFrom<&WellsfargoRouterData<&PaymentsCancelRouterData>> for WellsfargoVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( value: &WellsfargoRouterData<&PaymentsCancelRouterData>, ) -> Result<Self, Self::Error> { let merchant_defined_information = value .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { client_reference_information: ClientReferenceInformation { code: Some(value.router_data.connector_request_reference_id.clone()), }, reversal_information: ReversalInformation { amount_details: Amount { total_amount: value.amount.to_owned(), currency: value.router_data.request.currency.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "Currency", }, )?, }, reason: value .router_data .request .cancellation_reason .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "Cancellation Reason", })?, }, merchant_defined_information, }) } } pub struct WellsfargoAuthType { pub(super) api_key: Secret<String>, pub(super) merchant_account: Secret<String>, pub(super) api_secret: Secret<String>, } impl TryFrom<&ConnectorAuthType> for WellsfargoAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } = auth_type { Ok(Self { api_key: api_key.to_owned(), merchant_account: key1.to_owned(), api_secret: api_secret.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum WellsfargoPaymentStatus { Authorized, Succeeded, Failed, Voided, Reversed, Pending, Declined, Rejected, Challenge, AuthorizedPendingReview, AuthorizedRiskDeclined, Transmitted, InvalidRequest, ServerError, PendingAuthentication, PendingReview, Accepted, Cancelled, StatusNotReceived, //PartialAuthorized, not being consumed yet. } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum WellsfargoIncrementalAuthorizationStatus { Authorized, Declined, AuthorizedPendingReview, } fn map_attempt_status(status: WellsfargoPaymentStatus, capture: bool) -> enums::AttemptStatus { match status { WellsfargoPaymentStatus::Authorized | WellsfargoPaymentStatus::AuthorizedPendingReview => { if capture { // Because Wellsfargo will return Payment Status as Authorized even in AutoCapture Payment enums::AttemptStatus::Charged } else { enums::AttemptStatus::Authorized } } WellsfargoPaymentStatus::Pending => { if capture { enums::AttemptStatus::Charged } else { enums::AttemptStatus::Pending } } WellsfargoPaymentStatus::Succeeded | WellsfargoPaymentStatus::Transmitted => { enums::AttemptStatus::Charged } WellsfargoPaymentStatus::Voided | WellsfargoPaymentStatus::Reversed | WellsfargoPaymentStatus::Cancelled => enums::AttemptStatus::Voided, WellsfargoPaymentStatus::Failed | WellsfargoPaymentStatus::Declined | WellsfargoPaymentStatus::AuthorizedRiskDeclined | WellsfargoPaymentStatus::Rejected | WellsfargoPaymentStatus::InvalidRequest | WellsfargoPaymentStatus::ServerError => enums::AttemptStatus::Failure, WellsfargoPaymentStatus::PendingAuthentication => { enums::AttemptStatus::AuthenticationPending } WellsfargoPaymentStatus::PendingReview | WellsfargoPaymentStatus::StatusNotReceived | WellsfargoPaymentStatus::Challenge | WellsfargoPaymentStatus::Accepted => enums::AttemptStatus::Pending, } } impl From<WellsfargoIncrementalAuthorizationStatus> for common_enums::AuthorizationStatus { fn from(item: WellsfargoIncrementalAuthorizationStatus) -> Self { match item { WellsfargoIncrementalAuthorizationStatus::Authorized | WellsfargoIncrementalAuthorizationStatus::AuthorizedPendingReview => Self::Success, WellsfargoIncrementalAuthorizationStatus::Declined => Self::Failure, } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoPaymentsResponse { id: String, status: Option<WellsfargoPaymentStatus>, client_reference_information: Option<ClientReferenceInformation>, processor_information: Option<ClientProcessorInformation>, risk_information: Option<ClientRiskInformation>, token_information: Option<WellsfargoTokenInformation>, error_information: Option<WellsfargoErrorInformation>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoErrorInformationResponse { id: String, error_information: WellsfargoErrorInformation, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoPaymentsIncrementalAuthorizationResponse { status: WellsfargoIncrementalAuthorizationStatus, error_information: Option<WellsfargoErrorInformation>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ClientReferenceInformation { code: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ClientProcessorInformation { network_transaction_id: Option<String>, avs: Option<Avs>, card_verification: Option<CardVerification>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardVerification { result_code: Option<String>, result_code_raw: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Avs { code: Option<String>, code_raw: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientRiskInformation { rules: Option<Vec<ClientRiskInformationRules>>, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct ClientRiskInformationRules { name: Option<Secret<String>>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoTokenInformation { payment_instrument: Option<WellsfargoPaymentInstrument>, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct WellsfargoErrorInformation { reason: Option<String>, message: Option<String>, details: Option<Vec<Details>>, } fn get_error_response_if_failure( (info_response, status, http_code): (&WellsfargoPaymentsResponse, enums::AttemptStatus, u16), ) -> Option<ErrorResponse> { if utils::is_payment_failure(status) { Some(get_error_response( &info_response.error_information, &info_response.risk_information, Some(status), http_code, info_response.id.clone(), )) } else { None } } fn get_payment_response( (info_response, status, http_code): (&WellsfargoPaymentsResponse, enums::AttemptStatus, u16), ) -> Result<PaymentsResponseData, Box<ErrorResponse>> { let error_response = get_error_response_if_failure((info_response, status, http_code)); match error_response { Some(error) => Err(Box::new(error)), None => { let incremental_authorization_allowed = Some(status == enums::AttemptStatus::Authorized); let mandate_reference = info_response .token_information .clone() .map(|token_info| MandateReference { connector_mandate_id: token_info .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }); Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: info_response.processor_information.as_ref().and_then( |processor_information| processor_information.network_transaction_id.clone(), ), connector_response_reference_id: Some( info_response .client_reference_information .clone() .and_then(|client_reference_information| client_reference_information.code) .unwrap_or(info_response.id.clone()), ), incremental_authorization_allowed, charges: None, }) } } } impl TryFrom< ResponseRouterData< Authorize, WellsfargoPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Authorize, WellsfargoPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = map_attempt_status( item.response .status .clone() .unwrap_or(WellsfargoPaymentStatus::StatusNotReceived), item.data.request.is_auto_capture()?, ); let response = get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); let connector_response = item .response .processor_information .as_ref() .map(AdditionalPaymentMethodConnectorResponse::from) .map(ConnectorResponseData::with_additional_payment_method_data); Ok(Self { status, response, connector_response, ..item.data }) } } impl From<&ClientProcessorInformation> for AdditionalPaymentMethodConnectorResponse { fn from(processor_information: &ClientProcessorInformation) -> Self { let payment_checks = Some( serde_json::json!({"avs_response": processor_information.avs, "card_verification": processor_information.card_verification}), ); Self::Card { authentication_data: None, payment_checks, card_network: None, domestic_network: None, } } } impl<F> TryFrom< ResponseRouterData< F, WellsfargoPaymentsResponse, PaymentsCaptureData, PaymentsResponseData, >, > for RouterData<F, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, WellsfargoPaymentsResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = map_attempt_status( item.response .status .clone() .unwrap_or(WellsfargoPaymentStatus::StatusNotReceived), true, ); let response = get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); Ok(Self { status, response, ..item.data }) } } impl<F> TryFrom< ResponseRouterData<F, WellsfargoPaymentsResponse, PaymentsCancelData, PaymentsResponseData>, > for RouterData<F, PaymentsCancelData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, WellsfargoPaymentsResponse, PaymentsCancelData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = map_attempt_status( item.response .status .clone() .unwrap_or(WellsfargoPaymentStatus::StatusNotReceived), false, ); let response = get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); Ok(Self { status, response, ..item.data }) } } // zero dollar response impl TryFrom< ResponseRouterData< SetupMandate, WellsfargoPaymentsResponse, SetupMandateRequestData, PaymentsResponseData, >, > for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< SetupMandate, WellsfargoPaymentsResponse, SetupMandateRequestData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let mandate_reference = item.response .token_information .clone() .map(|token_info| MandateReference { connector_mandate_id: token_info .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }); let mut mandate_status = map_attempt_status( item.response .status .clone() .unwrap_or(WellsfargoPaymentStatus::StatusNotReceived), false, ); if matches!(mandate_status, enums::AttemptStatus::Authorized) { //In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well. mandate_status = enums::AttemptStatus::Charged } let error_response = get_error_response_if_failure((&item.response, mandate_status, item.http_code)); let connector_response = item .response .processor_information .as_ref() .map(AdditionalPaymentMethodConnectorResponse::from) .map(ConnectorResponseData::with_additional_payment_method_data); Ok(Self { status: mandate_status, response: match error_response { Some(error) => Err(error), None => Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: item.response.processor_information.as_ref().and_then( |processor_information| { processor_information.network_transaction_id.clone() }, ), connector_response_reference_id: Some( item.response .client_reference_information .and_then(|client_reference_information| { client_reference_information.code.clone() }) .unwrap_or(item.response.id), ), incremental_authorization_allowed: Some( mandate_status == enums::AttemptStatus::Authorized, ), charges: None, }), }, connector_response, ..item.data }) } } impl<F, T> TryFrom< ResponseRouterData< F, WellsfargoPaymentsIncrementalAuthorizationResponse, T, PaymentsResponseData, >, > for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, WellsfargoPaymentsIncrementalAuthorizationResponse, T, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: match item.response.error_information { Some(error) => Ok(PaymentsResponseData::IncrementalAuthorizationResponse { status: common_enums::AuthorizationStatus::Failure, error_code: error.reason, error_message: error.message, connector_authorization_id: None, }), _ => Ok(PaymentsResponseData::IncrementalAuthorizationResponse { status: item.response.status.into(), error_code: None, error_message: None, connector_authorization_id: None, }), }, ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoTransactionResponse { id: String, application_information: ApplicationInformation, client_reference_information: Option<ClientReferenceInformation>, error_information: Option<WellsfargoErrorInformation>, } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplicationInformation { status: Option<WellsfargoPaymentStatus>, } impl<F> TryFrom< ResponseRouterData< F, WellsfargoTransactionResponse, PaymentsSyncData, PaymentsResponseData, >, > for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, WellsfargoTransactionResponse, PaymentsSyncData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response.application_information.status { Some(status) => { let status = map_attempt_status(status, item.data.request.is_auto_capture()?); let incremental_authorization_allowed = Some(status == enums::AttemptStatus::Authorized); let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { Ok(Self { response: Err(get_error_response( &item.response.error_information, &risk_info, Some(status), item.http_code, item.response.id.clone(), )), status: enums::AttemptStatus::Failure, ..item.data }) } else { Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item .response .client_reference_information .map(|cref| cref.code) .unwrap_or(Some(item.response.id)), incremental_authorization_allowed, charges: None, }), ..item.data }) } } None => Ok(Self { status: item.data.status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, charges: None, }), ..item.data }), } } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoRefundRequest { order_information: OrderInformation, client_reference_information: ClientReferenceInformation, } impl<F> TryFrom<&WellsfargoRouterData<&RefundsRouterData<F>>> for WellsfargoRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &WellsfargoRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { order_information: OrderInformation { amount_details: Amount { total_amount: item.amount.clone(), currency: item.router_data.request.currency, }, }, client_reference_information: ClientReferenceInformation { code: Some(item.router_data.request.refund_id.clone()), }, }) } } impl From<WellsfargoRefundStatus> for enums::RefundStatus { fn from(item: WellsfargoRefundStatus) -> Self { match item { WellsfargoRefundStatus::Succeeded | WellsfargoRefundStatus::Transmitted => { Self::Success } WellsfargoRefundStatus::Cancelled | WellsfargoRefundStatus::Failed | WellsfargoRefundStatus::Voided => Self::Failure, WellsfargoRefundStatus::Pending => Self::Pending, } } } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum WellsfargoRefundStatus { Succeeded, Transmitted, Failed, Pending, Voided, Cancelled, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoRefundResponse { id: String, status: WellsfargoRefundStatus, error_information: Option<WellsfargoErrorInformation>, } impl TryFrom<RefundsResponseRouterData<Execute, WellsfargoRefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, WellsfargoRefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status.clone()); let response = if utils::is_refund_failure(refund_status) { Err(get_error_response( &item.response.error_information, &None, None, item.http_code, item.response.id.clone(), )) } else { Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status: enums::RefundStatus::from(item.response.status), }) }; Ok(Self { response, ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RsyncApplicationInformation { status: Option<WellsfargoRefundStatus>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoRsyncResponse { id: String, application_information: Option<RsyncApplicationInformation>, error_information: Option<WellsfargoErrorInformation>, } impl TryFrom<RefundsResponseRouterData<RSync, WellsfargoRsyncResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, WellsfargoRsyncResponse>, ) -> Result<Self, Self::Error> { let response = match item .response .application_information .and_then(|application_information| application_information.status) { Some(status) => { let refund_status = enums::RefundStatus::from(status.clone()); if utils::is_refund_failure(refund_status) { if status == WellsfargoRefundStatus::Voided { Err(get_error_response( &Some(WellsfargoErrorInformation { message: Some(constants::REFUND_VOIDED.to_string()), reason: Some(constants::REFUND_VOIDED.to_string()), details: None, }), &None, None, item.http_code, item.response.id.clone(), )) } else { Err(get_error_response( &item.response.error_information, &None, None, item.http_code, item.response.id.clone(), )) } } else { Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }) } } None => Ok(RefundsResponseData { connector_refund_id: item.response.id.clone(), refund_status: match item.data.response { Ok(response) => response.refund_status, Err(_) => common_enums::RefundStatus::Pending, }, }), }; Ok(Self { response, ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoStandardErrorResponse { pub error_information: Option<ErrorInformation>, pub status: Option<String>, pub message: Option<String>, pub reason: Option<String>, pub details: Option<Vec<Details>>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoNotAvailableErrorResponse { pub errors: Vec<WellsfargoNotAvailableErrorObject>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoNotAvailableErrorObject { #[serde(rename = "type")] pub error_type: Option<String>, pub message: Option<String>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WellsfargoServerErrorResponse { pub status: Option<String>, pub message: Option<String>, pub reason: Option<Reason>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum Reason { SystemError, ServerTimeout, ServiceTimeout, } #[derive(Debug, Deserialize, Serialize)] pub struct WellsfargoAuthenticationErrorResponse { pub response: AuthenticationErrorInformation, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum WellsfargoErrorResponse { AuthenticationError(Box<WellsfargoAuthenticationErrorResponse>), //If the request resource is not available/exists in wellsfargo NotAvailableError(Box<WellsfargoNotAvailableErrorResponse>), StandardError(Box<WellsfargoStandardErrorResponse>), } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct Details { pub field: String, pub reason: String, } #[derive(Debug, Default, Deserialize, Serialize)] pub struct ErrorInformation { pub message: String, pub reason: String, pub details: Option<Vec<Details>>, } #[derive(Debug, Default, Deserialize, Serialize)] pub struct AuthenticationErrorInformation { pub rmsg: String, } pub fn get_error_response( error_data: &Option<WellsfargoErrorInformation>, risk_information: &Option<ClientRiskInformation>, attempt_status: Option<enums::AttemptStatus>, status_code: u16, transaction_id: String, ) -> ErrorResponse { let avs_message = risk_information .clone() .map(|client_risk_information| { client_risk_information.rules.map(|rules| { rules .iter() .map(|risk_info| { risk_info.name.clone().map_or("".to_string(), |name| { format!(" , {}", name.clone().expose()) }) }) .collect::<Vec<String>>() .join("") }) }) .unwrap_or(Some("".to_string())); let detailed_error_info = error_data .clone() .map(|error_data| match error_data.details { Some(details) => details .iter() .map(|details| format!("{} : {}", details.field, details.reason)) .collect::<Vec<_>>() .join(", "), None => "".to_string(), }); let reason = get_error_reason( error_data.clone().and_then(|error_info| error_info.message), detailed_error_info, avs_message, ); let error_message = error_data.clone().and_then(|error_info| error_info.reason); ErrorResponse { code: error_message .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: error_message .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), reason, status_code, attempt_status, connector_transaction_id: Some(transaction_id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, } } pub fn get_error_reason( error_info: Option<String>, detailed_error_info: Option<String>, avs_error_info: Option<String>, ) -> Option<String> { match (error_info, detailed_error_info, avs_error_info) { (Some(message), Some(details), Some(avs_message)) => Some(format!( "{message}, detailed_error_information: {details}, avs_message: {avs_message}", )), (Some(message), Some(details), None) => { Some(format!("{message}, detailed_error_information: {details}")) } (Some(message), None, Some(avs_message)) => { Some(format!("{message}, avs_message: {avs_message}")) } (None, Some(details), Some(avs_message)) => { Some(format!("{details}, avs_message: {avs_message}")) } (Some(message), None, None) => Some(message), (None, Some(details), None) => Some(details), (None, None, Some(avs_message)) => Some(avs_message), (None, None, None) => None, } }
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
hyperswitch_connectors::src::connectors::wellsfargo::transformers
17,262
true
// File: crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs // Module: hyperswitch_connectors::src::connectors::hipay::transformers use std::collections::HashMap; use common_enums::{enums, CardNetwork}; use common_utils::{ pii::{self}, request::Method, types::StringMajorUnit, }; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, ErrorResponse, PaymentMethodToken, RouterData, }, router_flow_types::refunds::{Execute, RSync}, router_request_types::{BrowserInformation, PaymentsAuthorizeData, ResponseId}, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundsRouterData, TokenizationRouterData, }, }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors, }; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{ PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData, }, unimplemented_payment_method, utils::{self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, RouterData as _}, }; pub struct HipayRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for HipayRouterData<T> { fn from((amount, item): (StringMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Operation { Authorization, Sale, Capture, Refund, Cancel, } #[derive(Debug, Serialize, Deserialize)] pub struct HipayBrowserInfo { java_enabled: Option<bool>, javascript_enabled: Option<bool>, ipaddr: Option<std::net::IpAddr>, http_accept: String, http_user_agent: Option<String>, language: Option<String>, color_depth: Option<u8>, screen_height: Option<u32>, screen_width: Option<u32>, timezone: Option<i32>, } #[derive(Debug, Serialize, Deserialize)] pub struct HipayPaymentsRequest { operation: Operation, authentication_indicator: u8, cardtoken: Secret<String>, orderid: String, currency: enums::Currency, payment_product: String, amount: StringMajorUnit, description: String, decline_url: Option<String>, pending_url: Option<String>, cancel_url: Option<String>, accept_url: Option<String>, notify_url: Option<String>, #[serde(flatten)] #[serde(skip_serializing_if = "Option::is_none")] three_ds_data: Option<ThreeDSPaymentData>, } #[derive(Debug, Serialize, Deserialize)] pub struct ThreeDSPaymentData { #[serde(skip_serializing_if = "Option::is_none")] pub firstname: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub lastname: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub email: Option<pii::Email>, #[serde(skip_serializing_if = "Option::is_none")] pub streetaddress: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub city: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub zipcode: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub state: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub country: Option<enums::CountryAlpha2>, #[serde(skip_serializing_if = "Option::is_none")] pub browser_info: Option<HipayBrowserInfo>, } #[derive(Debug, Serialize, Deserialize)] pub struct HipayMaintenanceRequest { operation: Operation, currency: Option<enums::Currency>, amount: Option<StringMajorUnit>, } impl From<BrowserInformation> for HipayBrowserInfo { fn from(browser_info: BrowserInformation) -> Self { Self { java_enabled: browser_info.java_enabled, javascript_enabled: browser_info.java_script_enabled, ipaddr: browser_info.ip_address, http_accept: "*/*".to_string(), http_user_agent: browser_info.user_agent, language: browser_info.language, color_depth: browser_info.color_depth, screen_height: browser_info.screen_height, screen_width: browser_info.screen_width, timezone: browser_info.time_zone, } } } #[derive(Default, Debug, Serialize, Deserialize)] pub struct HiPayTokenRequest { pub card_number: cards::CardNumber, pub card_expiry_month: Secret<String>, pub card_expiry_year: Secret<String>, pub card_holder: Secret<String>, pub cvc: Secret<String>, } impl TryFrom<&HipayRouterData<&PaymentsAuthorizeRouterData>> for HipayPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &HipayRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { let (domestic_card_network, domestic_network) = item .router_data .connector_response .clone() .and_then(|response| match response.additional_payment_method_data { Some(AdditionalPaymentMethodConnectorResponse::Card { card_network, domestic_network, .. }) => Some((card_network, domestic_network)), _ => None, }) .unwrap_or_default(); match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => Ok(Self { operation: if item.router_data.request.is_auto_capture()? { Operation::Sale } else { Operation::Authorization }, authentication_indicator: if item.router_data.is_three_ds() { 2 } else { 0 }, cardtoken: match item.router_data.get_payment_method_token()? { PaymentMethodToken::Token(token) => token, PaymentMethodToken::ApplePayDecrypt(_) => { return Err(unimplemented_payment_method!("Apple Pay", "Hipay").into()); } PaymentMethodToken::PazeDecrypt(_) => { return Err(unimplemented_payment_method!("Paze", "Hipay").into()); } PaymentMethodToken::GooglePayDecrypt(_) => { return Err(unimplemented_payment_method!("Google Pay", "Hipay").into()); } }, orderid: item.router_data.connector_request_reference_id.clone(), currency: item.router_data.request.currency, payment_product: match (domestic_network, domestic_card_network.as_deref()) { (Some(domestic), _) => domestic, (None, Some("VISA")) => "visa".to_string(), (None, Some("MASTERCARD")) => "mastercard".to_string(), (None, Some("MAESTRO")) => "maestro".to_string(), (None, Some("AMERICAN EXPRESS")) => "american-express".to_string(), (None, Some("CB")) => "cb".to_string(), (None, Some("BCMC")) => "bcmc".to_string(), (None, _) => match req_card.card_network { Some(CardNetwork::Visa) => "visa".to_string(), Some(CardNetwork::Mastercard) => "mastercard".to_string(), Some(CardNetwork::AmericanExpress) => "american-express".to_string(), Some(CardNetwork::JCB) => "jcb".to_string(), Some(CardNetwork::DinersClub) => "diners".to_string(), Some(CardNetwork::Discover) => "discover".to_string(), Some(CardNetwork::CartesBancaires) => "cb".to_string(), Some(CardNetwork::UnionPay) => "unionpay".to_string(), Some(CardNetwork::Interac) => "interac".to_string(), Some(CardNetwork::RuPay) => "rupay".to_string(), Some(CardNetwork::Maestro) => "maestro".to_string(), Some(CardNetwork::Star) | Some(CardNetwork::Accel) | Some(CardNetwork::Pulse) | Some(CardNetwork::Nyce) | None => "".to_string(), }, }, amount: item.amount.clone(), description: item .router_data .get_description() .map(|s| s.to_string()) .unwrap_or("Short Description".to_string()), decline_url: item.router_data.request.router_return_url.clone(), pending_url: item.router_data.request.router_return_url.clone(), cancel_url: item.router_data.request.router_return_url.clone(), accept_url: item.router_data.request.router_return_url.clone(), notify_url: item.router_data.request.router_return_url.clone(), three_ds_data: if item.router_data.is_three_ds() { let billing_address = item.router_data.get_billing_address()?; Some(ThreeDSPaymentData { firstname: billing_address.get_optional_first_name(), lastname: billing_address.get_optional_last_name(), email: Some( item.router_data .get_billing_email() .or(item.router_data.request.get_email())?, ), city: billing_address.get_optional_city(), streetaddress: billing_address.get_optional_line1(), zipcode: billing_address.get_optional_zip(), state: billing_address.get_optional_state(), country: billing_address.get_optional_country(), browser_info: Some(HipayBrowserInfo::from( item.router_data.request.get_browser_info()?, )), }) } else { None }, }), _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } impl TryFrom<&TokenizationRouterData> for HiPayTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { PaymentMethodData::Card(card_data) => Ok(Self { card_number: card_data.card_number.clone(), card_expiry_month: card_data.card_exp_month.clone(), card_expiry_year: card_data.get_expiry_year_4_digit(), card_holder: item.get_billing_full_name()?, cvc: card_data.card_cvc, }), _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Hipay"), ) .into()), } } } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct HipayTokenResponse { token: Secret<String>, brand: String, domestic_network: Option<String>, } impl From<&HipayTokenResponse> for AdditionalPaymentMethodConnectorResponse { fn from(hipay_token_response: &HipayTokenResponse) -> Self { Self::Card { authentication_data: None, payment_checks: None, card_network: Some(hipay_token_response.brand.clone()), domestic_network: hipay_token_response.domestic_network.clone(), } } } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct HipayErrorResponse { pub code: u8, pub message: String, pub description: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, HipayTokenResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, HipayTokenResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PaymentsResponseData::TokenizationResponse { token: item.response.token.clone().expose(), }), connector_response: Some(ConnectorResponseData::with_additional_payment_method_data( AdditionalPaymentMethodConnectorResponse::from(&item.response), )), ..item.data }) } } pub struct HipayAuthType { pub(super) api_key: Secret<String>, pub(super) key1: Secret<String>, } impl TryFrom<&ConnectorAuthType> for HipayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.clone(), key1: key1.clone(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct HipayPaymentsResponse { status: HipayPaymentStatus, message: String, order: PaymentOrder, forward_url: String, transaction_reference: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentOrder { id: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct HipayMaintenanceResponse<S> { status: S, message: String, transaction_reference: String, } impl<F> TryFrom< ResponseRouterData<F, HipayPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData>, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, HipayPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = common_enums::AttemptStatus::from(item.response.status); let response = if status == enums::AttemptStatus::Failure { Err(ErrorResponse { code: NO_ERROR_CODE.to_string(), message: item.response.message.clone(), reason: Some(item.response.message.clone()), attempt_status: None, connector_transaction_id: Some(item.response.transaction_reference), status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_reference, ), redirection_data: match item.data.is_three_ds() { true => Box::new(Some(RedirectForm::Form { endpoint: item.response.forward_url, method: Method::Get, form_fields: HashMap::new(), })), false => Box::new(None), }, mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) }; Ok(Self { status, response, ..item.data }) } } impl<F> TryFrom<&HipayRouterData<&RefundsRouterData<F>>> for HipayMaintenanceRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &HipayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { amount: Some(item.amount.to_owned()), operation: Operation::Refund, currency: Some(item.router_data.request.currency), }) } } impl TryFrom<&PaymentsCancelRouterData> for HipayMaintenanceRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { Ok(Self { operation: Operation::Cancel, currency: item.request.currency, amount: None, }) } } impl TryFrom<&HipayRouterData<&PaymentsCaptureRouterData>> for HipayMaintenanceRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &HipayRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { Ok(Self { amount: Some(item.amount.to_owned()), operation: Operation::Capture, currency: Some(item.router_data.request.currency), }) } } #[derive(Debug, Serialize, Deserialize, Clone)] pub enum RefundStatus { #[serde(rename = "124")] RefundRequested, #[serde(rename = "125")] Refunded, #[serde(rename = "126")] PartiallyRefunded, #[serde(rename = "165")] RefundRefused, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::RefundRequested => Self::Pending, RefundStatus::Refunded | RefundStatus::PartiallyRefunded => Self::Success, RefundStatus::RefundRefused => Self::Failure, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum HipayPaymentStatus { #[serde(rename = "109")] AuthenticationFailed, #[serde(rename = "110")] Blocked, #[serde(rename = "111")] Denied, #[serde(rename = "112")] AuthorizedAndPending, #[serde(rename = "113")] Refused, #[serde(rename = "114")] Expired, #[serde(rename = "115")] Cancelled, #[serde(rename = "116")] Authorized, #[serde(rename = "117")] CaptureRequested, #[serde(rename = "118")] Captured, #[serde(rename = "119")] PartiallyCaptured, #[serde(rename = "129")] ChargedBack, #[serde(rename = "173")] CaptureRefused, #[serde(rename = "174")] AwaitingTerminal, #[serde(rename = "175")] AuthorizationCancellationRequested, #[serde(rename = "177")] ChallengeRequested, #[serde(rename = "178")] SoftDeclined, #[serde(rename = "200")] PendingPayment, #[serde(rename = "101")] Created, #[serde(rename = "105")] UnableToAuthenticate, #[serde(rename = "106")] CardholderAuthenticated, #[serde(rename = "107")] AuthenticationAttempted, #[serde(rename = "108")] CouldNotAuthenticate, #[serde(rename = "120")] Collected, #[serde(rename = "121")] PartiallyCollected, #[serde(rename = "122")] Settled, #[serde(rename = "123")] PartiallySettled, #[serde(rename = "140")] AuthenticationRequested, #[serde(rename = "141")] Authenticated, #[serde(rename = "151")] AcquirerNotFound, #[serde(rename = "161")] RiskAccepted, #[serde(rename = "163")] AuthorizationRefused, } impl From<HipayPaymentStatus> for common_enums::AttemptStatus { fn from(status: HipayPaymentStatus) -> Self { match status { HipayPaymentStatus::AuthenticationFailed => Self::AuthenticationFailed, HipayPaymentStatus::Blocked | HipayPaymentStatus::Refused | HipayPaymentStatus::Expired | HipayPaymentStatus::Denied => Self::Failure, HipayPaymentStatus::AuthorizedAndPending => Self::Pending, HipayPaymentStatus::Cancelled => Self::Voided, HipayPaymentStatus::Authorized => Self::Authorized, HipayPaymentStatus::CaptureRequested => Self::CaptureInitiated, HipayPaymentStatus::Captured => Self::Charged, HipayPaymentStatus::PartiallyCaptured => Self::PartialCharged, HipayPaymentStatus::CaptureRefused => Self::CaptureFailed, HipayPaymentStatus::AwaitingTerminal => Self::Pending, HipayPaymentStatus::AuthorizationCancellationRequested => Self::VoidInitiated, HipayPaymentStatus::ChallengeRequested => Self::AuthenticationPending, HipayPaymentStatus::SoftDeclined => Self::Failure, HipayPaymentStatus::PendingPayment => Self::Pending, HipayPaymentStatus::ChargedBack => Self::Failure, HipayPaymentStatus::Created => Self::Started, HipayPaymentStatus::UnableToAuthenticate | HipayPaymentStatus::CouldNotAuthenticate => { Self::AuthenticationFailed } HipayPaymentStatus::CardholderAuthenticated => Self::Pending, HipayPaymentStatus::AuthenticationAttempted => Self::AuthenticationPending, HipayPaymentStatus::Collected | HipayPaymentStatus::PartiallySettled | HipayPaymentStatus::PartiallyCollected | HipayPaymentStatus::Settled => Self::Charged, HipayPaymentStatus::AuthenticationRequested => Self::AuthenticationPending, HipayPaymentStatus::Authenticated => Self::AuthenticationSuccessful, HipayPaymentStatus::AcquirerNotFound => Self::Failure, HipayPaymentStatus::RiskAccepted => Self::Pending, HipayPaymentStatus::AuthorizationRefused => Self::Failure, } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: u64, status: u16, } impl TryFrom<RefundsResponseRouterData<Execute, HipayMaintenanceResponse<RefundStatus>>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, HipayMaintenanceResponse<RefundStatus>>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction_reference, refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: match item.response.status { 25 | 26 => enums::RefundStatus::Success, 65 => enums::RefundStatus::Failure, 24 => enums::RefundStatus::Pending, _ => enums::RefundStatus::Pending, }, }), ..item.data }) } } impl TryFrom<PaymentsCaptureResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>> for PaymentsCaptureRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsCaptureResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_reference.clone().to_string(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl TryFrom<PaymentsCancelResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>> for PaymentsCancelRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsCancelResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_reference.clone().to_string(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize)] pub struct Reason { reason: Option<String>, code: Option<u64>, } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum HipaySyncResponse { Response { status: i32, reason: Reason }, Error { message: String, code: u32 }, } fn get_sync_status(state: i32) -> enums::AttemptStatus { match state { 9 => enums::AttemptStatus::AuthenticationFailed, 10 => enums::AttemptStatus::Failure, 11 => enums::AttemptStatus::Failure, 12 => enums::AttemptStatus::Pending, 13 => enums::AttemptStatus::Failure, 14 => enums::AttemptStatus::Failure, 15 => enums::AttemptStatus::Voided, 16 => enums::AttemptStatus::Authorized, 17 => enums::AttemptStatus::CaptureInitiated, 18 => enums::AttemptStatus::Charged, 19 => enums::AttemptStatus::PartialCharged, 29 => enums::AttemptStatus::Failure, 73 => enums::AttemptStatus::CaptureFailed, 74 => enums::AttemptStatus::Pending, 75 => enums::AttemptStatus::VoidInitiated, 77 => enums::AttemptStatus::AuthenticationPending, 78 => enums::AttemptStatus::Failure, 200 => enums::AttemptStatus::Pending, 1 => enums::AttemptStatus::Started, 5 => enums::AttemptStatus::AuthenticationFailed, 6 => enums::AttemptStatus::Pending, 7 => enums::AttemptStatus::AuthenticationPending, 8 => enums::AttemptStatus::AuthenticationFailed, 20 => enums::AttemptStatus::Charged, 21 => enums::AttemptStatus::Charged, 22 => enums::AttemptStatus::Charged, 23 => enums::AttemptStatus::Charged, 40 => enums::AttemptStatus::AuthenticationPending, 41 => enums::AttemptStatus::AuthenticationSuccessful, 51 => enums::AttemptStatus::Failure, 61 => enums::AttemptStatus::Pending, 63 => enums::AttemptStatus::Failure, _ => enums::AttemptStatus::Failure, } } impl TryFrom<PaymentsSyncResponseRouterData<HipaySyncResponse>> for PaymentsSyncRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsSyncResponseRouterData<HipaySyncResponse>, ) -> Result<Self, Self::Error> { match item.response { HipaySyncResponse::Error { message, code } => { let response = Err(ErrorResponse { code: code.to_string(), message: message.clone(), reason: Some(message.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); Ok(Self { status: enums::AttemptStatus::Failure, response, ..item.data }) } HipaySyncResponse::Response { status, reason } => { let status = get_sync_status(status); let response = if status == enums::AttemptStatus::Failure { let error_code = reason .code .map_or(NO_ERROR_CODE.to_string(), |c| c.to_string()); let error_message = reason .reason .clone() .unwrap_or_else(|| NO_ERROR_MESSAGE.to_owned()); Err(ErrorResponse { code: error_code, message: error_message.clone(), reason: Some(error_message), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) }; Ok(Self { status, response, ..item.data }) } } } }
crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs
hyperswitch_connectors::src::connectors::hipay::transformers
6,344
true
// File: crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs // Module: hyperswitch_connectors::src::connectors::cashtocode::transformers use std::collections::HashMap; use common_enums::enums; pub use common_utils::request::Method; use common_utils::{ errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email, types::FloatMajorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_request_types::{PaymentsAuthorizeData, ResponseId}, router_response_types::{PaymentsResponseData, RedirectForm}, types::PaymentsAuthorizeRouterData, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::ResponseRouterData, utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData}, }; #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CashtocodePaymentsRequest { amount: FloatMajorUnit, transaction_id: String, user_id: Secret<id_type::CustomerId>, currency: enums::Currency, first_name: Option<Secret<String>>, last_name: Option<Secret<String>>, user_alias: Secret<id_type::CustomerId>, requested_url: String, cancel_url: String, email: Option<Email>, mid: Secret<String>, } fn get_mid( connector_auth_type: &ConnectorAuthType, payment_method_type: Option<enums::PaymentMethodType>, currency: enums::Currency, ) -> Result<Secret<String>, errors::ConnectorError> { match CashtocodeAuth::try_from((connector_auth_type, &currency)) { Ok(cashtocode_auth) => match payment_method_type { Some(enums::PaymentMethodType::ClassicReward) => Ok(cashtocode_auth .merchant_id_classic .ok_or(errors::ConnectorError::FailedToObtainAuthType)?), Some(enums::PaymentMethodType::Evoucher) => Ok(cashtocode_auth .merchant_id_evoucher .ok_or(errors::ConnectorError::FailedToObtainAuthType)?), _ => Err(errors::ConnectorError::FailedToObtainAuthType), }, Err(_) => Err(errors::ConnectorError::FailedToObtainAuthType)?, } } impl TryFrom<(&PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, amount): (&PaymentsAuthorizeRouterData, FloatMajorUnit), ) -> Result<Self, Self::Error> { let customer_id = item.get_customer_id()?; let url = item.request.get_router_return_url()?; let mid = get_mid( &item.connector_auth_type, item.request.payment_method_type, item.request.currency, )?; match item.payment_method { enums::PaymentMethod::Reward => Ok(Self { amount, transaction_id: item.attempt_id.clone(), currency: item.request.currency, user_id: Secret::new(customer_id.to_owned()), first_name: None, last_name: None, user_alias: Secret::new(customer_id), requested_url: url.to_owned(), cancel_url: url, email: item.request.email.clone(), mid, }), _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } #[derive(Default, Debug, Deserialize)] pub struct CashtocodeAuthType { pub auths: HashMap<enums::Currency, CashtocodeAuth>, } #[derive(Default, Debug, Deserialize)] pub struct CashtocodeAuth { pub password_classic: Option<Secret<String>>, pub password_evoucher: Option<Secret<String>>, pub username_classic: Option<Secret<String>>, pub username_evoucher: Option<Secret<String>>, pub merchant_id_classic: Option<Secret<String>>, pub merchant_id_evoucher: Option<Secret<String>>, } impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType { type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { let transformed_auths = auth_key_map .iter() .map(|(currency, identity_auth_key)| { let cashtocode_auth = identity_auth_key .to_owned() .parse_value::<CashtocodeAuth>("CashtocodeAuth") .change_context(errors::ConnectorError::InvalidDataFormat { field_name: "auth_key_map", })?; Ok((currency.to_owned(), cashtocode_auth)) }) .collect::<Result<_, Self::Error>>()?; Ok(Self { auths: transformed_auths, }) } _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } impl TryFrom<(&ConnectorAuthType, &enums::Currency)> for CashtocodeAuth { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: (&ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> { let (auth_type, currency) = value; if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type { if let Some(identity_auth_key) = auth_key_map.get(currency) { let cashtocode_auth: Self = identity_auth_key .to_owned() .parse_value("CashtocodeAuth") .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(cashtocode_auth) } else { Err(errors::ConnectorError::CurrencyNotSupported { message: currency.to_string(), connector: "CashToCode", } .into()) } } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } } } #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum CashtocodePaymentStatus { Succeeded, #[default] Processing, } impl From<CashtocodePaymentStatus> for enums::AttemptStatus { fn from(item: CashtocodePaymentStatus) -> Self { match item { CashtocodePaymentStatus::Succeeded => Self::Charged, CashtocodePaymentStatus::Processing => Self::AuthenticationPending, } } } #[derive(Debug, Deserialize, Clone, Serialize)] pub struct CashtocodeErrors { pub message: String, pub path: String, #[serde(rename = "type")] pub event_type: String, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum CashtocodePaymentsResponse { CashtoCodeError(CashtocodeErrorResponse), CashtoCodeData(CashtocodePaymentsResponseData), } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CashtocodePaymentsResponseData { pub pay_url: url::Url, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CashtocodePaymentsSyncResponse { pub transaction_id: String, pub amount: FloatMajorUnit, } fn get_redirect_form_data( payment_method_type: enums::PaymentMethodType, response_data: CashtocodePaymentsResponseData, ) -> CustomResult<RedirectForm, errors::ConnectorError> { match payment_method_type { enums::PaymentMethodType::ClassicReward => Ok(RedirectForm::Form { //redirect form is manually constructed because the connector for this pm type expects query params in the url endpoint: response_data.pay_url.to_string(), method: Method::Post, form_fields: Default::default(), }), enums::PaymentMethodType::Evoucher => Ok(RedirectForm::from(( //here the pay url gets parsed, and query params are sent as formfields as the connector expects response_data.pay_url, Method::Get, ))), _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("CashToCode"), ))?, } } impl<F> TryFrom< ResponseRouterData< F, CashtocodePaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CashtocodePaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (status, response) = match item.response { CashtocodePaymentsResponse::CashtoCodeError(error_data) => ( enums::AttemptStatus::Failure, Err(ErrorResponse { code: error_data.error.to_string(), status_code: item.http_code, message: error_data.error_description.clone(), reason: Some(error_data.error_description), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ), CashtocodePaymentsResponse::CashtoCodeData(response_data) => { let payment_method_type = item .data .request .payment_method_type .ok_or(errors::ConnectorError::MissingPaymentMethodType)?; let redirection_data = get_redirect_form_data(payment_method_type, response_data)?; ( enums::AttemptStatus::AuthenticationPending, Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.data.attempt_id.clone(), ), redirection_data: Box::new(Some(redirection_data)), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ) } }; Ok(Self { status, response, ..item.data }) } } impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::Charged, // Charged status is hardcoded because cashtocode do not support Psync, and we only receive webhooks when payment is succeeded, this tryFrom is used for CallConnectorAction. response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.data.attempt_id.clone(), //in response they only send PayUrl, so we use attempt_id as connector_transaction_id ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] pub struct CashtocodeErrorResponse { pub error: serde_json::Value, pub error_description: String, pub errors: Option<Vec<CashtocodeErrors>>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CashtocodeIncomingWebhook { pub amount: FloatMajorUnit, pub currency: String, pub foreign_transaction_id: String, #[serde(rename = "type")] pub event_type: String, pub transaction_id: String, }
crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
hyperswitch_connectors::src::connectors::cashtocode::transformers
2,605
true
// File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs // Module: hyperswitch_connectors::src::connectors::cybersource::transformers use api_models::payments; #[cfg(feature = "payouts")] use api_models::payouts::PayoutMethodData; use base64::Engine; use common_enums::{enums, FutureUsage}; use common_types::payments::{ApplePayPredecryptData, GPayPredecryptData}; use common_utils::{ consts, date_time, ext_traits::{OptionExt, ValueExt}, pii, types::{SemanticVersion, StringMajorUnit}, }; use error_stack::ResultExt; #[cfg(feature = "payouts")] use hyperswitch_domain_models::{ address::{AddressDetails, PhoneDetails}, router_flow_types::PoFulfill, router_response_types::PayoutsResponseData, types::PayoutsRouterData, }; use hyperswitch_domain_models::{ network_tokenization::NetworkTokenNumber, payment_method_data::{ ApplePayWalletData, GooglePayWalletData, NetworkTokenData, PaymentMethodData, SamsungPayWalletData, WalletData, }, router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, ErrorResponse, PaymentMethodToken, RouterData, }, router_flow_types::{ payments::Authorize, refunds::{Execute, RSync}, SetupMandate, }, router_request_types::{ authentication::MessageExtensionAttribute, CompleteAuthorizeData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPostAuthenticateData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSyncData, ResponseId, SetupMandateRequestData, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types::{ PaymentsAuthenticateRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsIncrementalAuthorizationRouterData, PaymentsPostAuthenticateRouterData, PaymentsPreAuthenticateRouterData, PaymentsPreProcessingRouterData, RefundsRouterData, SetupMandateRouterData, }, }; use hyperswitch_interfaces::{api, errors}; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; use utils::ForeignTryFrom; #[cfg(feature = "payouts")] use crate::types::PayoutsResponseRouterData; #[cfg(feature = "payouts")] use crate::utils::PayoutsData; use crate::{ constants, types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, utils::{ self, AddressDetailsData, CardData, CardIssuer, NetworkTokenData as _, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData, RouterData as OtherRouterData, }, }; #[derive(Debug, Serialize)] pub struct CybersourceRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for CybersourceRouterData<T> { fn from((amount, router_data): (StringMajorUnit, T)) -> Self { Self { amount, router_data, } } } impl From<CardIssuer> for String { fn from(card_issuer: CardIssuer) -> Self { let card_type = match card_issuer { CardIssuer::AmericanExpress => "003", CardIssuer::Master => "002", //"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024" CardIssuer::Maestro => "042", CardIssuer::Visa => "001", CardIssuer::Discover => "004", CardIssuer::DinersClub => "005", CardIssuer::CarteBlanche => "006", CardIssuer::JCB => "007", CardIssuer::CartesBancaires => "036", CardIssuer::UnionPay => "062", }; card_type.to_string() } } #[derive(Debug, Default, Serialize, Deserialize)] pub struct CybersourceConnectorMetadataObject { pub disable_avs: Option<bool>, pub disable_cvn: Option<bool>, } impl TryFrom<&Option<pii::SecretSerdeValue>> for CybersourceConnectorMetadataObject { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { let metadata = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata", })?; Ok(metadata) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceZeroMandateRequest { processing_information: ProcessingInformation, payment_information: PaymentInformation, order_information: OrderInformationWithBill, client_reference_information: ClientReferenceInformation, } impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> { let email = item.get_billing_email().or(item.request.get_email())?; let bill_to = build_bill_to(item.get_optional_billing(), email)?; let order_information = OrderInformationWithBill { amount_details: Amount { total_amount: StringMajorUnit::zero(), currency: item.request.currency, }, bill_to: Some(bill_to), }; let connector_merchant_config = CybersourceConnectorMetadataObject::try_from(&item.connector_meta_data)?; let (action_list, action_token_types, authorization_options) = ( Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![ CybersourceActionsTokenType::PaymentInstrument, CybersourceActionsTokenType::Customer, ]), Some(CybersourceAuthorizationOptions { initiator: Some(CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), credential_stored_on_file: Some(true), stored_credential_used: None, }), merchant_intitiated_transaction: None, ignore_avs_result: connector_merchant_config.disable_avs, ignore_cv_result: connector_merchant_config.disable_cvn, }), ); let client_reference_information = ClientReferenceInformation { code: Some(item.connector_request_reference_id.clone()), }; let (payment_information, solution) = match item.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => { let card_type = match ccard .card_network .clone() .and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; ( PaymentInformation::Cards(Box::new(CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: Some(ccard.card_cvc), card_type, type_selection_indicator: Some("1".to_owned()), }, })), None, ) } PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::ApplePay(apple_pay_data) => match item.payment_method_token.clone() { Some(payment_method_token) => match payment_method_token { PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { let expiration_month = decrypt_data.get_expiry_month().change_context( errors::ConnectorError::InvalidDataFormat { field_name: "expiration_month", }, )?; let expiration_year = decrypt_data.get_four_digit_expiry_year(); ( PaymentInformation::ApplePay(Box::new( ApplePayPaymentInformation { tokenized_card: TokenizedCard { number: decrypt_data.application_primary_account_number, cryptogram: Some( decrypt_data.payment_data.online_payment_cryptogram, ), transaction_type: TransactionType::InApp, expiration_year, expiration_month, }, }, )), Some(PaymentSolution::ApplePay), ) } PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!( "Apple Pay", "Manual", "Cybersource" ))?, PaymentMethodToken::PazeDecrypt(_) => { Err(unimplemented_payment_method!("Paze", "Cybersource"))? } PaymentMethodToken::GooglePayDecrypt(_) => { Err(unimplemented_payment_method!("Google Pay", "Cybersource"))? } }, None => { let apple_pay_encrypted_data = apple_pay_data .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", })?; ( PaymentInformation::ApplePayToken(Box::new( ApplePayTokenPaymentInformation { fluid_data: FluidData { value: Secret::from(apple_pay_encrypted_data.clone()), descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()), }, tokenized_card: ApplePayTokenizedCard { transaction_type: TransactionType::InApp, }, }, )), Some(PaymentSolution::ApplePay), ) } }, WalletData::GooglePay(google_pay_data) => ( PaymentInformation::GooglePayToken(Box::new( GooglePayTokenPaymentInformation { fluid_data: FluidData { value: Secret::from( consts::BASE64_ENGINE.encode( google_pay_data .tokenization_data .get_encrypted_google_pay_token() .change_context( errors::ConnectorError::MissingRequiredField { field_name: "gpay wallet_token", }, )?, ), ), descriptor: None, }, tokenized_card: GooglePayTokenizedCard { transaction_type: TransactionType::InApp, }, }, )), Some(PaymentSolution::GooglePay), ), WalletData::SamsungPay(samsung_pay_data) => ( (get_samsung_pay_payment_information(&samsung_pay_data) .attach_printable("Failed to get samsung pay payment information")?), Some(PaymentSolution::SamsungPay), ), WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::AmazonPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ))?, }, PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ))? } }; let processing_information = ProcessingInformation { capture: Some(false), capture_options: None, action_list, action_token_types, authorization_options, commerce_indicator: String::from("internet"), payment_solution: solution.map(String::from), }; Ok(Self { processing_information, payment_information, order_information, client_reference_information, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentsRequest { processing_information: ProcessingInformation, payment_information: PaymentInformation, order_information: OrderInformationWithBill, client_reference_information: ClientReferenceInformation, #[serde(skip_serializing_if = "Option::is_none")] consumer_authentication_information: Option<CybersourceConsumerAuthInformation>, #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProcessingInformation { action_list: Option<Vec<CybersourceActionsList>>, action_token_types: Option<Vec<CybersourceActionsTokenType>>, authorization_options: Option<CybersourceAuthorizationOptions>, commerce_indicator: String, capture: Option<bool>, capture_options: Option<CaptureOptions>, payment_solution: Option<String>, } #[derive(Debug, Serialize)] pub enum CybersourceParesStatus { #[serde(rename = "Y")] AuthenticationSuccessful, #[serde(rename = "A")] AuthenticationAttempted, #[serde(rename = "N")] AuthenticationFailed, #[serde(rename = "U")] AuthenticationNotCompleted, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceConsumerAuthInformation { ucaf_collection_indicator: Option<String>, cavv: Option<Secret<String>>, ucaf_authentication_data: Option<Secret<String>>, xid: Option<String>, directory_server_transaction_id: Option<Secret<String>>, specification_version: Option<SemanticVersion>, /// This field specifies the 3ds version pa_specification_version: Option<SemanticVersion>, /// Verification response enrollment status. /// /// This field is supported only on Asia, Middle East, and Africa Gateway. /// /// For external authentication, this field will always be "Y" veres_enrolled: Option<String>, /// Raw electronic commerce indicator (ECI) eci_raw: Option<String>, /// This field is supported only on Asia, Middle East, and Africa Gateway /// Also needed for Credit Mutuel-CIC in France and Mastercard Identity Check transactions /// This field is only applicable for Mastercard and Visa Transactions pares_status: Option<CybersourceParesStatus>, //This field is used to send the authentication date in yyyyMMDDHHMMSS format authentication_date: Option<String>, /// This field indicates the 3D Secure transaction flow. It is only supported for secure transactions in France. /// The possible values are - CH (Challenge), FD (Frictionless with delegation), FR (Frictionless) effective_authentication_type: Option<EffectiveAuthenticationType>, /// This field indicates the authentication type or challenge presented to the cardholder at checkout. challenge_code: Option<String>, /// This field indicates the reason for payer authentication response status. It is only supported for secure transactions in France. signed_pares_status_reason: Option<String>, /// This field indicates the reason why strong authentication was cancelled. It is only supported for secure transactions in France. challenge_cancel_code: Option<String>, /// This field indicates the score calculated by the 3D Securing platform. It is only supported for secure transactions in France. network_score: Option<u32>, /// This is the transaction ID generated by the access control server. This field is supported only for secure transactions in France. acs_transaction_id: Option<String>, /// This is the algorithm for generating a cardholder authentication verification value (CAVV) or universal cardholder authentication field (UCAF) data. cavv_algorithm: Option<String>, } #[derive(Debug, Serialize)] pub enum EffectiveAuthenticationType { CH, FR, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantDefinedInformation { key: u8, value: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CybersourceActionsList { TokenCreate, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum CybersourceActionsTokenType { Customer, PaymentInstrument, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceAuthorizationOptions { initiator: Option<CybersourcePaymentInitiator>, merchant_intitiated_transaction: Option<MerchantInitiatedTransaction>, ignore_avs_result: Option<bool>, ignore_cv_result: Option<bool>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantInitiatedTransaction { reason: Option<String>, previous_transaction_id: Option<Secret<String>>, //Required for recurring mandates payment original_authorized_amount: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentInitiator { #[serde(rename = "type")] initiator_type: Option<CybersourcePaymentInitiatorTypes>, credential_stored_on_file: Option<bool>, stored_credential_used: Option<bool>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum CybersourcePaymentInitiatorTypes { Customer, Merchant, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CaptureOptions { capture_sequence_number: u32, total_capture_count: u32, is_final: Option<bool>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NetworkTokenizedCard { number: NetworkTokenNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, cryptogram: Option<Secret<String>>, transaction_type: TransactionType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NetworkTokenPaymentInformation { tokenized_card: NetworkTokenizedCard, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardPaymentInformation { card: Card, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCard { number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, cryptogram: Option<Secret<String>>, transaction_type: TransactionType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayTokenizedCard { transaction_type: TransactionType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayTokenPaymentInformation { fluid_data: FluidData, tokenized_card: ApplePayTokenizedCard, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayPaymentInformation { tokenized_card: TokenizedCard, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MandatePaymentTokenizedCard { transaction_type: TransactionType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MandateCard { type_selection_indicator: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MandatePaymentInformation { payment_instrument: CybersoucrePaymentInstrument, #[serde(skip_serializing_if = "Option::is_none")] tokenized_card: Option<MandatePaymentTokenizedCard>, card: Option<MandateCard>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct FluidData { value: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] descriptor: Option<String>, } pub const FLUID_DATA_DESCRIPTOR: &str = "RklEPUNPTU1PTi5BUFBMRS5JTkFQUC5QQVlNRU5U"; pub const FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY: &str = "FID=COMMON.SAMSUNG.INAPP.PAYMENT"; #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayTokenPaymentInformation { fluid_data: FluidData, tokenized_card: GooglePayTokenizedCard, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayTokenizedCard { transaction_type: TransactionType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayPaymentInformation { tokenized_card: TokenizedCard, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SamsungPayTokenizedCard { transaction_type: TransactionType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SamsungPayPaymentInformation { fluid_data: FluidData, tokenized_card: SamsungPayTokenizedCard, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SamsungPayFluidDataValue { public_key_hash: Secret<String>, version: String, data: Secret<String>, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaymentInformation { Cards(Box<CardPaymentInformation>), GooglePayToken(Box<GooglePayTokenPaymentInformation>), GooglePay(Box<GooglePayPaymentInformation>), ApplePay(Box<ApplePayPaymentInformation>), ApplePayToken(Box<ApplePayTokenPaymentInformation>), MandatePayment(Box<MandatePaymentInformation>), SamsungPay(Box<SamsungPayPaymentInformation>), NetworkToken(Box<NetworkTokenPaymentInformation>), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CybersoucrePaymentInstrument { id: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Card { number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, security_code: Option<Secret<String>>, #[serde(rename = "type")] card_type: Option<String>, type_selection_indicator: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformationWithBill { amount_details: Amount, bill_to: Option<BillTo>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformationIncrementalAuthorization { amount_details: AdditionalAmount, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformation { amount_details: Amount, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Amount { total_amount: StringMajorUnit, currency: api_models::enums::Currency, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdditionalAmount { additional_amount: StringMajorUnit, currency: String, } #[derive(Debug, Serialize)] pub enum PaymentSolution { ApplePay, GooglePay, SamsungPay, } #[derive(Debug, Serialize)] pub enum TransactionType { #[serde(rename = "1")] InApp, #[serde(rename = "2")] ContactlessNFC, #[serde(rename = "3")] StoredCredentials, } impl From<PaymentSolution> for String { fn from(solution: PaymentSolution) -> Self { let payment_solution = match solution { PaymentSolution::ApplePay => "001", PaymentSolution::GooglePay => "012", PaymentSolution::SamsungPay => "008", }; payment_solution.to_string() } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BillTo { first_name: Option<Secret<String>>, last_name: Option<Secret<String>>, address1: Option<Secret<String>>, locality: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] administrative_area: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] postal_code: Option<Secret<String>>, country: Option<enums::CountryAlpha2>, email: pii::Email, } impl From<&CybersourceRouterData<&PaymentsPreAuthenticateRouterData>> for ClientReferenceInformation { fn from(item: &CybersourceRouterData<&PaymentsPreAuthenticateRouterData>) -> Self { Self { code: Some(item.router_data.connector_request_reference_id.clone()), } } } impl From<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation { fn from(item: &CybersourceRouterData<&PaymentsAuthorizeRouterData>) -> Self { Self { code: Some(item.router_data.connector_request_reference_id.clone()), } } } impl From<&CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>> for ClientReferenceInformation { fn from(item: &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>) -> Self { Self { code: Some(item.router_data.connector_request_reference_id.clone()), } } } impl TryFrom<( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, Option<PaymentSolution>, Option<String>, )> for ProcessingInformation { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, solution, network): ( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, Option<PaymentSolution>, Option<String>, ), ) -> Result<Self, Self::Error> { let mut commerce_indicator = solution .as_ref() .map(|pm_solution| match pm_solution { PaymentSolution::ApplePay | PaymentSolution::SamsungPay => network .as_ref() .map(|card_network| match card_network.to_lowercase().as_str() { "amex" => "internet", "discover" => "internet", "mastercard" => "spa", "visa" => "internet", _ => "internet", }) .unwrap_or("internet"), PaymentSolution::GooglePay => "internet", }) .unwrap_or("internet") .to_string(); let connector_merchant_config = CybersourceConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?; let (action_list, action_token_types, authorization_options) = if item .router_data .request .setup_future_usage == Some(FutureUsage::OffSession) && (item.router_data.request.customer_acceptance.is_some() || item .router_data .request .setup_mandate_details .clone() .is_some_and(|mandate_details| mandate_details.customer_acceptance.is_some())) { ( Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![ CybersourceActionsTokenType::PaymentInstrument, CybersourceActionsTokenType::Customer, ]), Some(CybersourceAuthorizationOptions { initiator: Some(CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), credential_stored_on_file: Some(true), stored_credential_used: None, }), ignore_avs_result: connector_merchant_config.disable_avs, ignore_cv_result: connector_merchant_config.disable_cvn, merchant_intitiated_transaction: None, }), ) } else if item.router_data.request.mandate_id.is_some() { match item .router_data .request .mandate_id .clone() .and_then(|mandate_id| mandate_id.mandate_reference_id) { Some(payments::MandateReferenceId::ConnectorMandateId(_)) => { let original_amount = item .router_data .recurring_mandate_payment_data .as_ref() .and_then(|recurring_mandate_payment_data| { recurring_mandate_payment_data.original_payment_authorized_amount }); let original_currency = item .router_data .recurring_mandate_payment_data .as_ref() .and_then(|recurring_mandate_payment_data| { recurring_mandate_payment_data.original_payment_authorized_currency }); let original_authorized_amount = match original_amount.zip(original_currency) { Some((original_amount, original_currency)) => { Some(utils::get_amount_as_string( &api::CurrencyUnit::Base, original_amount, original_currency, )?) } None => None, }; ( None, None, Some(CybersourceAuthorizationOptions { initiator: None, merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { reason: None, original_authorized_amount, previous_transaction_id: None, }), ignore_avs_result: connector_merchant_config.disable_avs, ignore_cv_result: connector_merchant_config.disable_cvn, }), ) } Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => { let (original_amount, original_currency) = match network .clone() .map(|network| network.to_lowercase()) .as_deref() { //This is to make original_authorized_amount mandatory for discover card networks in NetworkMandateId flow Some("004") => { let original_amount = Some( item.router_data .get_recurring_mandate_payment_data()? .get_original_payment_amount()?, ); let original_currency = Some( item.router_data .get_recurring_mandate_payment_data()? .get_original_payment_currency()?, ); (original_amount, original_currency) } _ => { let original_amount = item .router_data .recurring_mandate_payment_data .as_ref() .and_then(|recurring_mandate_payment_data| { recurring_mandate_payment_data .original_payment_authorized_amount }); let original_currency = item .router_data .recurring_mandate_payment_data .as_ref() .and_then(|recurring_mandate_payment_data| { recurring_mandate_payment_data .original_payment_authorized_currency }); (original_amount, original_currency) } }; let original_authorized_amount = match original_amount.zip(original_currency) { Some((original_amount, original_currency)) => Some( utils::to_currency_base_unit(original_amount, original_currency)?, ), None => None, }; commerce_indicator = "recurring".to_string(); ( None, None, Some(CybersourceAuthorizationOptions { initiator: Some(CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Merchant), credential_stored_on_file: None, stored_credential_used: Some(true), }), merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { reason: Some("7".to_string()), original_authorized_amount, previous_transaction_id: Some(Secret::new(network_transaction_id)), }), ignore_avs_result: connector_merchant_config.disable_avs, ignore_cv_result: connector_merchant_config.disable_cvn, }), ) } Some(payments::MandateReferenceId::NetworkTokenWithNTI(mandate_data)) => { let (original_amount, original_currency) = match network .clone() .map(|network| network.to_lowercase()) .as_deref() { //This is to make original_authorized_amount mandatory for discover card networks in NetworkMandateId flow Some("004") => { let original_amount = Some( item.router_data .get_recurring_mandate_payment_data()? .get_original_payment_amount()?, ); let original_currency = Some( item.router_data .get_recurring_mandate_payment_data()? .get_original_payment_currency()?, ); (original_amount, original_currency) } _ => { let original_amount = item .router_data .recurring_mandate_payment_data .as_ref() .and_then(|recurring_mandate_payment_data| { recurring_mandate_payment_data .original_payment_authorized_amount }); let original_currency = item .router_data .recurring_mandate_payment_data .as_ref() .and_then(|recurring_mandate_payment_data| { recurring_mandate_payment_data .original_payment_authorized_currency }); (original_amount, original_currency) } }; let original_authorized_amount = match original_amount.zip(original_currency) { Some((original_amount, original_currency)) => Some( utils::to_currency_base_unit(original_amount, original_currency)?, ), None => None, }; commerce_indicator = "recurring".to_string(); // ( None, None, Some(CybersourceAuthorizationOptions { initiator: Some(CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Merchant), credential_stored_on_file: None, stored_credential_used: Some(true), }), merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { reason: Some("7".to_string()), // 7 is for MIT using NTI original_authorized_amount, previous_transaction_id: Some(Secret::new( mandate_data.network_transaction_id, )), }), ignore_avs_result: connector_merchant_config.disable_avs, ignore_cv_result: connector_merchant_config.disable_cvn, }), ) } None => (None, None, None), } } else { ( None, None, Some(CybersourceAuthorizationOptions { initiator: None, merchant_intitiated_transaction: None, ignore_avs_result: connector_merchant_config.disable_avs, ignore_cv_result: connector_merchant_config.disable_cvn, }), ) }; // this logic is for external authenticated card let commerce_indicator_for_external_authentication = item .router_data .request .authentication_data .as_ref() .and_then(|authn_data| { authn_data .eci .clone() .map(|eci| get_commerce_indicator_for_external_authentication(network, eci)) }); Ok(Self { capture: Some(matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None )), payment_solution: solution.map(String::from), action_list, action_token_types, authorization_options, capture_options: None, commerce_indicator: commerce_indicator_for_external_authentication .unwrap_or(commerce_indicator), }) } } fn get_commerce_indicator_for_external_authentication( card_network: Option<String>, eci: String, ) -> String { let card_network_lower_case = card_network .as_ref() .map(|card_network| card_network.to_lowercase()); match eci.as_str() { "00" | "01" | "02" => { if matches!( card_network_lower_case.as_deref(), Some("mastercard") | Some("maestro") ) { "spa" } else { "internet" } } "05" => match card_network_lower_case.as_deref() { Some("amex") => "aesk", Some("discover") => "dipb", Some("mastercard") => "spa", Some("visa") => "vbv", Some("diners") => "pb", Some("upi") => "up3ds", _ => "internet", }, "06" => match card_network_lower_case.as_deref() { Some("amex") => "aesk_attempted", Some("discover") => "dipb_attempted", Some("mastercard") => "spa", Some("visa") => "vbv_attempted", Some("diners") => "pb_attempted", Some("upi") => "up3ds_attempted", _ => "internet", }, "07" => match card_network_lower_case.as_deref() { Some("amex") => "internet", Some("discover") => "internet", Some("mastercard") => "spa", Some("visa") => "vbv_failure", Some("diners") => "internet", Some("upi") => "up3ds_failure", _ => "internet", }, _ => "vbv_failure", } .to_string() } impl TryFrom<( &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>, Option<PaymentSolution>, &CybersourceConsumerAuthValidateResponse, )> for ProcessingInformation { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, solution, three_ds_data): ( &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>, Option<PaymentSolution>, &CybersourceConsumerAuthValidateResponse, ), ) -> Result<Self, Self::Error> { let connector_merchant_config = CybersourceConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?; let (action_list, action_token_types, authorization_options) = if item.router_data.request.setup_future_usage == Some(FutureUsage::OffSession) //TODO check for customer acceptance also { ( Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![ CybersourceActionsTokenType::PaymentInstrument, CybersourceActionsTokenType::Customer, ]), Some(CybersourceAuthorizationOptions { initiator: Some(CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), credential_stored_on_file: Some(true), stored_credential_used: None, }), merchant_intitiated_transaction: None, ignore_avs_result: connector_merchant_config.disable_avs, ignore_cv_result: connector_merchant_config.disable_cvn, }), ) } else { (None, None, None) }; Ok(Self { capture: Some(matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None )), payment_solution: solution.map(String::from), action_list, action_token_types, authorization_options, capture_options: None, commerce_indicator: three_ds_data .indicator .to_owned() .unwrap_or(String::from("internet")), }) } } impl From<( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, Option<BillTo>, )> for OrderInformationWithBill { fn from( (item, bill_to): ( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, Option<BillTo>, ), ) -> Self { Self { amount_details: Amount { total_amount: item.amount.to_owned(), currency: item.router_data.request.currency, }, bill_to, } } } impl From<( &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>, BillTo, )> for OrderInformationWithBill { fn from( (item, bill_to): ( &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>, BillTo, ), ) -> Self { Self { amount_details: Amount { total_amount: item.amount.to_owned(), currency: item.router_data.request.currency, }, bill_to: Some(bill_to), } } } // for cybersource each item in Billing is mandatory // fn build_bill_to( // address_details: &payments::Address, // email: pii::Email, // ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { // let address = address_details // .address // .as_ref() // .ok_or_else(utils::missing_field_err("billing.address"))?; // let country = address.get_country()?.to_owned(); // let first_name = address.get_first_name()?; // let (administrative_area, postal_code) = // if country == api_enums::CountryAlpha2::US || country == api_enums::CountryAlpha2::CA { // let mut state = address.to_state_code()?.peek().clone(); // state.truncate(20); // ( // Some(Secret::from(state)), // Some(address.get_zip()?.to_owned()), // ) // } else { // let zip = address.zip.clone(); // let mut_state = address.state.clone().map(|state| state.expose()); // match mut_state { // Some(mut state) => { // state.truncate(20); // (Some(Secret::from(state)), zip) // } // None => (None, zip), // } // }; // Ok(BillTo { // first_name: first_name.clone(), // last_name: address.get_last_name().unwrap_or(first_name).clone(), // address1: address.get_line1()?.to_owned(), // locality: address.get_city()?.to_owned(), // administrative_area, // postal_code, // country, // email, // }) // } fn truncate_string(state: &Secret<String>, max_len: usize) -> Secret<String> { let exposed = state.clone().expose(); let truncated = exposed.get(..max_len).unwrap_or(&exposed); Secret::new(truncated.to_string()) } fn build_bill_to( address_details: Option<&hyperswitch_domain_models::address::Address>, email: pii::Email, ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { let default_address = BillTo { first_name: None, last_name: None, address1: None, locality: None, administrative_area: None, postal_code: None, country: None, email: email.clone(), }; Ok(address_details .and_then(|addr| { addr.address.as_ref().map(|addr| BillTo { first_name: addr.first_name.remove_new_line(), last_name: addr.last_name.remove_new_line(), address1: addr.line1.remove_new_line(), locality: addr.city.remove_new_line(), administrative_area: addr.to_state_code_as_optional().unwrap_or_else(|_| { addr.state .remove_new_line() .as_ref() .map(|state| truncate_string(state, 20)) //NOTE: Cybersource connector throws error if billing state exceeds 20 characters, so truncation is done to avoid payment failure }), postal_code: addr.zip.remove_new_line(), country: addr.country, email, }) }) .unwrap_or(default_address)) } fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> { let hashmap: std::collections::BTreeMap<String, Value> = serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new()); let mut vector = Vec::new(); let mut iter = 1; for (key, value) in hashmap { vector.push(MerchantDefinedInformation { key: iter, value: format!("{key}={value}"), }); iter += 1; } vector } /* Example Message Extension: [ MessageExtensionAttribute { name: "CB-SCORE".to_string(), id: "A000000042_CB-SCORE".to_string(), criticality_indicator: false, data: "some value".to_string(), }, ] In this case, the **network score** is `42`, which should be extracted from the `id` field. The score is encoded in the numeric part of the `id` (after removing the leading 'A' and before the underscore). Note: This field represents the score calculated by the 3D Securing platform. It is only supported for secure transactions in France. */ fn extract_score_id(message_extensions: &[MessageExtensionAttribute]) -> Option<u32> { message_extensions.iter().find_map(|attr| { attr.id .ends_with("CB-SCORE") .then(|| { attr.id .split('_') .next() .and_then(|p| p.strip_prefix('A')) .and_then(|s| { s.parse::<u32>().map(Some).unwrap_or_else(|err| { router_env::logger::error!( "Failed to parse score_id from '{}': {}", s, err ); None }) }) .or_else(|| { router_env::logger::error!("Unexpected prefix format in id: {}", attr.id); None }) }) .flatten() }) } impl From<common_enums::DecoupledAuthenticationType> for EffectiveAuthenticationType { fn from(auth_type: common_enums::DecoupledAuthenticationType) -> Self { match auth_type { common_enums::DecoupledAuthenticationType::Challenge => Self::CH, common_enums::DecoupledAuthenticationType::Frictionless => Self::FR, } } } impl TryFrom<( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, hyperswitch_domain_models::payment_method_data::Card, )> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, ccard): ( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, hyperswitch_domain_models::payment_method_data::Card, ), ) -> Result<Self, Self::Error> { let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let additional_card_network = item .router_data .request .get_card_network_from_additional_payment_method_data() .map_err(|err| { router_env::logger::info!( "Error while getting card network from additional payment method data: {}", err ); }) .ok(); let raw_card_type = ccard.card_network.clone().or(additional_card_network); let card_type = match raw_card_type.clone().and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; // For all card payments, we are explicitly setting `pares_status` to `AuthenticationSuccessful` // to indicate that the Payer Authentication was successful, regardless of actual ACS response. // This is a default behavior and may be adjusted based on future integration requirements. let pares_status = Some(CybersourceParesStatus::AuthenticationSuccessful); let security_code = if item .router_data .request .get_optional_network_transaction_id() .is_some() { None } else { Some(ccard.card_cvc) }; let payment_information = PaymentInformation::Cards(Box::new(CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code, card_type: card_type.clone(), type_selection_indicator: Some("1".to_owned()), }, })); let processing_information = ProcessingInformation::try_from(( item, None, raw_card_type.map(|network| network.to_string()), ))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); let consumer_authentication_information = item .router_data .request .authentication_data .as_ref() .map(|authn_data| { let (ucaf_authentication_data, cavv, ucaf_collection_indicator) = if ccard.card_network == Some(common_enums::CardNetwork::Mastercard) { (Some(authn_data.cavv.clone()), None, Some("2".to_string())) } else { (None, Some(authn_data.cavv.clone()), None) }; let authentication_date = date_time::format_date( authn_data.created_at, date_time::DateFormat::YYYYMMDDHHmmss, ) .ok(); let effective_authentication_type = authn_data.authentication_type.map(Into::into); let network_score = (ccard.card_network == Some(common_enums::CardNetwork::CartesBancaires)) .then_some(authn_data.message_extension.as_ref()) .flatten() .map(|secret| secret.clone().expose()) .and_then(|exposed| { serde_json::from_value::<Vec<MessageExtensionAttribute>>(exposed) .map_err(|err| { router_env::logger::error!( "Failed to deserialize message_extension: {:?}", err ); }) .ok() .and_then(|exts| extract_score_id(&exts)) }); // The 3DS Server might not include the `cavvAlgorithm` field in the challenge response. // In such cases, we default to "2", which represents the CVV with Authentication Transaction Number (ATN) algorithm. // This is the most commonly used value for 3DS 2.0 transactions (e.g., Visa, Mastercard). let cavv_algorithm = Some("2".to_string()); CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, cavv, ucaf_authentication_data, xid: None, directory_server_transaction_id: authn_data .ds_trans_id .clone() .map(Secret::new), specification_version: authn_data.message_version.clone(), pa_specification_version: authn_data.message_version.clone(), veres_enrolled: Some("Y".to_string()), eci_raw: authn_data.eci.clone(), authentication_date, effective_authentication_type, challenge_code: authn_data.challenge_code.clone(), signed_pares_status_reason: authn_data.challenge_code_reason.clone(), challenge_cancel_code: authn_data.challenge_cancel.clone(), network_score, acs_transaction_id: authn_data.acs_trans_id.clone(), cavv_algorithm, } }); Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information, merchant_defined_information, }) } } impl TryFrom<( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId, )> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, ccard): ( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId, ), ) -> Result<Self, Self::Error> { let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let card_issuer = ccard.get_card_issuer(); let card_type = match card_issuer { Ok(issuer) => Some(String::from(issuer)), Err(_) => None, }; // For all card payments, we are explicitly setting `pares_status` to `AuthenticationSuccessful` // to indicate that the Payer Authentication was successful, regardless of actual ACS response. // This is a default behavior and may be adjusted based on future integration requirements. let pares_status = Some(CybersourceParesStatus::AuthenticationSuccessful); let payment_information = PaymentInformation::Cards(Box::new(CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: None, card_type: card_type.clone(), type_selection_indicator: Some("1".to_owned()), }, })); let processing_information = ProcessingInformation::try_from((item, None, card_type))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); let consumer_authentication_information = item .router_data .request .authentication_data .as_ref() .map(|authn_data| { let effective_authentication_type = authn_data.authentication_type.map(Into::into); let (ucaf_authentication_data, cavv, ucaf_collection_indicator) = if ccard.card_network == Some(common_enums::CardNetwork::Mastercard) { (Some(authn_data.cavv.clone()), None, Some("2".to_string())) } else { (None, Some(authn_data.cavv.clone()), None) }; let authentication_date = date_time::format_date( authn_data.created_at, date_time::DateFormat::YYYYMMDDHHmmss, ) .ok(); let network_score = (ccard.card_network == Some(common_enums::CardNetwork::CartesBancaires)) .then_some(authn_data.message_extension.as_ref()) .flatten() .map(|secret| secret.clone().expose()) .and_then(|exposed| { serde_json::from_value::<Vec<MessageExtensionAttribute>>(exposed) .map_err(|err| { router_env::logger::error!( "Failed to deserialize message_extension: {:?}", err ); }) .ok() .and_then(|exts| extract_score_id(&exts)) }); let cavv_algorithm = Some("2".to_string()); CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, cavv, ucaf_authentication_data, xid: None, directory_server_transaction_id: authn_data .ds_trans_id .clone() .map(Secret::new), specification_version: authn_data.message_version.clone(), pa_specification_version: authn_data.message_version.clone(), veres_enrolled: Some("Y".to_string()), eci_raw: authn_data.eci.clone(), authentication_date, effective_authentication_type, challenge_code: authn_data.challenge_code.clone(), signed_pares_status_reason: authn_data.challenge_code_reason.clone(), challenge_cancel_code: authn_data.challenge_cancel.clone(), network_score, acs_transaction_id: authn_data.acs_trans_id.clone(), cavv_algorithm, } }); Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information, merchant_defined_information, }) } } impl TryFrom<( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, NetworkTokenData, )> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, token_data): ( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, NetworkTokenData, ), ) -> Result<Self, Self::Error> { let transaction_type = if item.router_data.request.off_session == Some(true) { TransactionType::StoredCredentials } else { TransactionType::InApp }; let email = item.router_data.request.get_email()?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let card_issuer = token_data.get_card_issuer(); let card_type = match card_issuer { Ok(issuer) => Some(String::from(issuer)), Err(_) => None, }; // For all card payments, we are explicitly setting `pares_status` to `AuthenticationSuccessful` // to indicate that the Payer Authentication was successful, regardless of actual ACS response. // This is a default behavior and may be adjusted based on future integration requirements. let pares_status = Some(CybersourceParesStatus::AuthenticationSuccessful); let payment_information = PaymentInformation::NetworkToken(Box::new(NetworkTokenPaymentInformation { tokenized_card: NetworkTokenizedCard { number: token_data.get_network_token(), expiration_month: token_data.get_network_token_expiry_month(), expiration_year: token_data.get_network_token_expiry_year(), cryptogram: token_data.get_cryptogram().clone(), transaction_type, }, })); let processing_information = ProcessingInformation::try_from((item, None, card_type))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); let consumer_authentication_information = item .router_data .request .authentication_data .as_ref() .map(|authn_data| { let effective_authentication_type = authn_data.authentication_type.map(Into::into); let (ucaf_authentication_data, cavv, ucaf_collection_indicator) = if token_data.card_network == Some(common_enums::CardNetwork::Mastercard) { (Some(authn_data.cavv.clone()), None, Some("2".to_string())) } else { (None, Some(authn_data.cavv.clone()), None) }; let authentication_date = date_time::format_date( authn_data.created_at, date_time::DateFormat::YYYYMMDDHHmmss, ) .ok(); let network_score = (token_data.card_network == Some(common_enums::CardNetwork::CartesBancaires)) .then_some(authn_data.message_extension.as_ref()) .flatten() .map(|secret| secret.clone().expose()) .and_then(|exposed| { serde_json::from_value::<Vec<MessageExtensionAttribute>>(exposed) .map_err(|err| { router_env::logger::error!( "Failed to deserialize message_extension: {:?}", err ); }) .ok() .and_then(|exts| extract_score_id(&exts)) }); let cavv_algorithm = Some("2".to_string()); CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, cavv, ucaf_authentication_data, xid: None, directory_server_transaction_id: authn_data .ds_trans_id .clone() .map(Secret::new), specification_version: authn_data.message_version.clone(), pa_specification_version: authn_data.message_version.clone(), veres_enrolled: Some("Y".to_string()), eci_raw: authn_data.eci.clone(), authentication_date, effective_authentication_type, challenge_code: authn_data.challenge_code.clone(), signed_pares_status_reason: authn_data.challenge_code_reason.clone(), challenge_cancel_code: authn_data.challenge_cancel.clone(), network_score, acs_transaction_id: authn_data.acs_trans_id.clone(), cavv_algorithm, } }); Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information, merchant_defined_information, }) } } impl TryFrom<( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, Box<hyperswitch_domain_models::router_data::PazeDecryptedData>, )> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, paze_data): ( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, Box<hyperswitch_domain_models::router_data::PazeDecryptedData>, ), ) -> Result<Self, Self::Error> { let transaction_type = if item.router_data.request.off_session == Some(true) { TransactionType::StoredCredentials } else { TransactionType::InApp }; let email = item.router_data.request.get_email()?; let (first_name, last_name) = match paze_data.billing_address.name { Some(name) => { let (first_name, last_name) = name .peek() .split_once(' ') .map(|(first, last)| (first.to_string(), last.to_string())) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "billing_address.name", })?; (Secret::from(first_name), Secret::from(last_name)) } None => ( item.router_data.get_billing_first_name()?, item.router_data.get_billing_last_name()?, ), }; let bill_to = BillTo { first_name: Some(first_name), last_name: Some(last_name), address1: paze_data.billing_address.line1, locality: paze_data.billing_address.city.map(|city| city.expose()), administrative_area: Some(Secret::from( //Paze wallet is currently supported in US only common_enums::UsStatesAbbreviation::foreign_try_from( paze_data .billing_address .state .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "billing_address.state", })? .peek() .to_owned(), )? .to_string(), )), postal_code: paze_data.billing_address.zip, country: paze_data.billing_address.country_code, email, }; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = PaymentInformation::NetworkToken(Box::new(NetworkTokenPaymentInformation { tokenized_card: NetworkTokenizedCard { number: paze_data.token.payment_token, expiration_month: paze_data.token.token_expiration_month, expiration_year: paze_data.token.token_expiration_year, cryptogram: Some(paze_data.token.payment_account_reference), transaction_type, }, })); let processing_information = ProcessingInformation::try_from((item, None, None))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information: None, merchant_defined_information, }) } } impl TryFrom<( &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>, hyperswitch_domain_models::payment_method_data::Card, )> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, ccard): ( &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>, hyperswitch_domain_models::payment_method_data::Card, ), ) -> Result<Self, Self::Error> { let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, bill_to)); let card_type = match ccard .card_network .clone() .and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; // For all card payments, we are explicitly setting `pares_status` to `AuthenticationSuccessful` // to indicate that the Payer Authentication was successful, regardless of actual ACS response. // This is a default behavior and may be adjusted based on future integration requirements. let pares_status = Some(CybersourceParesStatus::AuthenticationSuccessful); let payment_information = PaymentInformation::Cards(Box::new(CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: Some(ccard.card_cvc), card_type, type_selection_indicator: Some("1".to_owned()), }, })); let client_reference_information = ClientReferenceInformation::from(item); let three_ds_info: CybersourceThreeDSMetadata = item .router_data .request .connector_meta .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "connector_meta", })? .parse_value("CybersourceThreeDSMetadata") .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata", })?; let processing_information = ProcessingInformation::try_from((item, None, &three_ds_info.three_ds_data))?; let consumer_authentication_information = Some(CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator: three_ds_info.three_ds_data.ucaf_collection_indicator, cavv: three_ds_info.three_ds_data.cavv, ucaf_authentication_data: three_ds_info.three_ds_data.ucaf_authentication_data, xid: three_ds_info.three_ds_data.xid, directory_server_transaction_id: three_ds_info .three_ds_data .directory_server_transaction_id, specification_version: three_ds_info.three_ds_data.specification_version.clone(), pa_specification_version: three_ds_info.three_ds_data.specification_version.clone(), veres_enrolled: None, eci_raw: None, authentication_date: None, effective_authentication_type: None, challenge_code: None, signed_pares_status_reason: None, challenge_cancel_code: None, network_score: None, acs_transaction_id: None, cavv_algorithm: None, }); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information, merchant_defined_information, }) } } impl TryFrom<( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, Box<ApplePayPredecryptData>, ApplePayWalletData, )> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, apple_pay_data, apple_pay_wallet_data): ( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, Box<ApplePayPredecryptData>, ApplePayWalletData, ), ) -> Result<Self, Self::Error> { let transaction_type = if item.router_data.request.off_session == Some(true) { TransactionType::StoredCredentials } else { TransactionType::InApp }; let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = ProcessingInformation::try_from(( item, Some(PaymentSolution::ApplePay), Some(apple_pay_wallet_data.payment_method.network.clone()), ))?; let client_reference_information = ClientReferenceInformation::from(item); let expiration_month = apple_pay_data.get_expiry_month().change_context( errors::ConnectorError::InvalidDataFormat { field_name: "expiration_month", }, )?; let expiration_year = apple_pay_data.get_four_digit_expiry_year(); let payment_information = PaymentInformation::ApplePay(Box::new(ApplePayPaymentInformation { tokenized_card: TokenizedCard { number: apple_pay_data.application_primary_account_number, cryptogram: Some(apple_pay_data.payment_data.online_payment_cryptogram), transaction_type, expiration_year, expiration_month, }, })); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); let ucaf_collection_indicator = match apple_pay_wallet_data .payment_method .network .to_lowercase() .as_str() { "mastercard" => Some("2".to_string()), _ => None, }; Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information: Some(CybersourceConsumerAuthInformation { pares_status: None, ucaf_collection_indicator, cavv: None, ucaf_authentication_data: None, xid: None, directory_server_transaction_id: None, specification_version: None, pa_specification_version: None, veres_enrolled: None, eci_raw: None, authentication_date: None, effective_authentication_type: None, challenge_code: None, signed_pares_status_reason: None, challenge_cancel_code: None, network_score: None, acs_transaction_id: None, cavv_algorithm: None, }), merchant_defined_information, }) } } impl TryFrom<( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, GooglePayWalletData, )> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, google_pay_data): ( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, GooglePayWalletData, ), ) -> Result<Self, Self::Error> { let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = PaymentInformation::GooglePayToken(Box::new(GooglePayTokenPaymentInformation { fluid_data: FluidData { value: Secret::from( consts::BASE64_ENGINE.encode( google_pay_data .tokenization_data .get_encrypted_google_pay_token() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "gpay wallet_token", })?, ), ), descriptor: None, }, tokenized_card: GooglePayTokenizedCard { transaction_type: TransactionType::InApp, }, })); let processing_information = ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information: None, merchant_defined_information, }) } } impl TryFrom<( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, Box<GPayPredecryptData>, GooglePayWalletData, )> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, google_pay_decrypted_data, google_pay_data): ( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, Box<GPayPredecryptData>, GooglePayWalletData, ), ) -> Result<Self, Self::Error> { let transaction_type = if item.router_data.request.off_session == Some(true) { TransactionType::StoredCredentials } else { TransactionType::InApp }; let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = PaymentInformation::GooglePay(Box::new(GooglePayPaymentInformation { tokenized_card: TokenizedCard { number: google_pay_decrypted_data .application_primary_account_number .clone(), cryptogram: google_pay_decrypted_data.cryptogram.clone(), transaction_type, expiration_year: google_pay_decrypted_data .get_four_digit_expiry_year() .change_context(errors::ConnectorError::InvalidDataFormat { field_name: "expiration_year", })?, expiration_month: google_pay_decrypted_data .get_expiry_month() .change_context(errors::ConnectorError::InvalidDataFormat { field_name: "expiration_month", })?, }, })); let processing_information = ProcessingInformation::try_from(( item, Some(PaymentSolution::GooglePay), Some(google_pay_data.info.card_network.clone()), ))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); let ucaf_collection_indicator = match google_pay_data.info.card_network.to_lowercase().as_str() { "mastercard" => Some("2".to_string()), _ => None, }; Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information: Some(CybersourceConsumerAuthInformation { pares_status: None, ucaf_collection_indicator, cavv: None, ucaf_authentication_data: None, xid: None, directory_server_transaction_id: None, specification_version: None, pa_specification_version: None, veres_enrolled: None, eci_raw: None, authentication_date: None, effective_authentication_type: None, challenge_code: None, signed_pares_status_reason: None, challenge_cancel_code: None, network_score: None, acs_transaction_id: None, cavv_algorithm: None, }), merchant_defined_information, }) } } impl TryFrom<( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, Box<SamsungPayWalletData>, )> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, samsung_pay_data): ( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, Box<SamsungPayWalletData>, ), ) -> Result<Self, Self::Error> { let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = get_samsung_pay_payment_information(&samsung_pay_data) .attach_printable("Failed to get samsung pay payment information")?; let processing_information = ProcessingInformation::try_from(( item, Some(PaymentSolution::SamsungPay), Some(samsung_pay_data.payment_credential.card_brand.to_string()), ))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information: None, merchant_defined_information, }) } } fn get_samsung_pay_payment_information( samsung_pay_data: &SamsungPayWalletData, ) -> Result<PaymentInformation, error_stack::Report<errors::ConnectorError>> { let samsung_pay_fluid_data_value = get_samsung_pay_fluid_data_value(&samsung_pay_data.payment_credential.token_data)?; let samsung_pay_fluid_data_str = serde_json::to_string(&samsung_pay_fluid_data_value) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to serialize samsung pay fluid data")?; let payment_information = PaymentInformation::SamsungPay(Box::new(SamsungPayPaymentInformation { fluid_data: FluidData { value: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_fluid_data_str)), descriptor: Some( consts::BASE64_ENGINE.encode(FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY), ), }, tokenized_card: SamsungPayTokenizedCard { transaction_type: TransactionType::InApp, }, })); Ok(payment_information) } fn get_samsung_pay_fluid_data_value( samsung_pay_token_data: &hyperswitch_domain_models::payment_method_data::SamsungPayTokenData, ) -> Result<SamsungPayFluidDataValue, error_stack::Report<errors::ConnectorError>> { let samsung_pay_header = josekit::jwt::decode_header(samsung_pay_token_data.data.clone().peek()) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to decode samsung pay header")?; let samsung_pay_kid_optional = samsung_pay_header.claim("kid").and_then(|kid| kid.as_str()); let samsung_pay_fluid_data_value = SamsungPayFluidDataValue { public_key_hash: Secret::new( samsung_pay_kid_optional .get_required_value("samsung pay public_key_hash") .change_context(errors::ConnectorError::RequestEncodingFailed)? .to_string(), ), version: samsung_pay_token_data.version.clone(), data: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_token_data.data.peek())), }; Ok(samsung_pay_fluid_data_value) } impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CybersourceRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.connector_mandate_id() { Some(connector_mandate_id) => Self::try_from((item, connector_mandate_id)), None => { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::ApplePay(apple_pay_data) => { match item.router_data.payment_method_token.clone() { Some(payment_method_token) => match payment_method_token { PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { Self::try_from((item, decrypt_data, apple_pay_data)) } PaymentMethodToken::Token(_) => { Err(unimplemented_payment_method!( "Apple Pay", "Manual", "Cybersource" ))? } PaymentMethodToken::PazeDecrypt(_) => { Err(unimplemented_payment_method!("Paze", "Cybersource"))? } PaymentMethodToken::GooglePayDecrypt(_) => Err( unimplemented_payment_method!("Google Pay", "Cybersource"), )?, }, None => { let transaction_type = if item.router_data.request.off_session == Some(true) { TransactionType::StoredCredentials } else { TransactionType::InApp }; let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to( item.router_data.get_optional_billing(), email, )?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = ProcessingInformation::try_from(( item, Some(PaymentSolution::ApplePay), Some(apple_pay_data.payment_method.network.clone()), ))?; let client_reference_information = ClientReferenceInformation::from(item); let apple_pay_encrypted_data = apple_pay_data .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context( errors::ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", }, )?; let payment_information = PaymentInformation::ApplePayToken( Box::new(ApplePayTokenPaymentInformation { fluid_data: FluidData { value: Secret::from( apple_pay_encrypted_data.clone(), ), descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()), }, tokenized_card: ApplePayTokenizedCard { transaction_type, }, }), ); let merchant_defined_information = item.router_data.request.metadata.clone().map(|metadata| { convert_metadata_to_merchant_defined_info(metadata) }); let ucaf_collection_indicator = match apple_pay_data .payment_method .network .to_lowercase() .as_str() { "mastercard" => Some("2".to_string()), _ => None, }; Ok(Self { processing_information, payment_information, order_information, client_reference_information, merchant_defined_information, consumer_authentication_information: Some( CybersourceConsumerAuthInformation { pares_status: None, ucaf_collection_indicator, cavv: None, ucaf_authentication_data: None, xid: None, directory_server_transaction_id: None, specification_version: None, pa_specification_version: None, veres_enrolled: None, eci_raw: None, authentication_date: None, effective_authentication_type: None, challenge_code: None, signed_pares_status_reason: None, challenge_cancel_code: None, network_score: None, acs_transaction_id: None, cavv_algorithm: None, }, ), }) } } } WalletData::GooglePay(google_pay_data) => { match item.router_data.payment_method_token.clone() { Some(payment_method_token) => match payment_method_token { PaymentMethodToken::GooglePayDecrypt(decrypt_data) => { Self::try_from((item, decrypt_data, google_pay_data)) } PaymentMethodToken::Token(_) => { Err(unimplemented_payment_method!( "Apple Pay", "Manual", "Cybersource" ))? } PaymentMethodToken::PazeDecrypt(_) => { Err(unimplemented_payment_method!("Paze", "Cybersource"))? } PaymentMethodToken::ApplePayDecrypt(_) => { Err(unimplemented_payment_method!( "Apple Pay", "Simplified", "Cybersource" ))? } }, None => Self::try_from((item, google_pay_data)), } } WalletData::SamsungPay(samsung_pay_data) => { Self::try_from((item, samsung_pay_data)) } WalletData::Paze(_) => { match item.router_data.payment_method_token.clone() { Some(PaymentMethodToken::PazeDecrypt(paze_decrypted_data)) => { Self::try_from((item, paze_decrypted_data)) } _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message( "Cybersource", ), ) .into()), } } WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::AmazonPay(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ) .into()), }, // If connector_mandate_id is present MandatePayment will be the PMD, the case will be handled in the first `if` clause. // This is a fallback implementation in the event of catastrophe. PaymentMethodData::MandatePayment => { let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "connector_mandate_id", }, )?; Self::try_from((item, connector_mandate_id)) } PaymentMethodData::NetworkToken(token_data) => { Self::try_from((item, token_data)) } PaymentMethodData::CardDetailsForNetworkTransactionId(card) => { Self::try_from((item, card)) } PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ) .into()) } } } } } } impl TryFrom<(&CybersourceRouterData<&PaymentsAuthorizeRouterData>, String)> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, connector_mandate_id): ( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, String, ), ) -> Result<Self, Self::Error> { let processing_information = ProcessingInformation::try_from((item, None, None))?; let payment_instrument = CybersoucrePaymentInstrument { id: connector_mandate_id.into(), }; let mandate_card_information = match item.router_data.request.payment_method_type { Some(enums::PaymentMethodType::Credit) | Some(enums::PaymentMethodType::Debit) => { Some(MandateCard { type_selection_indicator: Some("1".to_owned()), }) } _ => None, }; let tokenized_card = match item.router_data.request.payment_method_type { Some(enums::PaymentMethodType::GooglePay) | Some(enums::PaymentMethodType::ApplePay) | Some(enums::PaymentMethodType::SamsungPay) => Some(MandatePaymentTokenizedCard { transaction_type: TransactionType::StoredCredentials, }), _ => None, }; let bill_to = item .router_data .get_optional_billing_email() .or(item.router_data.request.get_optional_email()) .and_then(|email| build_bill_to(item.router_data.get_optional_billing(), email).ok()); let order_information = OrderInformationWithBill::from((item, bill_to)); let payment_information = PaymentInformation::MandatePayment(Box::new(MandatePaymentInformation { payment_instrument, tokenized_card, card: mandate_card_information, })); let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { processing_information, payment_information, order_information, client_reference_information, merchant_defined_information, consumer_authentication_information: None, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceAuthSetupRequest { payment_information: PaymentInformation, client_reference_information: ClientReferenceInformation, } impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for CybersourceAuthSetupRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CybersourceRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => { let card_type = match ccard .card_network .clone() .and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; let payment_information = PaymentInformation::Cards(Box::new(CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: Some(ccard.card_cvc), card_type, type_selection_indicator: Some("1".to_owned()), }, })); let client_reference_information = ClientReferenceInformation::from(item); Ok(Self { payment_information, client_reference_information, }) } PaymentMethodData::Wallet(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ) .into()) } } } } impl TryFrom<&CybersourceRouterData<&PaymentsPreAuthenticateRouterData>> for CybersourceAuthSetupRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CybersourceRouterData<&PaymentsPreAuthenticateRouterData>, ) -> Result<Self, Self::Error> { let payment_method_data = item .router_data .request .payment_method_data .as_ref() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "payment_method_data", })?; match payment_method_data.clone() { PaymentMethodData::Card(ccard) => { let card_type = match ccard .card_network .clone() .and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; let payment_information = PaymentInformation::Cards(Box::new(CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: Some(ccard.card_cvc), card_type, type_selection_indicator: Some("1".to_owned()), }, })); let client_reference_information = ClientReferenceInformation::from(item); Ok(Self { payment_information, client_reference_information, }) } PaymentMethodData::Wallet(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ) .into()) } } } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentsCaptureRequest { processing_information: ProcessingInformation, order_information: OrderInformationWithBill, client_reference_information: ClientReferenceInformation, #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentsIncrementalAuthorizationRequest { processing_information: ProcessingInformation, order_information: OrderInformationIncrementalAuthorization, } impl TryFrom<&CybersourceRouterData<&PaymentsCaptureRouterData>> for CybersourcePaymentsCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CybersourceRouterData<&PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); let is_final = matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Manual) ) .then_some(true); Ok(Self { processing_information: ProcessingInformation { capture_options: Some(CaptureOptions { capture_sequence_number: 1, total_capture_count: 1, is_final, }), action_list: None, action_token_types: None, authorization_options: None, capture: None, commerce_indicator: String::from("internet"), payment_solution: None, }, order_information: OrderInformationWithBill { amount_details: Amount { total_amount: item.amount.clone(), currency: item.router_data.request.currency, }, bill_to: None, }, client_reference_information: ClientReferenceInformation { code: Some(item.router_data.connector_request_reference_id.clone()), }, merchant_defined_information, }) } } impl TryFrom<&CybersourceRouterData<&PaymentsIncrementalAuthorizationRouterData>> for CybersourcePaymentsIncrementalAuthorizationRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CybersourceRouterData<&PaymentsIncrementalAuthorizationRouterData>, ) -> Result<Self, Self::Error> { let connector_merchant_config = CybersourceConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?; Ok(Self { processing_information: ProcessingInformation { action_list: None, action_token_types: None, authorization_options: Some(CybersourceAuthorizationOptions { initiator: Some(CybersourcePaymentInitiator { initiator_type: None, credential_stored_on_file: None, stored_credential_used: Some(true), }), merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { reason: Some("5".to_owned()), previous_transaction_id: None, original_authorized_amount: None, }), ignore_avs_result: connector_merchant_config.disable_avs, ignore_cv_result: connector_merchant_config.disable_cvn, }), commerce_indicator: String::from("internet"), capture: None, capture_options: None, payment_solution: None, }, order_information: OrderInformationIncrementalAuthorization { amount_details: AdditionalAmount { additional_amount: item.amount.clone(), currency: item.router_data.request.currency.to_string(), }, }, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceVoidRequest { client_reference_information: ClientReferenceInformation, reversal_information: ReversalInformation, #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, // The connector documentation does not mention the merchantDefinedInformation field for Void requests. But this has been still added because it works! } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ReversalInformation { amount_details: Amount, reason: String, } impl TryFrom<&CybersourceRouterData<&PaymentsCancelRouterData>> for CybersourceVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( value: &CybersourceRouterData<&PaymentsCancelRouterData>, ) -> Result<Self, Self::Error> { let merchant_defined_information = value .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { client_reference_information: ClientReferenceInformation { code: Some(value.router_data.connector_request_reference_id.clone()), }, reversal_information: ReversalInformation { amount_details: Amount { total_amount: value.amount.to_owned(), currency: value.router_data.request.currency.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "Currency", }, )?, }, reason: value .router_data .request .cancellation_reason .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "Cancellation Reason", })?, }, merchant_defined_information, }) } } pub struct CybersourceAuthType { pub(super) api_key: Secret<String>, pub(super) merchant_account: Secret<String>, pub(super) api_secret: Secret<String>, } impl TryFrom<&ConnectorAuthType> for CybersourceAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } = auth_type { Ok(Self { api_key: api_key.to_owned(), merchant_account: key1.to_owned(), api_secret: api_secret.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CybersourcePaymentStatus { Authorized, Succeeded, Failed, Voided, Reversed, Pending, Declined, Rejected, Challenge, AuthorizedPendingReview, AuthorizedRiskDeclined, Transmitted, InvalidRequest, ServerError, PendingAuthentication, PendingReview, Accepted, Cancelled, StatusNotReceived, //PartialAuthorized, not being consumed yet. } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CybersourceIncrementalAuthorizationStatus { Authorized, Declined, AuthorizedPendingReview, } pub fn map_cybersource_attempt_status( status: CybersourcePaymentStatus, capture: bool, ) -> enums::AttemptStatus { match status { CybersourcePaymentStatus::Authorized => { if capture { // Because Cybersource will return Payment Status as Authorized even in AutoCapture Payment enums::AttemptStatus::Charged } else { enums::AttemptStatus::Authorized } } CybersourcePaymentStatus::Succeeded | CybersourcePaymentStatus::Transmitted => { enums::AttemptStatus::Charged } CybersourcePaymentStatus::Voided | CybersourcePaymentStatus::Reversed | CybersourcePaymentStatus::Cancelled => enums::AttemptStatus::Voided, CybersourcePaymentStatus::Failed | CybersourcePaymentStatus::Declined | CybersourcePaymentStatus::AuthorizedRiskDeclined | CybersourcePaymentStatus::Rejected | CybersourcePaymentStatus::InvalidRequest | CybersourcePaymentStatus::ServerError => enums::AttemptStatus::Failure, CybersourcePaymentStatus::PendingAuthentication => { enums::AttemptStatus::AuthenticationPending } CybersourcePaymentStatus::PendingReview | CybersourcePaymentStatus::StatusNotReceived | CybersourcePaymentStatus::Challenge | CybersourcePaymentStatus::Accepted | CybersourcePaymentStatus::Pending | CybersourcePaymentStatus::AuthorizedPendingReview => enums::AttemptStatus::Pending, } } impl From<CybersourceIncrementalAuthorizationStatus> for common_enums::AuthorizationStatus { fn from(item: CybersourceIncrementalAuthorizationStatus) -> Self { match item { CybersourceIncrementalAuthorizationStatus::Authorized => Self::Success, CybersourceIncrementalAuthorizationStatus::AuthorizedPendingReview => Self::Processing, CybersourceIncrementalAuthorizationStatus::Declined => Self::Failure, } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentsResponse { id: String, status: Option<CybersourcePaymentStatus>, client_reference_information: Option<ClientReferenceInformation>, processor_information: Option<ClientProcessorInformation>, risk_information: Option<ClientRiskInformation>, token_information: Option<CybersourceTokenInformation>, error_information: Option<CybersourceErrorInformation>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceErrorInformationResponse { id: String, error_information: CybersourceErrorInformation, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceConsumerAuthInformationResponse { access_token: String, device_data_collection_url: String, reference_id: String, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientAuthSetupInfoResponse { id: String, client_reference_information: ClientReferenceInformation, consumer_authentication_information: CybersourceConsumerAuthInformationResponse, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum CybersourceAuthSetupResponse { ClientAuthSetupInfo(Box<ClientAuthSetupInfoResponse>), ErrorInformation(Box<CybersourceErrorInformationResponse>), } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentsIncrementalAuthorizationResponse { status: CybersourceIncrementalAuthorizationStatus, error_information: Option<CybersourceErrorInformation>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ClientReferenceInformation { code: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ClientProcessorInformation { network_transaction_id: Option<String>, avs: Option<Avs>, card_verification: Option<CardVerification>, merchant_advice: Option<MerchantAdvice>, response_code: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantAdvice { code: Option<String>, code_raw: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardVerification { result_code: Option<String>, result_code_raw: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Avs { code: Option<String>, code_raw: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientRiskInformation { rules: Option<Vec<ClientRiskInformationRules>>, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct ClientRiskInformationRules { name: Option<Secret<String>>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceTokenInformation { payment_instrument: Option<CybersoucrePaymentInstrument>, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct CybersourceErrorInformation { reason: Option<String>, message: Option<String>, details: Option<Vec<Details>>, } fn get_error_response_if_failure( (info_response, status, http_code): (&CybersourcePaymentsResponse, enums::AttemptStatus, u16), ) -> Option<ErrorResponse> { if utils::is_payment_failure(status) { Some(get_error_response( &info_response.error_information, &info_response.processor_information, &info_response.risk_information, Some(status), http_code, info_response.id.clone(), )) } else { None } } fn get_payment_response( (info_response, status, http_code): (&CybersourcePaymentsResponse, enums::AttemptStatus, u16), ) -> Result<PaymentsResponseData, Box<ErrorResponse>> { let error_response = get_error_response_if_failure((info_response, status, http_code)); match error_response { Some(error) => Err(Box::new(error)), None => { let incremental_authorization_allowed = Some(status == enums::AttemptStatus::Authorized); let mandate_reference = info_response .token_information .clone() .map(|token_info| MandateReference { connector_mandate_id: token_info .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }); Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: info_response.processor_information.as_ref().and_then( |processor_information| processor_information.network_transaction_id.clone(), ), connector_response_reference_id: Some( info_response .client_reference_information .clone() .and_then(|client_reference_information| client_reference_information.code) .unwrap_or(info_response.id.clone()), ), incremental_authorization_allowed, charges: None, }) } } } impl TryFrom< ResponseRouterData< Authorize, CybersourcePaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Authorize, CybersourcePaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = map_cybersource_attempt_status( item.response .status .clone() .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), item.data.request.is_auto_capture()?, ); let response = get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); let connector_response = item .response .processor_information .as_ref() .map(AdditionalPaymentMethodConnectorResponse::from) .map(ConnectorResponseData::with_additional_payment_method_data); Ok(Self { status, response, connector_response, ..item.data }) } } impl<F> TryFrom< ResponseRouterData< F, CybersourceAuthSetupResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CybersourceAuthSetupResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response { CybersourceAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(Some(RedirectForm::CybersourceAuthSetup { access_token: info_response .consumer_authentication_information .access_token, ddc_url: info_response .consumer_authentication_information .device_data_collection_url, reference_id: info_response .consumer_authentication_information .reference_id, })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( info_response .client_reference_information .code .unwrap_or(info_response.id.clone()), ), incremental_authorization_allowed: None, charges: None, }), ..item.data }), CybersourceAuthSetupResponse::ErrorInformation(error_response) => { let detailed_error_info = error_response .error_information .details .to_owned() .map(|details| { details .iter() .map(|details| format!("{} : {}", details.field, details.reason)) .collect::<Vec<_>>() .join(", ") }); let reason = get_error_reason( error_response.error_information.message, detailed_error_info, None, ); let error_message = error_response.error_information.reason; Ok(Self { response: Err(ErrorResponse { code: error_message .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: error_message.unwrap_or( hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string(), ), reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), status: enums::AttemptStatus::AuthenticationFailed, ..item.data }) } } } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceConsumerAuthInformationRequest { return_url: String, reference_id: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceAuthEnrollmentRequest { payment_information: PaymentInformation, client_reference_information: ClientReferenceInformation, consumer_authentication_information: CybersourceConsumerAuthInformationRequest, order_information: OrderInformationWithBill, } #[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct CybersourceRedirectionAuthResponse { pub transaction_id: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceConsumerAuthInformationValidateRequest { authentication_transaction_id: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceAuthValidateRequest { payment_information: PaymentInformation, client_reference_information: ClientReferenceInformation, consumer_authentication_information: CybersourceConsumerAuthInformationValidateRequest, order_information: OrderInformation, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum CybersourcePreProcessingRequest { AuthEnrollment(Box<CybersourceAuthEnrollmentRequest>), AuthValidate(Box<CybersourceAuthValidateRequest>), } impl TryFrom<&CybersourceRouterData<&PaymentsPreProcessingRouterData>> for CybersourcePreProcessingRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CybersourceRouterData<&PaymentsPreProcessingRouterData>, ) -> Result<Self, Self::Error> { let client_reference_information = ClientReferenceInformation { code: Some(item.router_data.connector_request_reference_id.clone()), }; let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "payment_method_data", }, )?; let payment_information = match payment_method_data { PaymentMethodData::Card(ccard) => { let card_type = match ccard .card_network .clone() .and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; Ok(PaymentInformation::Cards(Box::new( CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: Some(ccard.card_cvc), card_type, type_selection_indicator: Some("1".to_owned()), }, }, ))) } PaymentMethodData::Wallet(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), )) } }?; let redirect_response = item.router_data.request.redirect_response.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "redirect_response", }, )?; let amount_details = Amount { total_amount: item.amount.clone(), currency: item.router_data.request.currency.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "currency", }, )?, }; match redirect_response.params { Some(param) if !param.clone().peek().is_empty() => { let reference_id = param .clone() .peek() .split_once('=') .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.params.reference_id", })? .1 .to_string(); let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill { amount_details, bill_to: Some(bill_to), }; Ok(Self::AuthEnrollment(Box::new( CybersourceAuthEnrollmentRequest { payment_information, client_reference_information, consumer_authentication_information: CybersourceConsumerAuthInformationRequest { return_url: item .router_data .request .get_complete_authorize_url()?, reference_id, }, order_information, }, ))) } Some(_) | None => { let redirect_payload: CybersourceRedirectionAuthResponse = redirect_response .payload .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.payload", })? .peek() .clone() .parse_value("CybersourceRedirectionAuthResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let order_information = OrderInformation { amount_details }; Ok(Self::AuthValidate(Box::new( CybersourceAuthValidateRequest { payment_information, client_reference_information, consumer_authentication_information: CybersourceConsumerAuthInformationValidateRequest { authentication_transaction_id: redirect_payload.transaction_id, }, order_information, }, ))) } } } } impl TryFrom<&CybersourceRouterData<&PaymentsAuthenticateRouterData>> for CybersourceAuthEnrollmentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CybersourceRouterData<&PaymentsAuthenticateRouterData>, ) -> Result<Self, Self::Error> { let client_reference_information = ClientReferenceInformation { code: Some(item.router_data.connector_request_reference_id.clone()), }; let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "payment_method_data", }, )?; let payment_information = match payment_method_data { PaymentMethodData::Card(ccard) => { let card_type = match ccard .card_network .clone() .and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; Ok(PaymentInformation::Cards(Box::new( CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: Some(ccard.card_cvc), card_type, type_selection_indicator: Some("1".to_owned()), }, }, ))) } PaymentMethodData::Wallet(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), )) } }?; let redirect_response = item.router_data.request.redirect_response.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "redirect_response", }, )?; let amount_details = Amount { total_amount: item.amount.clone(), currency: item.router_data.request.currency.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "currency", }, )?, }; let param = redirect_response.params.ok_or( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.params", }, )?; let reference_id = param .clone() .peek() .split('=') .next_back() .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.params.reference_id", })? .to_string(); let email = item.router_data.get_billing_email().or(item .router_data .request .email .clone() .ok_or_else(utils::missing_field_err("email")))?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill { amount_details, bill_to: Some(bill_to), }; Ok(Self { payment_information, client_reference_information, consumer_authentication_information: CybersourceConsumerAuthInformationRequest { return_url: item .router_data .request .complete_authorize_url .clone() .ok_or_else(utils::missing_field_err("complete_authorize_url"))?, reference_id, }, order_information, }) } } impl TryFrom<&CybersourceRouterData<&PaymentsPostAuthenticateRouterData>> for CybersourceAuthValidateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CybersourceRouterData<&PaymentsPostAuthenticateRouterData>, ) -> Result<Self, Self::Error> { let client_reference_information = ClientReferenceInformation { code: Some(item.router_data.connector_request_reference_id.clone()), }; let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "payment_method_data", }, )?; let payment_information = match payment_method_data { PaymentMethodData::Card(ccard) => { let card_type = match ccard .card_network .clone() .and_then(get_cybersource_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; Ok(PaymentInformation::Cards(Box::new( CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: Some(ccard.card_cvc), card_type, type_selection_indicator: Some("1".to_owned()), }, }, ))) } PaymentMethodData::Wallet(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), )) } }?; let redirect_response = item.router_data.request.redirect_response.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "redirect_response", }, )?; let amount_details = Amount { total_amount: item.amount.clone(), currency: item.router_data.request.currency.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "currency", }, )?, }; let redirect_payload: CybersourceRedirectionAuthResponse = redirect_response .payload .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.payload", })? .peek() .clone() .parse_value("CybersourceRedirectionAuthResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let order_information = OrderInformation { amount_details }; Ok(Self { payment_information, client_reference_information, consumer_authentication_information: CybersourceConsumerAuthInformationValidateRequest { authentication_transaction_id: redirect_payload.transaction_id, }, order_information, }) } } impl TryFrom<&CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>> for CybersourcePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "payment_method_data", }, )?; match payment_method_data { PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), PaymentMethodData::Wallet(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ) .into()) } } } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CybersourceAuthEnrollmentStatus { PendingAuthentication, AuthenticationSuccessful, AuthenticationFailed, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceConsumerAuthValidateResponse { ucaf_collection_indicator: Option<String>, cavv: Option<Secret<String>>, ucaf_authentication_data: Option<Secret<String>>, xid: Option<String>, specification_version: Option<SemanticVersion>, directory_server_transaction_id: Option<Secret<String>>, indicator: Option<String>, } #[derive(Debug, Deserialize, Serialize)] pub struct CybersourceThreeDSMetadata { three_ds_data: CybersourceConsumerAuthValidateResponse, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceConsumerAuthInformationEnrollmentResponse { access_token: Option<Secret<String>>, step_up_url: Option<String>, //Added to segregate the three_ds_data in a separate struct #[serde(flatten)] validate_response: CybersourceConsumerAuthValidateResponse, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientAuthCheckInfoResponse { id: String, client_reference_information: ClientReferenceInformation, consumer_authentication_information: CybersourceConsumerAuthInformationEnrollmentResponse, status: CybersourceAuthEnrollmentStatus, error_information: Option<CybersourceErrorInformation>, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum CybersourcePreProcessingResponse { ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), ErrorInformation(Box<CybersourceErrorInformationResponse>), } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum CybersourceAuthenticateResponse { ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), ErrorInformation(Box<CybersourceErrorInformationResponse>), } impl From<CybersourceAuthEnrollmentStatus> for enums::AttemptStatus { fn from(item: CybersourceAuthEnrollmentStatus) -> Self { match item { CybersourceAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending, CybersourceAuthEnrollmentStatus::AuthenticationSuccessful => { Self::AuthenticationSuccessful } CybersourceAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed, } } } impl<F> TryFrom< ResponseRouterData< F, CybersourcePreProcessingResponse, PaymentsPreProcessingData, PaymentsResponseData, >, > for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CybersourcePreProcessingResponse, PaymentsPreProcessingData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response { CybersourcePreProcessingResponse::ClientAuthCheckInfo(info_response) => { let status = enums::AttemptStatus::from(info_response.status); let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { let response = Err(get_error_response( &info_response.error_information, &None, &risk_info, Some(status), item.http_code, info_response.id.clone(), )); Ok(Self { status, response, ..item.data }) } else { let connector_response_reference_id = Some( info_response .client_reference_information .code .unwrap_or(info_response.id.clone()), ); let redirection_data = match ( info_response .consumer_authentication_information .access_token, info_response .consumer_authentication_information .step_up_url, ) { (Some(token), Some(step_up_url)) => { Some(RedirectForm::CybersourceConsumerAuth { access_token: token.expose(), step_up_url, }) } _ => None, }; let three_ds_data = serde_json::to_value( info_response .consumer_authentication_information .validate_response, ) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!({ "three_ds_data": three_ds_data })), network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } CybersourcePreProcessingResponse::ErrorInformation(error_response) => { let detailed_error_info = error_response .error_information .details .to_owned() .map(|details| { details .iter() .map(|details| format!("{} : {}", details.field, details.reason)) .collect::<Vec<_>>() .join(", ") }); let reason = get_error_reason( error_response.error_information.message, detailed_error_info, None, ); let error_message = error_response.error_information.reason.to_owned(); let response = Err(ErrorResponse { code: error_message .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: error_message .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); Ok(Self { response, status: enums::AttemptStatus::AuthenticationFailed, ..item.data }) } } } } impl<F> TryFrom< ResponseRouterData< F, CybersourcePaymentsResponse, CompleteAuthorizeData, PaymentsResponseData, >, > for RouterData<F, CompleteAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CybersourcePaymentsResponse, CompleteAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = map_cybersource_attempt_status( item.response .status .clone() .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), item.data.request.is_auto_capture()?, ); let response = get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); let connector_response = item .response .processor_information .as_ref() .map(AdditionalPaymentMethodConnectorResponse::from) .map(ConnectorResponseData::with_additional_payment_method_data); Ok(Self { status, response, connector_response, ..item.data }) } } impl From<&ClientProcessorInformation> for AdditionalPaymentMethodConnectorResponse { fn from(processor_information: &ClientProcessorInformation) -> Self { let payment_checks = Some( serde_json::json!({"avs_response": processor_information.avs, "card_verification": processor_information.card_verification}), ); Self::Card { authentication_data: None, payment_checks, card_network: None, domestic_network: None, } } } impl<F> TryFrom< ResponseRouterData< F, CybersourcePaymentsResponse, PaymentsCaptureData, PaymentsResponseData, >, > for RouterData<F, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CybersourcePaymentsResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = map_cybersource_attempt_status( item.response .status .clone() .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), true, ); let response = get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); Ok(Self { status, response, ..item.data }) } } impl<F> TryFrom< ResponseRouterData< F, CybersourcePaymentsResponse, PaymentsCancelData, PaymentsResponseData, >, > for RouterData<F, PaymentsCancelData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CybersourcePaymentsResponse, PaymentsCancelData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = map_cybersource_attempt_status( item.response .status .clone() .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), false, ); let response = get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); Ok(Self { status, response, ..item.data }) } } // zero dollar response impl TryFrom< ResponseRouterData< SetupMandate, CybersourcePaymentsResponse, SetupMandateRequestData, PaymentsResponseData, >, > for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< SetupMandate, CybersourcePaymentsResponse, SetupMandateRequestData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let mandate_reference = item.response .token_information .clone() .map(|token_info| MandateReference { connector_mandate_id: token_info .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }); let mut mandate_status = map_cybersource_attempt_status( item.response .status .clone() .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), false, ); if matches!(mandate_status, enums::AttemptStatus::Authorized) { //In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well. mandate_status = enums::AttemptStatus::Charged } let error_response = get_error_response_if_failure((&item.response, mandate_status, item.http_code)); let connector_response = item .response .processor_information .as_ref() .map(AdditionalPaymentMethodConnectorResponse::from) .map(ConnectorResponseData::with_additional_payment_method_data); Ok(Self { status: mandate_status, response: match error_response { Some(error) => Err(error), None => Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: item.response.processor_information.as_ref().and_then( |processor_information| { processor_information.network_transaction_id.clone() }, ), connector_response_reference_id: Some( item.response .client_reference_information .and_then(|client_reference_information| { client_reference_information.code.clone() }) .unwrap_or(item.response.id), ), incremental_authorization_allowed: Some( mandate_status == enums::AttemptStatus::Authorized, ), charges: None, }), }, connector_response, ..item.data }) } } impl<F, T> TryFrom< ResponseRouterData< F, CybersourcePaymentsIncrementalAuthorizationResponse, T, PaymentsResponseData, >, > for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CybersourcePaymentsIncrementalAuthorizationResponse, T, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: match item.response.error_information { Some(error) => Ok(PaymentsResponseData::IncrementalAuthorizationResponse { status: common_enums::AuthorizationStatus::Failure, error_code: error.reason, error_message: error.message, connector_authorization_id: None, }), None => Ok(PaymentsResponseData::IncrementalAuthorizationResponse { status: item.response.status.into(), error_code: None, error_message: None, connector_authorization_id: None, }), }, ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceTransactionResponse { id: String, application_information: ApplicationInformation, processor_information: Option<ClientProcessorInformation>, client_reference_information: Option<ClientReferenceInformation>, error_information: Option<CybersourceErrorInformation>, } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplicationInformation { status: Option<CybersourcePaymentStatus>, } impl<F> TryFrom< ResponseRouterData< F, CybersourceAuthSetupResponse, PaymentsPreAuthenticateData, PaymentsResponseData, >, > for RouterData<F, PaymentsPreAuthenticateData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CybersourceAuthSetupResponse, PaymentsPreAuthenticateData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response { CybersourceAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(Some(RedirectForm::CybersourceAuthSetup { access_token: info_response .consumer_authentication_information .access_token, ddc_url: info_response .consumer_authentication_information .device_data_collection_url, reference_id: info_response .consumer_authentication_information .reference_id, })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( info_response .client_reference_information .code .unwrap_or(info_response.id.clone()), ), incremental_authorization_allowed: None, charges: None, }), ..item.data }), CybersourceAuthSetupResponse::ErrorInformation(error_response) => { let detailed_error_info = error_response .error_information .details .to_owned() .map(|details| { details .iter() .map(|details| format!("{} : {}", details.field, details.reason)) .collect::<Vec<_>>() .join(", ") }); let reason = get_error_reason( error_response.error_information.message, detailed_error_info, None, ); let error_message = error_response.error_information.reason; Ok(Self { response: Err(ErrorResponse { code: error_message .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: error_message.unwrap_or( hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string(), ), reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), status: enums::AttemptStatus::AuthenticationFailed, ..item.data }) } } } } impl<F> TryFrom< ResponseRouterData< F, CybersourceAuthenticateResponse, PaymentsAuthenticateData, PaymentsResponseData, >, > for RouterData<F, PaymentsAuthenticateData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CybersourceAuthenticateResponse, PaymentsAuthenticateData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response { CybersourceAuthenticateResponse::ClientAuthCheckInfo(info_response) => { let status = enums::AttemptStatus::from(info_response.status); let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { let response = Err(get_error_response( &info_response.error_information, &None, &risk_info, Some(status), item.http_code, info_response.id.clone(), )); Ok(Self { status, response, ..item.data }) } else { let connector_response_reference_id = Some( info_response .client_reference_information .code .unwrap_or(info_response.id.clone()), ); let redirection_data = match ( info_response .consumer_authentication_information .access_token, info_response .consumer_authentication_information .step_up_url, ) { (Some(token), Some(step_up_url)) => { Some(RedirectForm::CybersourceConsumerAuth { access_token: token.expose(), step_up_url, }) } _ => None, }; let three_ds_data = serde_json::to_value( info_response .consumer_authentication_information .validate_response, ) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!({ "three_ds_data": three_ds_data })), network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } CybersourceAuthenticateResponse::ErrorInformation(error_response) => { let detailed_error_info = error_response .error_information .details .to_owned() .map(|details| { details .iter() .map(|details| format!("{} : {}", details.field, details.reason)) .collect::<Vec<_>>() .join(", ") }); let reason = get_error_reason( error_response.error_information.message, detailed_error_info, None, ); let error_message = error_response.error_information.reason.to_owned(); let response = Err(ErrorResponse { code: error_message .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: error_message .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); Ok(Self { response, status: enums::AttemptStatus::AuthenticationFailed, ..item.data }) } } } } impl<F> TryFrom< ResponseRouterData< F, CybersourceAuthenticateResponse, PaymentsPostAuthenticateData, PaymentsResponseData, >, > for RouterData<F, PaymentsPostAuthenticateData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CybersourceAuthenticateResponse, PaymentsPostAuthenticateData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response { CybersourceAuthenticateResponse::ClientAuthCheckInfo(info_response) => { let status = enums::AttemptStatus::from(info_response.status); let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { let response = Err(get_error_response( &info_response.error_information, &None, &risk_info, Some(status), item.http_code, info_response.id.clone(), )); Ok(Self { status, response, ..item.data }) } else { let connector_response_reference_id = Some( info_response .client_reference_information .code .unwrap_or(info_response.id.clone()), ); let redirection_data = match ( info_response .consumer_authentication_information .access_token, info_response .consumer_authentication_information .step_up_url, ) { (Some(token), Some(step_up_url)) => { Some(RedirectForm::CybersourceConsumerAuth { access_token: token.expose(), step_up_url, }) } _ => None, }; let three_ds_data = serde_json::to_value( info_response .consumer_authentication_information .validate_response, ) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!({ "three_ds_data": three_ds_data })), network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } CybersourceAuthenticateResponse::ErrorInformation(error_response) => { let detailed_error_info = error_response .error_information .details .to_owned() .map(|details| { details .iter() .map(|details| format!("{} : {}", details.field, details.reason)) .collect::<Vec<_>>() .join(", ") }); let reason = get_error_reason( error_response.error_information.message, detailed_error_info, None, ); let error_message = error_response.error_information.reason.to_owned(); let response = Err(ErrorResponse { code: error_message .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: error_message .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); Ok(Self { response, status: enums::AttemptStatus::AuthenticationFailed, ..item.data }) } } } } impl<F> TryFrom< ResponseRouterData< F, CybersourceTransactionResponse, PaymentsSyncData, PaymentsResponseData, >, > for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, CybersourceTransactionResponse, PaymentsSyncData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response.application_information.status { Some(status) => { let status = map_cybersource_attempt_status(status, item.data.request.is_auto_capture()?); let incremental_authorization_allowed = Some(status == enums::AttemptStatus::Authorized); let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { Ok(Self { response: Err(get_error_response( &item.response.error_information, &item.response.processor_information, &risk_info, Some(status), item.http_code, item.response.id.clone(), )), status: enums::AttemptStatus::Failure, ..item.data }) } else { Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item .response .client_reference_information .map(|cref| cref.code) .unwrap_or(Some(item.response.id)), incremental_authorization_allowed, charges: None, }), ..item.data }) } } None => Ok(Self { status: item.data.status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, charges: None, }), ..item.data }), } } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceRefundRequest { order_information: OrderInformation, client_reference_information: ClientReferenceInformation, } impl<F> TryFrom<&CybersourceRouterData<&RefundsRouterData<F>>> for CybersourceRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &CybersourceRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { order_information: OrderInformation { amount_details: Amount { total_amount: item.amount.clone(), currency: item.router_data.request.currency, }, }, client_reference_information: ClientReferenceInformation { code: Some(item.router_data.request.refund_id.clone()), }, }) } } impl From<CybersourceRefundStatus> for enums::RefundStatus { fn from(item: CybersourceRefundStatus) -> Self { match item { CybersourceRefundStatus::Succeeded | CybersourceRefundStatus::Transmitted => { Self::Success } CybersourceRefundStatus::Cancelled | CybersourceRefundStatus::Failed | CybersourceRefundStatus::Voided => Self::Failure, CybersourceRefundStatus::Pending => Self::Pending, } } } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CybersourceRefundStatus { Succeeded, Transmitted, Failed, Pending, Voided, Cancelled, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceRefundResponse { id: String, status: CybersourceRefundStatus, error_information: Option<CybersourceErrorInformation>, } impl TryFrom<RefundsResponseRouterData<Execute, CybersourceRefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, CybersourceRefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status.clone()); let response = if utils::is_refund_failure(refund_status) { Err(get_error_response( &item.response.error_information, &None, &None, None, item.http_code, item.response.id.clone(), )) } else { Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status: enums::RefundStatus::from(item.response.status), }) }; Ok(Self { response, ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RsyncApplicationInformation { status: Option<CybersourceRefundStatus>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceRsyncResponse { id: String, application_information: Option<RsyncApplicationInformation>, error_information: Option<CybersourceErrorInformation>, } impl TryFrom<RefundsResponseRouterData<RSync, CybersourceRsyncResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, CybersourceRsyncResponse>, ) -> Result<Self, Self::Error> { let response = match item .response .application_information .and_then(|application_information| application_information.status) { Some(status) => { let refund_status = enums::RefundStatus::from(status.clone()); if utils::is_refund_failure(refund_status) { if status == CybersourceRefundStatus::Voided { Err(get_error_response( &Some(CybersourceErrorInformation { message: Some(constants::REFUND_VOIDED.to_string()), reason: Some(constants::REFUND_VOIDED.to_string()), details: None, }), &None, &None, None, item.http_code, item.response.id.clone(), )) } else { Err(get_error_response( &item.response.error_information, &None, &None, None, item.http_code, item.response.id.clone(), )) } } else { Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }) } } None => Ok(RefundsResponseData { connector_refund_id: item.response.id.clone(), refund_status: match item.data.response { Ok(response) => response.refund_status, Err(_) => common_enums::RefundStatus::Pending, }, }), }; Ok(Self { response, ..item.data }) } } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePayoutFulfillRequest { client_reference_information: ClientReferenceInformation, order_information: OrderInformation, recipient_information: CybersourceRecipientInfo, sender_information: CybersourceSenderInfo, processing_information: CybersourceProcessingInfo, payment_information: PaymentInformation, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceRecipientInfo { first_name: Secret<String>, last_name: Secret<String>, address1: Secret<String>, locality: String, administrative_area: Secret<String>, postal_code: Secret<String>, country: enums::CountryAlpha2, phone_number: Option<Secret<String>>, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceSenderInfo { reference_number: String, account: CybersourceAccountInfo, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceAccountInfo { funds_source: CybersourcePayoutFundSourceType, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] pub enum CybersourcePayoutFundSourceType { #[serde(rename = "05")] Disbursement, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceProcessingInfo { business_application_id: CybersourcePayoutBusinessType, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] pub enum CybersourcePayoutBusinessType { #[serde(rename = "PP")] PersonToPerson, #[serde(rename = "AA")] AccountToAccount, } #[cfg(feature = "payouts")] impl TryFrom<&CybersourceRouterData<&PayoutsRouterData<PoFulfill>>> for CybersourcePayoutFulfillRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CybersourceRouterData<&PayoutsRouterData<PoFulfill>>, ) -> Result<Self, Self::Error> { let payout_type = item.router_data.request.get_payout_type()?; match payout_type { enums::PayoutType::Card => { let client_reference_information = ClientReferenceInformation { code: Some(item.router_data.connector_request_reference_id.clone()), }; let order_information = OrderInformation { amount_details: Amount { total_amount: item.amount.to_owned(), currency: item.router_data.request.destination_currency, }, }; let billing_address = item.router_data.get_billing_address()?; let phone_address = item.router_data.get_billing_phone()?; let recipient_information = CybersourceRecipientInfo::try_from((billing_address, phone_address))?; let sender_information = CybersourceSenderInfo { reference_number: item.router_data.connector_request_reference_id.clone(), account: CybersourceAccountInfo { funds_source: CybersourcePayoutFundSourceType::Disbursement, }, }; let processing_information = CybersourceProcessingInfo { business_application_id: CybersourcePayoutBusinessType::PersonToPerson, // this means sender and receiver are different }; let payout_method_data = item.router_data.get_payout_method_data()?; let payment_information = PaymentInformation::try_from(payout_method_data)?; Ok(Self { client_reference_information, order_information, recipient_information, sender_information, processing_information, payment_information, }) } enums::PayoutType::Bank | enums::PayoutType::Wallet | enums::PayoutType::BankRedirect => Err(errors::ConnectorError::NotSupported { message: "PayoutType is not supported".to_string(), connector: "Cybersource", })?, } } } #[cfg(feature = "payouts")] impl TryFrom<(&AddressDetails, &PhoneDetails)> for CybersourceRecipientInfo { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: (&AddressDetails, &PhoneDetails)) -> Result<Self, Self::Error> { let (billing_address, phone_address) = item; Ok(Self { first_name: billing_address.get_first_name()?.to_owned(), last_name: billing_address.get_last_name()?.to_owned(), address1: billing_address.get_line1()?.to_owned(), locality: billing_address.get_city()?.to_owned(), administrative_area: { billing_address .to_state_code_as_optional() .unwrap_or_else(|_| { billing_address .state .remove_new_line() .as_ref() .map(|state| truncate_string(state, 20)) //NOTE: Cybersource connector throws error if billing state exceeds 20 characters, so truncation is done to avoid payment failure }) .ok_or_else(|| errors::ConnectorError::MissingRequiredField { field_name: "billing_address.state", })? }, postal_code: billing_address.get_zip()?.to_owned(), country: billing_address.get_country()?.to_owned(), phone_number: phone_address.number.clone(), }) } } #[cfg(feature = "payouts")] impl TryFrom<PayoutMethodData> for PaymentInformation { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: PayoutMethodData) -> Result<Self, Self::Error> { match item { PayoutMethodData::Card(card_details) => { let card_issuer = card_details.get_card_issuer().ok(); let card_type = card_issuer.map(String::from); let card = Card { number: card_details.card_number, expiration_month: card_details.expiry_month, expiration_year: card_details.expiry_year, security_code: None, card_type, type_selection_indicator: None, }; Ok(Self::Cards(Box::new(CardPaymentInformation { card }))) } PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) | PayoutMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotSupported { message: "PayoutMethod is not supported".to_string(), connector: "Cybersource", })?, } } } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceFulfillResponse { id: String, status: CybersourcePayoutStatus, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CybersourcePayoutStatus { Accepted, Declined, InvalidRequest, } #[cfg(feature = "payouts")] fn map_payout_status(status: CybersourcePayoutStatus) -> enums::PayoutStatus { match status { CybersourcePayoutStatus::Accepted => enums::PayoutStatus::Success, CybersourcePayoutStatus::Declined | CybersourcePayoutStatus::InvalidRequest => { enums::PayoutStatus::Failed } } } #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, CybersourceFulfillResponse>> for PayoutsRouterData<F> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PayoutsResponseRouterData<F, CybersourceFulfillResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PayoutsResponseData { status: Some(map_payout_status(item.response.status)), connector_payout_id: Some(item.response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceStandardErrorResponse { pub error_information: Option<ErrorInformation>, pub status: Option<String>, pub message: Option<String>, pub reason: Option<String>, pub details: Option<Vec<Details>>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceNotAvailableErrorResponse { pub errors: Vec<CybersourceNotAvailableErrorObject>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceNotAvailableErrorObject { #[serde(rename = "type")] pub error_type: Option<String>, pub message: Option<String>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceServerErrorResponse { pub status: Option<String>, pub message: Option<String>, pub reason: Option<Reason>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum Reason { SystemError, ServerTimeout, ServiceTimeout, } #[derive(Debug, Deserialize, Serialize)] pub struct CybersourceAuthenticationErrorResponse { pub response: AuthenticationErrorInformation, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum CybersourceErrorResponse { AuthenticationError(Box<CybersourceAuthenticationErrorResponse>), //If the request resource is not available/exists in cybersource NotAvailableError(Box<CybersourceNotAvailableErrorResponse>), StandardError(Box<CybersourceStandardErrorResponse>), } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct Details { pub field: String, pub reason: String, } #[derive(Debug, Default, Deserialize, Serialize)] pub struct ErrorInformation { pub message: String, pub reason: String, pub details: Option<Vec<Details>>, } #[derive(Debug, Default, Deserialize, Serialize)] pub struct AuthenticationErrorInformation { pub rmsg: String, } pub fn get_error_response( error_data: &Option<CybersourceErrorInformation>, processor_information: &Option<ClientProcessorInformation>, risk_information: &Option<ClientRiskInformation>, attempt_status: Option<enums::AttemptStatus>, status_code: u16, transaction_id: String, ) -> ErrorResponse { let avs_message = risk_information .clone() .map(|client_risk_information| { client_risk_information.rules.map(|rules| { rules .iter() .map(|risk_info| { risk_info.name.clone().map_or("".to_string(), |name| { format!(" , {}", name.clone().expose()) }) }) .collect::<Vec<String>>() .join("") }) }) .unwrap_or(Some("".to_string())); let detailed_error_info = error_data.as_ref().and_then(|error_data| { error_data.details.as_ref().map(|details| { details .iter() .map(|detail| format!("{} : {}", detail.field, detail.reason)) .collect::<Vec<_>>() .join(", ") }) }); let network_decline_code = processor_information .as_ref() .and_then(|info| info.response_code.clone()); let network_advice_code = processor_information.as_ref().and_then(|info| { info.merchant_advice .as_ref() .and_then(|merchant_advice| merchant_advice.code_raw.clone()) }); let reason = get_error_reason( error_data .as_ref() .and_then(|error_info| error_info.message.clone()), detailed_error_info, avs_message, ); let error_message = error_data .as_ref() .and_then(|error_info| error_info.reason.clone()); ErrorResponse { code: error_message .clone() .unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: error_message .unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), reason, status_code, attempt_status, connector_transaction_id: Some(transaction_id), network_advice_code, network_decline_code, network_error_message: None, connector_metadata: None, } } pub fn get_error_reason( error_info: Option<String>, detailed_error_info: Option<String>, avs_error_info: Option<String>, ) -> Option<String> { match (error_info, detailed_error_info, avs_error_info) { (Some(message), Some(details), Some(avs_message)) => Some(format!( "{message}, detailed_error_information: {details}, avs_message: {avs_message}", )), (Some(message), Some(details), None) => { Some(format!("{message}, detailed_error_information: {details}")) } (Some(message), None, Some(avs_message)) => { Some(format!("{message}, avs_message: {avs_message}")) } (None, Some(details), Some(avs_message)) => { Some(format!("{details}, avs_message: {avs_message}")) } (Some(message), None, None) => Some(message), (None, Some(details), None) => Some(details), (None, None, Some(avs_message)) => Some(avs_message), (None, None, None) => None, } } fn get_cybersource_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> { match card_network { common_enums::CardNetwork::Visa => Some("001"), common_enums::CardNetwork::Mastercard => Some("002"), common_enums::CardNetwork::AmericanExpress => Some("003"), common_enums::CardNetwork::JCB => Some("007"), common_enums::CardNetwork::DinersClub => Some("005"), common_enums::CardNetwork::Discover => Some("004"), common_enums::CardNetwork::CartesBancaires => Some("036"), common_enums::CardNetwork::UnionPay => Some("062"), //"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024" common_enums::CardNetwork::Maestro => Some("042"), common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay | common_enums::CardNetwork::Star | common_enums::CardNetwork::Accel | common_enums::CardNetwork::Pulse | common_enums::CardNetwork::Nyce => None, } } pub trait RemoveNewLine { fn remove_new_line(&self) -> Self; } impl RemoveNewLine for Option<Secret<String>> { fn remove_new_line(&self) -> Self { self.clone().map(|masked_value| { let new_string = masked_value.expose().replace("\n", " "); Secret::new(new_string) }) } } impl RemoveNewLine for Option<String> { fn remove_new_line(&self) -> Self { self.clone().map(|value| value.replace("\n", " ")) } }
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
hyperswitch_connectors::src::connectors::cybersource::transformers
38,030
true
// File: crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs // Module: hyperswitch_connectors::src::connectors::cryptopay::transformers use common_enums::enums; use common_utils::{ pii, types::{MinorUnit, StringMajorUnit}, }; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm}, types, }; use hyperswitch_interfaces::{consts, errors}; use masking::Secret; use reqwest::Url; use serde::{Deserialize, Serialize}; use crate::{ types::ResponseRouterData, utils::{self, CryptoData, ForeignTryFrom, PaymentsAuthorizeRequestData}, }; #[derive(Debug, Serialize)] pub struct CryptopayRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for CryptopayRouterData<T> { fn from((amount, item): (StringMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Default, Debug, Serialize)] pub struct CryptopayPaymentsRequest { price_amount: StringMajorUnit, price_currency: enums::Currency, pay_currency: String, #[serde(skip_serializing_if = "Option::is_none")] network: Option<String>, success_redirect_url: Option<String>, unsuccess_redirect_url: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] metadata: Option<pii::SecretSerdeValue>, custom_id: String, } impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> for CryptopayPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CryptopayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let cryptopay_request = match item.router_data.request.payment_method_data { PaymentMethodData::Crypto(ref cryptodata) => { let pay_currency = cryptodata.get_pay_currency()?; Ok(Self { price_amount: item.amount.clone(), price_currency: item.router_data.request.currency, pay_currency, network: cryptodata.network.to_owned(), success_redirect_url: item.router_data.request.router_return_url.clone(), unsuccess_redirect_url: item.router_data.request.router_return_url.clone(), //Cryptopay only accepts metadata as Object. If any other type, payment will fail with error. metadata: item.router_data.request.get_metadata_as_object(), custom_id: item.router_data.connector_request_reference_id.clone(), }) } PaymentMethodData::Card(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("CryptoPay"), )) } }?; Ok(cryptopay_request) } } // Auth Struct pub struct CryptopayAuthType { pub(super) api_key: Secret<String>, pub(super) api_secret: Secret<String>, } impl TryFrom<&ConnectorAuthType> for CryptopayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { Ok(Self { api_key: api_key.to_owned(), api_secret: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } } } // PaymentsResponse #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum CryptopayPaymentStatus { New, Completed, Unresolved, Refunded, Cancelled, } impl From<CryptopayPaymentStatus> for enums::AttemptStatus { fn from(item: CryptopayPaymentStatus) -> Self { match item { CryptopayPaymentStatus::New => Self::AuthenticationPending, CryptopayPaymentStatus::Completed => Self::Charged, CryptopayPaymentStatus::Cancelled => Self::Failure, CryptopayPaymentStatus::Unresolved | CryptopayPaymentStatus::Refunded => { Self::Unresolved } //mapped refunded to Unresolved because refund api is not available, also merchant has done the action on the connector dashboard. } } } #[derive(Debug, Serialize, Deserialize)] pub struct CryptopayPaymentsResponse { pub data: CryptopayPaymentResponseData, } impl<F, T> ForeignTryFrom<( ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>, Option<MinorUnit>, )> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from( (item, amount_captured_in_minor_units): ( ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>, Option<MinorUnit>, ), ) -> Result<Self, Self::Error> { let status = enums::AttemptStatus::from(item.response.data.status.clone()); let response = if utils::is_payment_failure(status) { let payment_response = &item.response.data; Err(ErrorResponse { code: payment_response .name .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), message: payment_response .status_context .clone() .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: payment_response.status_context.clone(), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(payment_response.id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { let redirection_data = item .response .data .hosted_page_url .map(|x| RedirectForm::from((x, common_utils::request::Method::Get))); Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.data.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item .response .data .custom_id .or(Some(item.response.data.id)), incremental_authorization_allowed: None, charges: None, }) }; match (amount_captured_in_minor_units, status) { (Some(minor_amount), enums::AttemptStatus::Charged) => { let amount_captured = Some(minor_amount.get_amount_as_i64()); Ok(Self { status, response, amount_captured, minor_amount_captured: amount_captured_in_minor_units, ..item.data }) } _ => Ok(Self { status, response, ..item.data }), } } } #[derive(Default, Debug, Serialize, Deserialize)] pub struct CryptopayErrorData { pub code: String, pub message: String, pub reason: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct CryptopayErrorResponse { pub error: CryptopayErrorData, } #[derive(Debug, Serialize, Deserialize)] pub struct CryptopayPaymentResponseData { pub id: String, pub custom_id: Option<String>, pub customer_id: Option<String>, pub status: CryptopayPaymentStatus, pub status_context: Option<String>, pub address: Option<Secret<String>>, pub network: Option<String>, pub uri: Option<String>, pub price_amount: Option<StringMajorUnit>, pub price_currency: Option<String>, pub pay_amount: Option<StringMajorUnit>, pub pay_currency: Option<String>, pub fee: Option<String>, pub fee_currency: Option<String>, pub paid_amount: Option<String>, pub name: Option<String>, pub description: Option<String>, pub success_redirect_url: Option<String>, pub unsuccess_redirect_url: Option<String>, pub hosted_page_url: Option<Url>, pub created_at: Option<String>, pub expires_at: Option<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct CryptopayWebhookDetails { #[serde(rename = "type")] pub service_type: String, pub event: WebhookEvent, pub data: CryptopayPaymentResponseData, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum WebhookEvent { TransactionCreated, TransactionConfirmed, StatusChanged, }
crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
hyperswitch_connectors::src::connectors::cryptopay::transformers
2,081
true
// File: crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs // Module: hyperswitch_connectors::src::connectors::paystack::transformers use common_enums::{enums, Currency}; use common_utils::{pii::Email, request::Method, types::MinorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankRedirectData, PaymentMethodData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::PaymentsAuthorizeRequestData, }; pub struct PaystackRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> From<(MinorUnit, T)> for PaystackRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { //Todo : use utils to convert the amount to the type of amount that a connector accepts Self { amount, router_data: item, } } } #[derive(Default, Debug, Serialize, PartialEq)] pub struct PaystackEftProvider { provider: String, } #[derive(Default, Debug, Serialize, PartialEq)] pub struct PaystackPaymentsRequest { amount: MinorUnit, currency: Currency, email: Email, eft: PaystackEftProvider, } impl TryFrom<&PaystackRouterData<&PaymentsAuthorizeRouterData>> for PaystackPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaystackRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::BankRedirect(BankRedirectData::Eft { provider }) => { let email = item.router_data.request.get_email()?; let eft = PaystackEftProvider { provider }; Ok(Self { amount: item.amount, currency: item.router_data.request.currency, email, eft, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } pub struct PaystackAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for PaystackAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PaystackEftRedirect { reference: String, status: String, url: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PaystackPaymentsResponseData { status: bool, message: String, data: PaystackEftRedirect, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(untagged)] pub enum PaystackPaymentsResponse { PaystackPaymentsData(PaystackPaymentsResponseData), PaystackPaymentsError(PaystackErrorResponse), } impl<F, T> TryFrom<ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let (status, response) = match item.response { PaystackPaymentsResponse::PaystackPaymentsData(resp) => { let redirection_url = Url::parse(resp.data.url.as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let redirection_data = RedirectForm::from((redirection_url, Method::Get)); ( common_enums::AttemptStatus::AuthenticationPending, Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( resp.data.reference.clone(), ), redirection_data: Box::new(Some(redirection_data)), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ) } PaystackPaymentsResponse::PaystackPaymentsError(err) => { let err_msg = get_error_message(err.clone()); ( common_enums::AttemptStatus::Failure, Err(ErrorResponse { code: err.code, message: err_msg.clone(), reason: Some(err_msg.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ) } }; Ok(Self { status, response, ..item.data }) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum PaystackPSyncStatus { Abandoned, Failed, Ongoing, Pending, Processing, Queued, Reversed, Success, } impl From<PaystackPSyncStatus> for common_enums::AttemptStatus { fn from(item: PaystackPSyncStatus) -> Self { match item { PaystackPSyncStatus::Success => Self::Charged, PaystackPSyncStatus::Abandoned => Self::AuthenticationPending, PaystackPSyncStatus::Ongoing | PaystackPSyncStatus::Pending | PaystackPSyncStatus::Processing | PaystackPSyncStatus::Queued => Self::Pending, PaystackPSyncStatus::Failed => Self::Failure, PaystackPSyncStatus::Reversed => Self::Voided, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PaystackPSyncData { status: PaystackPSyncStatus, reference: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PaystackPSyncResponseData { status: bool, message: String, data: PaystackPSyncData, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(untagged)] pub enum PaystackPSyncResponse { PaystackPSyncData(PaystackPSyncResponseData), PaystackPSyncWebhook(PaystackPaymentWebhookData), PaystackPSyncError(PaystackErrorResponse), } impl<F, T> TryFrom<ResponseRouterData<F, PaystackPSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaystackPSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response { PaystackPSyncResponse::PaystackPSyncData(resp) => Ok(Self { status: common_enums::AttemptStatus::from(resp.data.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(resp.data.reference.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), PaystackPSyncResponse::PaystackPSyncWebhook(resp) => Ok(Self { status: common_enums::AttemptStatus::from(resp.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(resp.reference.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), PaystackPSyncResponse::PaystackPSyncError(err) => { let err_msg = get_error_message(err.clone()); Ok(Self { response: Err(ErrorResponse { code: err.code, message: err_msg.clone(), reason: Some(err_msg.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct PaystackRefundRequest { pub transaction: String, pub amount: MinorUnit, } impl<F> TryFrom<&PaystackRouterData<&RefundsRouterData<F>>> for PaystackRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaystackRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { transaction: item.router_data.request.connector_transaction_id.clone(), amount: item.amount.to_owned(), }) } } #[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)] #[serde(rename_all = "lowercase")] pub enum PaystackRefundStatus { Processed, Failed, #[default] Processing, Pending, } impl From<PaystackRefundStatus> for enums::RefundStatus { fn from(item: PaystackRefundStatus) -> Self { match item { PaystackRefundStatus::Processed => Self::Success, PaystackRefundStatus::Failed => Self::Failure, PaystackRefundStatus::Processing | PaystackRefundStatus::Pending => Self::Pending, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PaystackRefundsData { status: PaystackRefundStatus, id: i64, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PaystackRefundsResponseData { status: bool, message: String, data: PaystackRefundsData, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(untagged)] pub enum PaystackRefundsResponse { PaystackRefundsData(PaystackRefundsResponseData), PaystackRSyncWebhook(PaystackRefundWebhookData), PaystackRefundsError(PaystackErrorResponse), } impl TryFrom<RefundsResponseRouterData<Execute, PaystackRefundsResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, PaystackRefundsResponse>, ) -> Result<Self, Self::Error> { match item.response { PaystackRefundsResponse::PaystackRefundsData(resp) => Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: resp.data.id.to_string(), refund_status: enums::RefundStatus::from(resp.data.status), }), ..item.data }), PaystackRefundsResponse::PaystackRSyncWebhook(resp) => Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: resp.id, refund_status: enums::RefundStatus::from(resp.status), }), ..item.data }), PaystackRefundsResponse::PaystackRefundsError(err) => { let err_msg = get_error_message(err.clone()); Ok(Self { response: Err(ErrorResponse { code: err.code, message: err_msg.clone(), reason: Some(err_msg.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } } impl TryFrom<RefundsResponseRouterData<RSync, PaystackRefundsResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, PaystackRefundsResponse>, ) -> Result<Self, Self::Error> { match item.response { PaystackRefundsResponse::PaystackRefundsData(resp) => Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: resp.data.id.to_string(), refund_status: enums::RefundStatus::from(resp.data.status), }), ..item.data }), PaystackRefundsResponse::PaystackRSyncWebhook(resp) => Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: resp.id, refund_status: enums::RefundStatus::from(resp.status), }), ..item.data }), PaystackRefundsResponse::PaystackRefundsError(err) => { let err_msg = get_error_message(err.clone()); Ok(Self { response: Err(ErrorResponse { code: err.code, message: err_msg.clone(), reason: Some(err_msg.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } } #[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct PaystackErrorResponse { pub status: bool, pub message: String, pub data: Option<serde_json::Value>, pub meta: serde_json::Value, pub code: String, } pub fn get_error_message(response: PaystackErrorResponse) -> String { if let Some(serde_json::Value::Object(err_map)) = response.data { err_map.get("message").map(|msg| msg.clone().to_string()) } else { None } .unwrap_or(response.message) } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct PaystackPaymentWebhookData { pub status: PaystackPSyncStatus, pub reference: String, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct PaystackRefundWebhookData { pub status: PaystackRefundStatus, pub id: String, pub transaction_reference: String, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(untagged)] pub enum PaystackWebhookEventData { Payment(PaystackPaymentWebhookData), Refund(PaystackRefundWebhookData), } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct PaystackWebhookData { pub event: String, pub data: PaystackWebhookEventData, } impl From<PaystackWebhookEventData> for api_models::webhooks::IncomingWebhookEvent { fn from(item: PaystackWebhookEventData) -> Self { match item { PaystackWebhookEventData::Payment(payment_data) => match payment_data.status { PaystackPSyncStatus::Success => Self::PaymentIntentSuccess, PaystackPSyncStatus::Failed => Self::PaymentIntentFailure, PaystackPSyncStatus::Abandoned | PaystackPSyncStatus::Ongoing | PaystackPSyncStatus::Pending | PaystackPSyncStatus::Processing | PaystackPSyncStatus::Queued => Self::PaymentIntentProcessing, PaystackPSyncStatus::Reversed => Self::EventNotSupported, }, PaystackWebhookEventData::Refund(refund_data) => match refund_data.status { PaystackRefundStatus::Processed => Self::RefundSuccess, PaystackRefundStatus::Failed => Self::RefundFailure, PaystackRefundStatus::Processing | PaystackRefundStatus::Pending => { Self::EventNotSupported } }, } } }
crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs
hyperswitch_connectors::src::connectors::paystack::transformers
3,615
true
// File: crates/hyperswitch_connectors/src/connectors/calida/transformers.rs // Module: hyperswitch_connectors::src::connectors::calida::transformers use std::collections::HashMap; use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::ByteSliceExt, pii::{Email, IpAddress}, request::Method, types::FloatMajorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{self as connector_utils, PaymentsAuthorizeRequestData, RouterData as OtherRouterData}, }; pub struct CalidaRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for CalidaRouterData<T> { fn from((amount, item): (FloatMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Default, Serialize, Deserialize)] pub struct CalidaMetadataObject { pub shop_name: String, } impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for CalidaMetadataObject { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( meta_data: &Option<common_utils::pii::SecretSerdeValue>, ) -> Result<Self, Self::Error> { let metadata = connector_utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata", })?; Ok(metadata) } } #[derive(Debug, Serialize, PartialEq)] pub struct CalidaPaymentsRequest { pub amount: FloatMajorUnit, pub currency: enums::Currency, pub payment_provider: String, pub shop_name: String, pub reference: String, pub ip_address: Option<Secret<String, IpAddress>>, pub first_name: Secret<String>, pub last_name: Secret<String>, pub billing_address_country_code_iso: enums::CountryAlpha2, pub billing_address_city: String, pub billing_address_line1: Secret<String>, pub billing_address_postal_code: Secret<String>, pub webhook_url: String, pub success_url: String, pub failure_url: String, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct CalidaCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } impl TryFrom<&CalidaRouterData<&PaymentsAuthorizeRouterData>> for CalidaPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CalidaRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.capture_method { Some(enums::CaptureMethod::Manual) | Some(enums::CaptureMethod::ManualMultiple) | Some(enums::CaptureMethod::Scheduled) | Some(enums::CaptureMethod::SequentialAutomatic) => { Err(errors::ConnectorError::FlowNotSupported { flow: format!("{:?}", item.router_data.request.capture_method), connector: "Calida".to_string(), } .into()) } Some(enums::CaptureMethod::Automatic) | None => { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Wallet(WalletData::BluecodeRedirect {}) => { let calida_mca_metadata = CalidaMetadataObject::try_from(&item.router_data.connector_meta_data)?; Self::try_from((item, &calida_mca_metadata)) } _ => Err( errors::ConnectorError::NotImplemented("Payment method".to_string()).into(), ), } } } } } impl TryFrom<( &CalidaRouterData<&PaymentsAuthorizeRouterData>, &CalidaMetadataObject, )> for CalidaPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( value: ( &CalidaRouterData<&PaymentsAuthorizeRouterData>, &CalidaMetadataObject, ), ) -> Result<Self, Self::Error> { let item = value.0; Ok(Self { amount: item.amount, currency: item.router_data.request.currency, payment_provider: "bluecode_payment".to_string(), shop_name: value.1.shop_name.clone(), reference: item.router_data.payment_id.clone(), ip_address: item.router_data.request.get_ip_address_as_optional(), first_name: item.router_data.get_billing_first_name()?, last_name: item.router_data.get_billing_last_name()?, billing_address_country_code_iso: item.router_data.get_billing_country()?, billing_address_city: item.router_data.get_billing_city()?, billing_address_line1: item.router_data.get_billing_line1()?, billing_address_postal_code: item.router_data.get_billing_zip()?, webhook_url: item.router_data.request.get_webhook_url()?, success_url: item.router_data.request.get_router_return_url()?, failure_url: item.router_data.request.get_router_return_url()?, }) } } pub struct CalidaAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for CalidaAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } impl From<CalidaPaymentStatus> for common_enums::AttemptStatus { fn from(item: CalidaPaymentStatus) -> Self { match item { CalidaPaymentStatus::ManualProcessing => Self::Pending, CalidaPaymentStatus::Pending | CalidaPaymentStatus::PaymentInitiated => { Self::AuthenticationPending } CalidaPaymentStatus::Failed => Self::Failure, CalidaPaymentStatus::Completed => Self::Charged, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CalidaPaymentsResponse { pub id: i64, pub order_id: String, pub amount: FloatMajorUnit, pub currency: enums::Currency, pub charged_amount: FloatMajorUnit, pub charged_currency: enums::Currency, pub status: CalidaPaymentStatus, pub payment_link: url::Url, pub etoken: Secret<String>, pub payment_request_id: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CalidaSyncResponse { pub id: Option<i64>, pub order_id: String, pub user_id: Option<i64>, pub customer_id: Option<String>, pub customer_email: Option<Email>, pub customer_phone: Option<String>, pub status: CalidaPaymentStatus, pub payment_provider: Option<String>, pub payment_connector: Option<String>, pub payment_method: Option<String>, pub payment_method_type: Option<String>, pub shop_name: Option<String>, pub sender_name: Option<String>, pub sender_email: Option<String>, pub description: Option<String>, pub amount: FloatMajorUnit, pub currency: enums::Currency, pub charged_amount: Option<FloatMajorUnit>, pub charged_amount_currency: Option<String>, pub charged_fx_amount: Option<FloatMajorUnit>, pub charged_fx_amount_currency: Option<enums::Currency>, pub is_underpaid: Option<bool>, pub billing_amount: Option<FloatMajorUnit>, pub billing_currency: Option<String>, pub language: Option<String>, pub ip_address: Option<Secret<String, IpAddress>>, pub first_name: Option<Secret<String>>, pub last_name: Option<Secret<String>>, pub billing_address_line1: Option<Secret<String>>, pub billing_address_city: Option<Secret<String>>, pub billing_address_postal_code: Option<Secret<String>>, pub billing_address_country: Option<String>, pub billing_address_country_code_iso: Option<enums::CountryAlpha2>, pub shipping_address_country_code_iso: Option<enums::CountryAlpha2>, pub success_url: Option<String>, pub failure_url: Option<String>, pub source: Option<String>, pub bonus_code: Option<String>, pub dob: Option<String>, pub fees_amount: Option<f64>, pub fx_margin_amount: Option<f64>, pub fx_margin_percent: Option<f64>, pub fees_percent: Option<f64>, pub reseller_id: Option<String>, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CalidaPaymentStatus { Pending, PaymentInitiated, ManualProcessing, Failed, Completed, } impl<F, T> TryFrom<ResponseRouterData<F, CalidaPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, CalidaPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let url = item.response.payment_link.clone(); let redirection_data = Some(RedirectForm::from((url, Method::Get))); Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.payment_request_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl<F, T> TryFrom<ResponseRouterData<F, CalidaSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, CalidaSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: item.data.response, ..item.data }) } } #[derive(Default, Debug, Serialize)] pub struct CalidaRefundRequest { pub amount: FloatMajorUnit, } impl<F> TryFrom<&CalidaRouterData<&RefundsRouterData<F>>> for CalidaRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &CalidaRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct CalidaErrorResponse { pub message: String, pub context_data: HashMap<String, Value>, } pub(crate) fn get_calida_webhook_event( status: CalidaPaymentStatus, ) -> api_models::webhooks::IncomingWebhookEvent { match status { CalidaPaymentStatus::Completed => { api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess } CalidaPaymentStatus::PaymentInitiated | CalidaPaymentStatus::ManualProcessing | CalidaPaymentStatus::Pending => { api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing } CalidaPaymentStatus::Failed => { api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure } } } pub(crate) fn get_webhook_object_from_body( body: &[u8], ) -> CustomResult<CalidaSyncResponse, common_utils::errors::ParsingError> { let webhook: CalidaSyncResponse = body.parse_struct("CalidaIncomingWebhook")?; Ok(webhook) } pub fn sort_and_minify_json(value: &Value) -> Result<String, errors::ConnectorError> { fn sort_value(val: &Value) -> Value { match val { Value::Object(map) => { let mut entries: Vec<_> = map.iter().collect(); entries.sort_by_key(|(k, _)| k.to_owned()); let sorted_map: Map<String, Value> = entries .into_iter() .map(|(k, v)| (k.clone(), sort_value(v))) .collect(); Value::Object(sorted_map) } Value::Array(arr) => Value::Array(arr.iter().map(sort_value).collect()), _ => val.clone(), } } let sorted_value = sort_value(value); serde_json::to_string(&sorted_value) .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed) }
crates/hyperswitch_connectors/src/connectors/calida/transformers.rs
hyperswitch_connectors::src::connectors::calida::transformers
3,356
true
// File: crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs // Module: hyperswitch_connectors::src::connectors::tokenio::transformers use std::collections::HashMap; use api_models::admin::{AdditionalMerchantData, MerchantAccountData, MerchantRecipientData}; use common_enums::enums; use common_utils::{id_type::MerchantId, request::Method, types::StringMajorUnit}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors, }; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{self}, }; //TODO: Fill the struct with respective fields pub struct TokenioRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for TokenioRouterData<T> { fn from((amount, item): (StringMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TokenioPaymentsRequest { pub initiation: PaymentInitiation, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct PaymentInitiation { pub ref_id: String, pub remittance_information_primary: MerchantId, pub amount: Amount, pub local_instrument: LocalInstrument, pub creditor: Creditor, pub callback_url: Option<String>, pub flow_type: FlowType, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Amount { pub value: StringMajorUnit, pub currency: enums::Currency, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum LocalInstrument { Sepa, SepaInstant, FasterPayments, Elixir, Bankgiro, Plusgiro, } #[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] pub enum Creditor { FasterPayments { #[serde(rename = "sortCode")] sort_code: Secret<String>, #[serde(rename = "accountNumber")] account_number: Secret<String>, name: Secret<String>, }, Sepa { iban: Secret<String>, name: Secret<String>, }, SepaInstant { iban: Secret<String>, name: Secret<String>, }, ElixirIban { iban: Secret<String>, name: Secret<String>, }, ElixirAccount { #[serde(rename = "accountNumber")] account_number: Secret<String>, name: Secret<String>, }, Bankgiro { #[serde(rename = "bankgiroNumber")] bankgiro_number: Secret<String>, name: Secret<String>, }, Plusgiro { #[serde(rename = "plusgiroNumber")] plusgiro_number: Secret<String>, name: Secret<String>, }, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum FlowType { ApiOnly, FullHostedPages, EmbeddedHostedPages, } impl TryFrom<&TokenioRouterData<&PaymentsAuthorizeRouterData>> for TokenioPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &TokenioRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::OpenBanking(_) => { let (local_instrument, creditor) = match item .router_data .additional_merchant_data .as_ref() .and_then(|data| match data { AdditionalMerchantData::OpenBankingRecipientData(recipient_data) => { match recipient_data { MerchantRecipientData::AccountData(account_data) => { Some(account_data) } _ => None, } } }) { Some(MerchantAccountData::FasterPayments { account_number, sort_code, name, .. }) => ( LocalInstrument::FasterPayments, Creditor::FasterPayments { sort_code: sort_code.clone(), account_number: account_number.clone(), name: name.clone().into(), }, ), Some(MerchantAccountData::SepaInstant { iban, name, .. }) => ( LocalInstrument::SepaInstant, Creditor::SepaInstant { iban: iban.clone(), name: name.clone().into(), }, ), Some(MerchantAccountData::Sepa { iban, name, .. }) => ( LocalInstrument::Sepa, Creditor::Sepa { iban: iban.clone(), name: name.clone().into(), }, ), Some(MerchantAccountData::Iban { iban, name, .. }) => ( LocalInstrument::Sepa, // Assuming IBAN defaults to SEPA Creditor::Sepa { iban: iban.clone(), name: name.clone().into(), }, ), Some(MerchantAccountData::Elixir { account_number, iban, name, .. }) => { if !iban.peek().is_empty() { ( LocalInstrument::Elixir, Creditor::ElixirIban { iban: iban.clone(), name: name.clone().into(), }, ) } else { ( LocalInstrument::Elixir, Creditor::ElixirAccount { account_number: account_number.clone(), name: name.clone().into(), }, ) } } Some(MerchantAccountData::Bacs { account_number, sort_code, name, .. }) => ( LocalInstrument::FasterPayments, Creditor::FasterPayments { sort_code: sort_code.clone(), account_number: account_number.clone(), name: name.clone().into(), }, ), Some(MerchantAccountData::Bankgiro { number, name, .. }) => ( LocalInstrument::Bankgiro, Creditor::Bankgiro { bankgiro_number: number.clone(), name: name.clone().into(), }, ), Some(MerchantAccountData::Plusgiro { number, name, .. }) => ( LocalInstrument::Plusgiro, Creditor::Plusgiro { plusgiro_number: number.clone(), name: name.clone().into(), }, ), None => { return Err(errors::ConnectorError::InvalidConnectorConfig { config: "No valid payment method found in additional merchant data", } .into()) } }; Ok(Self { initiation: PaymentInitiation { ref_id: utils::generate_12_digit_number().to_string(), remittance_information_primary: item.router_data.merchant_id.clone(), amount: Amount { value: item.amount.clone(), currency: item.router_data.request.currency, }, local_instrument, creditor, callback_url: item.router_data.request.router_return_url.clone(), flow_type: FlowType::FullHostedPages, }, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } pub struct TokenioAuthType { pub(super) merchant_id: Secret<String>, pub(super) private_key: Secret<String>, pub(super) key_id: Secret<String>, pub(super) key_algorithm: CryptoAlgorithm, } #[derive(Debug, Deserialize, PartialEq)] pub enum CryptoAlgorithm { RS256, ES256, #[serde(rename = "EdDSA")] EDDSA, } impl TryFrom<&str> for CryptoAlgorithm { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(s: &str) -> Result<Self, Self::Error> { match s.to_uppercase().as_str() { "RS256" | "rs256" => Ok(Self::RS256), "ES256" | "es256" => Ok(Self::ES256), "EDDSA" | "eddsa" | "EdDSA" => Ok(Self::EDDSA), _ => Err(errors::ConnectorError::InvalidConnectorConfig { config: "Unsupported key algorithm. Select from RS256, ES256, EdDSA", } .into()), } } } impl TryFrom<&ConnectorAuthType> for TokenioAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => Ok(Self { merchant_id: key1.to_owned(), private_key: api_secret.to_owned(), key_id: api_key.to_owned(), key_algorithm: CryptoAlgorithm::try_from(key2.clone().expose().as_str())?, }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Serialize, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenioApiWrapper { pub payment: PaymentResponse, } #[derive(Debug, Serialize, Clone, Deserialize)] #[serde(untagged)] pub enum TokenioPaymentsResponse { Success(TokenioApiWrapper), Error(TokenioErrorResponse), } #[derive(Debug, Serialize, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentResponse { pub id: String, pub status: PaymentStatus, pub status_reason_information: Option<String>, pub authentication: Option<Authentication>, pub error_info: Option<ErrorInfo>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaymentStatus { InitiationPending, InitiationPendingRedirectAuth, InitiationPendingRedirectAuthVerification, InitiationPendingRedirectHp, InitiationPendingRedemption, InitiationPendingRedemptionVerification, InitiationProcessing, InitiationCompleted, InitiationRejected, InitiationRejectedInsufficientFunds, InitiationFailed, InitiationDeclined, InitiationExpired, InitiationNoFinalStatusAvailable, SettlementInProgress, SettlementCompleted, SettlementIncomplete, } #[derive(Debug, Serialize, Clone, Deserialize)] #[serde(untagged)] pub enum Authentication { RedirectUrl { #[serde(rename = "redirectUrl")] redirect_url: String, }, } #[derive(Debug, Serialize, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ErrorInfo { pub http_error_code: i32, pub message: Option<String>, pub token_external_error: Option<bool>, pub token_trace_id: Option<String>, } impl From<TokenioPaymentsResponse> for common_enums::AttemptStatus { fn from(response: TokenioPaymentsResponse) -> Self { match response { TokenioPaymentsResponse::Success(wrapper) => match wrapper.payment.status { // Pending statuses - payment is still in progress PaymentStatus::InitiationPending | PaymentStatus::InitiationPendingRedirectAuth | PaymentStatus::InitiationPendingRedirectAuthVerification | PaymentStatus::InitiationPendingRedirectHp | PaymentStatus::InitiationPendingRedemption | PaymentStatus::InitiationPendingRedemptionVerification => { Self::AuthenticationPending } // Success statuses PaymentStatus::SettlementCompleted => Self::Charged, // Settlement in progress - could map to different status based on business logic PaymentStatus::SettlementInProgress => Self::Pending, // Failure statuses PaymentStatus::InitiationRejected | PaymentStatus::InitiationFailed | PaymentStatus::InitiationExpired | PaymentStatus::InitiationRejectedInsufficientFunds | PaymentStatus::InitiationDeclined => Self::Failure, // Uncertain status PaymentStatus::InitiationCompleted | PaymentStatus::InitiationProcessing | PaymentStatus::InitiationNoFinalStatusAvailable | PaymentStatus::SettlementIncomplete => Self::Pending, }, TokenioPaymentsResponse::Error(_) => Self::Failure, } } } impl<F, T> TryFrom<ResponseRouterData<F, TokenioPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, TokenioPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let status = common_enums::AttemptStatus::from(item.response.clone()); let response = match item.response { TokenioPaymentsResponse::Success(wrapper) => { let payment = wrapper.payment; if let common_enums::AttemptStatus::Failure = status { Err(ErrorResponse { code: payment .error_info .as_ref() .map(|ei| ei.http_error_code.to_string()) .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: payment .error_info .as_ref() .and_then(|ei| ei.message.clone()) .or_else(|| payment.status_reason_information.clone()) .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: Some( payment .error_info .as_ref() .and_then(|ei| ei.message.clone()) .or_else(|| payment.status_reason_information.clone()) .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), ), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(payment.id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(payment.id.clone()), redirection_data: Box::new(payment.authentication.as_ref().map(|auth| { match auth { Authentication::RedirectUrl { redirect_url } => { RedirectForm::Form { endpoint: redirect_url.to_string(), method: Method::Get, form_fields: HashMap::new(), } } } })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) } } TokenioPaymentsResponse::Error(error_response) => Err(ErrorResponse { code: error_response.get_error_code(), message: error_response.get_message(), reason: Some(error_response.get_message()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), }; Ok(Self { status, response, ..item.data }) } } #[derive(Default, Debug, Serialize)] pub struct TokenioRefundRequest { pub amount: StringMajorUnit, } impl<F> TryFrom<&TokenioRouterData<&RefundsRouterData<F>>> for TokenioRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &TokenioRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Debug, Serialize, Clone, Deserialize)] #[serde(untagged)] pub enum TokenioErrorResponse { Json { #[serde(rename = "errorCode")] error_code: Option<String>, message: Option<String>, }, Text(String), } impl TokenioErrorResponse { pub fn from_bytes(bytes: &[u8]) -> Self { // First try to parse as JSON if let Ok(json_response) = serde_json::from_slice::<Self>(bytes) { json_response } else { // If JSON parsing fails, treat as plain text let text = String::from_utf8_lossy(bytes).to_string(); Self::Text(text) } } pub fn get_message(&self) -> String { match self { Self::Json { message, error_code, } => message .as_deref() .or(error_code.as_deref()) .unwrap_or(NO_ERROR_MESSAGE) .to_string(), Self::Text(text) => text.clone(), } } pub fn get_error_code(&self) -> String { match self { Self::Json { error_code, .. } => { error_code.as_deref().unwrap_or(NO_ERROR_CODE).to_string() } Self::Text(_) => NO_ERROR_CODE.to_string(), } } } #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TokenioWebhookEventType { PaymentStatusChanged, #[serde(other)] Unknown, } #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TokenioWebhookPaymentStatus { InitiationCompleted, PaymentCompleted, PaymentFailed, PaymentCancelled, InitiationRejected, InitiationProcessing, #[serde(other)] Unknown, } // Base webhook payload structure #[derive(Debug, Deserialize, Serialize)] pub struct TokenioWebhookPayload { #[serde(rename = "eventType", skip_serializing_if = "Option::is_none")] pub event_type: Option<String>, pub id: String, #[serde(flatten)] pub event_data: TokenioWebhookEventData, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum TokenioWebhookEventData { PaymentV2 { payment: TokenioPaymentObjectV2 }, } // Payment v2 structures #[derive(Debug, Deserialize, Serialize)] pub struct TokenioPaymentObjectV2 { pub id: String, pub status: TokenioPaymentStatus, } #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TokenioPaymentStatus { InitiationCompleted, PaymentCompleted, PaymentFailed, PaymentCancelled, InitiationRejected, InitiationProcessing, InitiationPendingRedirectHp, #[serde(other)] Other, }
crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
hyperswitch_connectors::src::connectors::tokenio::transformers
4,527
true
// File: crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs // Module: hyperswitch_connectors::src::connectors::recurly::transformers #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use std::str::FromStr; use common_enums::enums; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use common_utils::types::{ConnectorTransactionId, FloatMajorUnitForConnector}; use common_utils::{ errors::CustomResult, ext_traits::ByteSliceExt, id_type, types::{FloatMajorUnit, StringMinorUnit}, }; use error_stack::ResultExt; use hyperswitch_domain_models::router_data::ConnectorAuthType; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::{ router_data_v2::flow_common_types as recovery_flow_common_types, router_flow_types::revenue_recovery as recovery_router_flows, router_request_types::revenue_recovery as recovery_request_types, router_response_types::revenue_recovery as recovery_response_types, types as recovery_router_data_types, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use crate::{types::ResponseRouterDataV2, utils}; pub struct RecurlyRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for RecurlyRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { //Todo : use utils to convert the amount to the type of amount that a connector accepts Self { amount, router_data: item, } } } // Auth Struct pub struct RecurlyAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for RecurlyAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct RecurlyErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct RecurlyWebhookBody { // Transaction uuid pub uuid: String, pub event_type: RecurlyPaymentEventType, } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] pub enum RecurlyPaymentEventType { #[serde(rename = "succeeded")] PaymentSucceeded, #[serde(rename = "failed")] PaymentFailed, } impl RecurlyWebhookBody { pub fn get_webhook_object_from_body(body: &[u8]) -> CustomResult<Self, errors::ConnectorError> { let webhook_body = body .parse_struct::<Self>("RecurlyWebhookBody") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(webhook_body) } } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] pub enum RecurlyChargeStatus { #[serde(rename = "success")] Succeeded, #[serde(rename = "declined")] Failed, } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum RecurlyFundingTypes { Credit, Debit, } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum RecurlyPaymentObject { CreditCard, } #[derive(Debug, Serialize, Deserialize)] pub struct RecurlyRecoveryDetailsData { pub amount: FloatMajorUnit, pub currency: common_enums::Currency, pub id: String, pub status_code: Option<String>, pub status_message: Option<String>, pub account: Account, pub invoice: Invoice, pub payment_method: PaymentMethod, pub payment_gateway: PaymentGateway, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, pub status: RecurlyChargeStatus, } #[derive(Debug, Serialize, Deserialize)] pub struct PaymentMethod { pub gateway_token: String, pub funding_source: RecurlyFundingTypes, pub object: RecurlyPaymentObject, pub card_type: common_enums::CardNetwork, pub first_six: String, } #[derive(Debug, Serialize, Deserialize)] pub struct Invoice { pub id: String, } #[derive(Debug, Serialize, Deserialize)] pub struct Account { pub id: String, } #[derive(Debug, Serialize, Deserialize)] pub struct PaymentGateway { pub id: String, } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl TryFrom< ResponseRouterDataV2< recovery_router_flows::BillingConnectorPaymentsSync, RecurlyRecoveryDetailsData, recovery_flow_common_types::BillingConnectorPaymentsSyncFlowData, recovery_request_types::BillingConnectorPaymentsSyncRequest, recovery_response_types::BillingConnectorPaymentsSyncResponse, >, > for recovery_router_data_types::BillingConnectorPaymentsSyncRouterDataV2 { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterDataV2< recovery_router_flows::BillingConnectorPaymentsSync, RecurlyRecoveryDetailsData, recovery_flow_common_types::BillingConnectorPaymentsSyncFlowData, recovery_request_types::BillingConnectorPaymentsSyncRequest, recovery_response_types::BillingConnectorPaymentsSyncResponse, >, ) -> Result<Self, Self::Error> { let merchant_reference_id = id_type::PaymentReferenceId::from_str(&item.response.invoice.id) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let connector_transaction_id = Some(ConnectorTransactionId::from(item.response.id)); Ok(Self { response: Ok( recovery_response_types::BillingConnectorPaymentsSyncResponse { status: item.response.status.into(), amount: utils::convert_back_amount_to_minor_units( &FloatMajorUnitForConnector, item.response.amount, item.response.currency, )?, currency: item.response.currency, merchant_reference_id, connector_account_reference_id: item.response.payment_gateway.id, connector_transaction_id, error_code: item.response.status_code, error_message: item.response.status_message, processor_payment_method_token: item.response.payment_method.gateway_token, connector_customer_id: item.response.account.id, transaction_created_at: Some(item.response.created_at), payment_method_sub_type: common_enums::PaymentMethodType::from( item.response.payment_method.funding_source, ), payment_method_type: common_enums::PaymentMethod::from( item.response.payment_method.object, ), // This none because this field is specific to stripebilling. charge_id: None, // Need to populate these card info field card_info: api_models::payments::AdditionalCardInfo { card_network: Some(item.response.payment_method.card_type), card_isin: Some(item.response.payment_method.first_six), card_issuer: None, card_type: None, card_issuing_country: None, bank_code: None, last4: None, card_extended_bin: None, card_exp_month: None, card_exp_year: None, card_holder_name: None, payment_checks: None, authentication_data: None, is_regulated: None, signature_network: None, }, }, ), ..item.data }) } } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl From<RecurlyChargeStatus> for enums::AttemptStatus { fn from(status: RecurlyChargeStatus) -> Self { match status { RecurlyChargeStatus::Succeeded => Self::Charged, RecurlyChargeStatus::Failed => Self::Failure, } } } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl From<RecurlyFundingTypes> for common_enums::PaymentMethodType { fn from(funding: RecurlyFundingTypes) -> Self { match funding { RecurlyFundingTypes::Credit => Self::Credit, RecurlyFundingTypes::Debit => Self::Debit, } } } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl From<RecurlyPaymentObject> for common_enums::PaymentMethod { fn from(funding: RecurlyPaymentObject) -> Self { match funding { RecurlyPaymentObject::CreditCard => Self::Card, } } } #[derive(Debug, Serialize, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum RecurlyRecordStatus { Success, Failure, } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl TryFrom<enums::AttemptStatus> for RecurlyRecordStatus { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(status: enums::AttemptStatus) -> Result<Self, Self::Error> { match status { enums::AttemptStatus::Charged | enums::AttemptStatus::PartialCharged | enums::AttemptStatus::PartialChargedAndChargeable => Ok(Self::Success), enums::AttemptStatus::Failure | enums::AttemptStatus::CaptureFailed | enums::AttemptStatus::RouterDeclined => Ok(Self::Failure), enums::AttemptStatus::AuthenticationFailed | enums::AttemptStatus::Started | enums::AttemptStatus::AuthenticationPending | enums::AttemptStatus::AuthenticationSuccessful | enums::AttemptStatus::Authorized | enums::AttemptStatus::PartiallyAuthorized | enums::AttemptStatus::AuthorizationFailed | enums::AttemptStatus::Authorizing | enums::AttemptStatus::CodInitiated | enums::AttemptStatus::Voided | enums::AttemptStatus::VoidedPostCharge | enums::AttemptStatus::VoidInitiated | enums::AttemptStatus::CaptureInitiated | enums::AttemptStatus::VoidFailed | enums::AttemptStatus::AutoRefunded | enums::AttemptStatus::Unresolved | enums::AttemptStatus::Pending | enums::AttemptStatus::PaymentMethodAwaited | enums::AttemptStatus::ConfirmationAwaited | enums::AttemptStatus::DeviceDataCollectionPending | enums::AttemptStatus::IntegrityFailure | enums::AttemptStatus::Expired => Err(errors::ConnectorError::NotSupported { message: "Record back flow is only supported for terminal status".to_string(), connector: "recurly", } .into()), } } } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct RecurlyRecordBackResponse { // Invoice id pub id: id_type::PaymentReferenceId, } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl TryFrom< ResponseRouterDataV2< recovery_router_flows::InvoiceRecordBack, RecurlyRecordBackResponse, recovery_flow_common_types::InvoiceRecordBackData, recovery_request_types::InvoiceRecordBackRequest, recovery_response_types::InvoiceRecordBackResponse, >, > for recovery_router_data_types::InvoiceRecordBackRouterDataV2 { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterDataV2< recovery_router_flows::InvoiceRecordBack, RecurlyRecordBackResponse, recovery_flow_common_types::InvoiceRecordBackData, recovery_request_types::InvoiceRecordBackRequest, recovery_response_types::InvoiceRecordBackResponse, >, ) -> Result<Self, Self::Error> { let merchant_reference_id = item.response.id; Ok(Self { response: Ok(recovery_response_types::InvoiceRecordBackResponse { merchant_reference_id, }), ..item.data }) } } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct RecurlyInvoiceSyncResponse { pub id: String, pub total: FloatMajorUnit, pub currency: common_enums::Currency, pub address: Option<RecurlyInvoiceBillingAddress>, pub line_items: Vec<RecurlyLineItems>, pub transactions: Vec<RecurlyInvoiceTransactionsStatus>, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct RecurlyInvoiceBillingAddress { pub street1: Option<Secret<String>>, pub street2: Option<Secret<String>>, pub region: Option<Secret<String>>, pub country: Option<enums::CountryAlpha2>, pub postal_code: Option<Secret<String>>, pub city: Option<String>, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct RecurlyLineItems { #[serde(rename = "type")] pub invoice_type: RecurlyInvoiceLineItemType, #[serde(with = "common_utils::custom_serde::iso8601")] pub start_date: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub end_date: PrimitiveDateTime, } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum RecurlyInvoiceLineItemType { Credit, Charge, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "snake_case")] pub struct RecurlyInvoiceTransactionsStatus { pub status: String, } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl TryFrom< ResponseRouterDataV2< recovery_router_flows::BillingConnectorInvoiceSync, RecurlyInvoiceSyncResponse, recovery_flow_common_types::BillingConnectorInvoiceSyncFlowData, recovery_request_types::BillingConnectorInvoiceSyncRequest, recovery_response_types::BillingConnectorInvoiceSyncResponse, >, > for recovery_router_data_types::BillingConnectorInvoiceSyncRouterDataV2 { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterDataV2< recovery_router_flows::BillingConnectorInvoiceSync, RecurlyInvoiceSyncResponse, recovery_flow_common_types::BillingConnectorInvoiceSyncFlowData, recovery_request_types::BillingConnectorInvoiceSyncRequest, recovery_response_types::BillingConnectorInvoiceSyncResponse, >, ) -> Result<Self, Self::Error> { #[allow(clippy::as_conversions)] // No of retries never exceeds u16 in recurly. So its better to suppress the clippy warning let retry_count = item.response.transactions.len() as u16; let merchant_reference_id = id_type::PaymentReferenceId::from_str(&item.response.id) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(Self { response: Ok( recovery_response_types::BillingConnectorInvoiceSyncResponse { amount: utils::convert_back_amount_to_minor_units( &FloatMajorUnitForConnector, item.response.total, item.response.currency, )?, currency: item.response.currency, merchant_reference_id, retry_count: Some(retry_count), billing_address: Some(api_models::payments::Address { address: Some(api_models::payments::AddressDetails { city: item .response .address .clone() .and_then(|address| address.city), state: item .response .address .clone() .and_then(|address| address.region), country: item .response .address .clone() .and_then(|address| address.country), line1: item .response .address .clone() .and_then(|address| address.street1), line2: item .response .address .clone() .and_then(|address| address.street2), line3: None, zip: item .response .address .clone() .and_then(|address| address.postal_code), first_name: None, last_name: None, origin_zip: None, }), phone: None, email: None, }), created_at: item.response.line_items.first().map(|line| line.start_date), ends_at: item.response.line_items.first().map(|line| line.end_date), }, ), ..item.data }) } }
crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs
hyperswitch_connectors::src::connectors::recurly::transformers
3,703
true
// File: crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs // Module: hyperswitch_connectors::src::connectors::prophetpay::transformers use std::collections::HashMap; use common_enums::enums; use common_utils::{ consts::{PROPHETPAY_REDIRECT_URL, PROPHETPAY_TOKEN}, errors::CustomResult, request::Method, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{CardRedirectData, PaymentMethodData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::Execute, router_request_types::{ CompleteAuthorizeData, CompleteAuthorizeRedirectResponse, PaymentsAuthorizeData, ResponseId, }, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types, }; use hyperswitch_interfaces::{api, consts::NO_ERROR_CODE, errors}; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{self, to_connector_meta}, }; pub struct ProphetpayRouterData<T> { pub amount: f64, pub router_data: T, } impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for ProphetpayRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?; Ok(Self { amount, router_data: item, }) } } pub struct ProphetpayAuthType { pub(super) user_name: Secret<String>, pub(super) password: Secret<String>, pub(super) profile_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for ProphetpayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { user_name: api_key.to_owned(), password: key1.to_owned(), profile_id: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "PascalCase")] pub struct ProphetpayTokenRequest { ref_info: String, profile: Secret<String>, entry_method: i8, token_type: i8, card_entry_context: i8, } #[derive(Debug, Clone)] pub enum ProphetpayEntryMethod { ManualEntry, CardSwipe, } impl ProphetpayEntryMethod { fn get_entry_method(&self) -> i8 { match self { Self::ManualEntry => 1, Self::CardSwipe => 2, } } } #[derive(Debug, Clone)] #[repr(i8)] pub enum ProphetpayTokenType { Normal, SaleTab, TemporarySave, } impl ProphetpayTokenType { fn get_token_type(&self) -> i8 { match self { Self::Normal => 0, Self::SaleTab => 1, Self::TemporarySave => 2, } } } #[derive(Debug, Clone)] #[repr(i8)] pub enum ProphetpayCardContext { NotApplicable, WebConsumerInitiated, } impl ProphetpayCardContext { fn get_card_context(&self) -> i8 { match self { Self::NotApplicable => 0, Self::WebConsumerInitiated => 5, } } } impl TryFrom<&ProphetpayRouterData<&types::PaymentsAuthorizeRouterData>> for ProphetpayTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &ProphetpayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { if item.router_data.request.currency == api_models::enums::Currency::USD { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::CardRedirect(CardRedirectData::CardRedirect {}) => { let auth_data = ProphetpayAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(Self { ref_info: item.router_data.connector_request_reference_id.to_owned(), profile: auth_data.profile_id, entry_method: ProphetpayEntryMethod::get_entry_method( &ProphetpayEntryMethod::ManualEntry, ), token_type: ProphetpayTokenType::get_token_type( &ProphetpayTokenType::SaleTab, ), card_entry_context: ProphetpayCardContext::get_card_context( &ProphetpayCardContext::WebConsumerInitiated, ), }) } _ => Err( errors::ConnectorError::NotImplemented("Payment methods".to_string()).into(), ), } } else { Err(errors::ConnectorError::CurrencyNotSupported { message: item.router_data.request.currency.to_string(), connector: "Prophetpay", } .into()) } } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayTokenResponse { hosted_tokenize_id: Secret<String>, } impl<F> TryFrom< ResponseRouterData<F, ProphetpayTokenResponse, PaymentsAuthorizeData, PaymentsResponseData>, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, ProphetpayTokenResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let url_data = format!( "{}{}", PROPHETPAY_REDIRECT_URL, item.response.hosted_tokenize_id.expose() ); let redirect_url = Url::parse(url_data.as_str()) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let redirection_data = get_redirect_url_form( redirect_url, item.data.request.complete_authorize_url.clone(), ) .ok(); Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } fn get_redirect_url_form( mut redirect_url: Url, complete_auth_url: Option<String>, ) -> CustomResult<RedirectForm, errors::ConnectorError> { let mut form_fields = HashMap::<String, String>::new(); form_fields.insert( String::from("redirectUrl"), complete_auth_url.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "complete_auth_url", })?, ); // Do not include query params in the endpoint redirect_url.set_query(None); Ok(RedirectForm::Form { endpoint: redirect_url.to_string(), method: Method::Get, form_fields, }) } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayCompleteRequest { amount: f64, ref_info: String, inquiry_reference: String, profile: Secret<String>, action_type: i8, card_token: Secret<String>, } impl TryFrom<&ProphetpayRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for ProphetpayCompleteRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &ProphetpayRouterData<&types::PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let auth_data = ProphetpayAuthType::try_from(&item.router_data.connector_auth_type)?; let card_token = Secret::new(get_card_token( item.router_data.request.redirect_response.clone(), )?); Ok(Self { amount: item.amount.to_owned(), ref_info: item.router_data.connector_request_reference_id.to_owned(), inquiry_reference: item.router_data.connector_request_reference_id.clone(), profile: auth_data.profile_id, action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Charge), card_token, }) } } fn get_card_token( response: Option<CompleteAuthorizeRedirectResponse>, ) -> CustomResult<String, errors::ConnectorError> { let res = response.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "redirect_response", })?; let queries_params = res .params .map(|param| { let mut queries = HashMap::<String, String>::new(); let values = param.peek().split('&').collect::<Vec<&str>>(); for value in values { let pair = value.split('=').collect::<Vec<&str>>(); queries.insert( pair.first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)? .to_string(), pair.get(1) .ok_or(errors::ConnectorError::ResponseDeserializationFailed)? .to_string(), ); } Ok::<_, errors::ConnectorError>(queries) }) .transpose()? .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; for (key, val) in queries_params { if key.as_str() == PROPHETPAY_TOKEN { return Ok(val); } } Err(errors::ConnectorError::MissingRequiredField { field_name: "card_token", } .into()) } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpaySyncRequest { transaction_id: String, ref_info: String, inquiry_reference: String, profile: Secret<String>, action_type: i8, } #[derive(Debug, Clone)] pub enum ProphetpayActionType { Charge, Refund, Inquiry, } impl ProphetpayActionType { fn get_action_type(&self) -> i8 { match self { Self::Charge => 1, Self::Refund => 3, Self::Inquiry => 7, } } } impl TryFrom<&types::PaymentsSyncRouterData> for ProphetpaySyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { let auth_data = ProphetpayAuthType::try_from(&item.connector_auth_type)?; let transaction_id = item .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; Ok(Self { transaction_id, ref_info: item.connector_request_reference_id.to_owned(), inquiry_reference: item.connector_request_reference_id.clone(), profile: auth_data.profile_id, action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Inquiry), }) } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayCompleteAuthResponse { pub success: bool, pub response_text: String, #[serde(rename = "transactionID")] pub transaction_id: String, pub response_code: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProphetpayCardTokenData { card_token: Secret<String>, } impl<F> TryFrom< ResponseRouterData< F, ProphetpayCompleteAuthResponse, CompleteAuthorizeData, PaymentsResponseData, >, > for RouterData<F, CompleteAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, ProphetpayCompleteAuthResponse, CompleteAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { if item.response.success { let card_token = get_card_token(item.data.request.redirect_response.clone())?; let card_token_data = ProphetpayCardTokenData { card_token: Secret::from(card_token), }; let connector_metadata = serde_json::to_value(card_token_data).ok(); Ok(Self { status: enums::AttemptStatus::Charged, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.transaction_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { Ok(Self { status: enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: item.response.response_code, message: item.response.response_text.clone(), reason: Some(item.response.response_text), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpaySyncResponse { success: bool, pub response_text: String, #[serde(rename = "transactionID")] pub transaction_id: String, } impl<F, T> TryFrom<ResponseRouterData<F, ProphetpaySyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, ProphetpaySyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { if item.response.success { Ok(Self { status: enums::AttemptStatus::Charged, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.transaction_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { Ok(Self { status: enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: NO_ERROR_CODE.to_string(), message: item.response.response_text.clone(), reason: Some(item.response.response_text), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayVoidResponse { pub success: bool, pub response_text: String, #[serde(rename = "transactionID")] pub transaction_id: String, } impl<F, T> TryFrom<ResponseRouterData<F, ProphetpayVoidResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, ProphetpayVoidResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { if item.response.success { Ok(Self { status: enums::AttemptStatus::Voided, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.transaction_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { Ok(Self { status: enums::AttemptStatus::VoidFailed, response: Err(ErrorResponse { code: NO_ERROR_CODE.to_string(), message: item.response.response_text.clone(), reason: Some(item.response.response_text), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayVoidRequest { pub transaction_id: String, pub profile: Secret<String>, pub ref_info: String, pub inquiry_reference: String, pub action_type: i8, } impl TryFrom<&types::PaymentsCancelRouterData> for ProphetpayVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth_data = ProphetpayAuthType::try_from(&item.connector_auth_type)?; let transaction_id = item.request.connector_transaction_id.to_owned(); Ok(Self { transaction_id, ref_info: item.connector_request_reference_id.to_owned(), inquiry_reference: item.connector_request_reference_id.clone(), profile: auth_data.profile_id, action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Inquiry), }) } } #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayRefundRequest { pub amount: f64, pub card_token: Secret<String>, pub transaction_id: String, pub profile: Secret<String>, pub ref_info: String, pub inquiry_reference: String, pub action_type: i8, } impl<F> TryFrom<&ProphetpayRouterData<&types::RefundsRouterData<F>>> for ProphetpayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &ProphetpayRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { if item.router_data.request.payment_amount == item.router_data.request.refund_amount { let auth_data = ProphetpayAuthType::try_from(&item.router_data.connector_auth_type)?; let transaction_id = item.router_data.request.connector_transaction_id.to_owned(); let card_token_data: ProphetpayCardTokenData = to_connector_meta(item.router_data.request.connector_metadata.clone())?; Ok(Self { transaction_id, amount: item.amount.to_owned(), card_token: card_token_data.card_token, profile: auth_data.profile_id, ref_info: item.router_data.request.refund_id.to_owned(), inquiry_reference: item.router_data.request.refund_id.clone(), action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Refund), }) } else { Err(errors::ConnectorError::NotImplemented("Partial Refund".to_string()).into()) } } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayRefundResponse { pub success: bool, pub response_text: String, pub tran_seq_number: Option<String>, } impl TryFrom<RefundsResponseRouterData<Execute, ProphetpayRefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, ProphetpayRefundResponse>, ) -> Result<Self, Self::Error> { if item.response.success { Ok(Self { response: Ok(RefundsResponseData { // no refund id is generated, tranSeqNumber is kept for future usage connector_refund_id: item.response.tran_seq_number.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "tran_seq_number", }, )?, refund_status: enums::RefundStatus::Success, }), ..item.data }) } else { Ok(Self { status: enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: NO_ERROR_CODE.to_string(), message: item.response.response_text.clone(), reason: Some(item.response.response_text), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayRefundSyncResponse { pub success: bool, pub response_text: String, } impl<T> TryFrom<RefundsResponseRouterData<T, ProphetpayRefundSyncResponse>> for types::RefundsRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<T, ProphetpayRefundSyncResponse>, ) -> Result<Self, Self::Error> { if item.response.success { Ok(Self { response: Ok(RefundsResponseData { // no refund id is generated, rather transaction id is used for referring to status in refund also connector_refund_id: item.data.request.connector_transaction_id.clone(), refund_status: enums::RefundStatus::Success, }), ..item.data }) } else { Ok(Self { status: enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: NO_ERROR_CODE.to_string(), message: item.response.response_text.clone(), reason: Some(item.response.response_text), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProphetpayRefundSyncRequest { transaction_id: String, inquiry_reference: String, ref_info: String, profile: Secret<String>, action_type: i8, } impl TryFrom<&types::RefundSyncRouterData> for ProphetpayRefundSyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> { let auth_data = ProphetpayAuthType::try_from(&item.connector_auth_type)?; Ok(Self { transaction_id: item.request.connector_transaction_id.clone(), ref_info: item.connector_request_reference_id.to_owned(), inquiry_reference: item.connector_request_reference_id.clone(), profile: auth_data.profile_id, action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Inquiry), }) } }
crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs
hyperswitch_connectors::src::connectors::prophetpay::transformers
5,097
true
// File: crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs // Module: hyperswitch_connectors::src::connectors::getnet::transformers use api_models::webhooks::IncomingWebhookEvent; use base64::Engine; use cards::CardNumber; use common_enums::{enums, AttemptStatus, CaptureMethod, CountryAlpha2}; use common_utils::{ consts::BASE64_ENGINE, errors::CustomResult, pii::{Email, IpAddress}, types::FloatMajorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, ResponseId, }, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ connectors::paybox::transformers::parse_url_encoded_to_struct, types::{PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ BrowserInformationData, PaymentsAuthorizeRequestData, PaymentsSyncRequestData, RouterData as _, }, }; pub struct GetnetRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for GetnetRouterData<T> { fn from((amount, item): (FloatMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Amount { pub value: FloatMajorUnit, pub currency: enums::Currency, } #[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Address { #[serde(rename = "street1")] pub street1: Option<Secret<String>>, pub city: Option<String>, pub state: Option<Secret<String>>, pub country: Option<CountryAlpha2>, } #[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct AccountHolder { #[serde(rename = "first-name")] pub first_name: Option<Secret<String>>, #[serde(rename = "last-name")] pub last_name: Option<Secret<String>>, pub email: Option<Email>, pub phone: Option<Secret<String>>, pub address: Option<Address>, } #[derive(Default, Debug, Serialize, PartialEq)] pub struct Card { #[serde(rename = "account-number")] pub account_number: CardNumber, #[serde(rename = "expiration-month")] pub expiration_month: Secret<String>, #[serde(rename = "expiration-year")] pub expiration_year: Secret<String>, #[serde(rename = "card-security-code")] pub card_security_code: Secret<String>, #[serde(rename = "card-type")] pub card_type: String, } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum GetnetPaymentMethods { CreditCard, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct PaymentMethod { pub name: GetnetPaymentMethods, } #[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Notification { pub url: Option<String>, } #[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct PaymentMethodContainer { #[serde(rename = "payment-method")] pub payment_method: Vec<PaymentMethod>, } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum NotificationFormat { #[serde(rename = "application/json-signed")] JsonSigned, #[serde(rename = "application/json")] Json, #[serde(rename = "application/xml")] Xml, #[serde(rename = "application/html")] Html, #[serde(rename = "application/x-www-form-urlencoded")] Urlencoded, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct NotificationContainer { pub notification: Vec<Notification>, pub format: NotificationFormat, } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] pub struct MerchantAccountId { pub value: Secret<String>, } #[derive(Debug, Serialize, PartialEq)] pub struct PaymentData { #[serde(rename = "merchant-account-id")] pub merchant_account_id: MerchantAccountId, #[serde(rename = "request-id")] pub request_id: String, #[serde(rename = "transaction-type")] pub transaction_type: GetnetTransactionType, #[serde(rename = "requested-amount")] pub requested_amount: Amount, #[serde(rename = "account-holder")] pub account_holder: Option<AccountHolder>, pub card: Card, #[serde(rename = "ip-address")] pub ip_address: Option<Secret<String, IpAddress>>, #[serde(rename = "payment-methods")] pub payment_methods: PaymentMethodContainer, pub notifications: Option<NotificationContainer>, } #[derive(Debug, Serialize)] pub struct GetnetPaymentsRequest { payment: PaymentData, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct GetnetCard { number: CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } impl TryFrom<enums::PaymentMethodType> for PaymentMethodContainer { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(payment_method_type: enums::PaymentMethodType) -> Result<Self, Self::Error> { match payment_method_type { enums::PaymentMethodType::Credit => Ok(Self { payment_method: vec![PaymentMethod { name: GetnetPaymentMethods::CreditCard, }], }), _ => Err(errors::ConnectorError::NotSupported { message: "Payment method type not supported".to_string(), connector: "Getnet", } .into()), } } } impl TryFrom<&GetnetRouterData<&PaymentsAuthorizeRouterData>> for GetnetPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &GetnetRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ref req_card) => { if item.router_data.is_three_ds() { return Err(errors::ConnectorError::NotSupported { message: "3DS payments".to_string(), connector: "Getnet", } .into()); } let request = &item.router_data.request; let auth_type = GetnetAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let merchant_account_id = MerchantAccountId { value: auth_type.merchant_id, }; let requested_amount = Amount { value: item.amount, currency: request.currency, }; let account_holder = AccountHolder { first_name: item.router_data.get_optional_billing_first_name(), last_name: item.router_data.get_optional_billing_last_name(), email: item.router_data.request.get_optional_email(), phone: item.router_data.get_optional_billing_phone_number(), address: Some(Address { street1: item.router_data.get_optional_billing_line2(), city: item.router_data.get_optional_billing_city(), state: item.router_data.get_optional_billing_state(), country: item.router_data.get_optional_billing_country(), }), }; let card = Card { account_number: req_card.card_number.clone(), expiration_month: req_card.card_exp_month.clone(), expiration_year: req_card.card_exp_year.clone(), card_security_code: req_card.card_cvc.clone(), card_type: req_card .card_network .as_ref() .map(|network| network.to_string().to_lowercase()) .unwrap_or_default(), }; let pmt = item.router_data.request.get_payment_method_type()?; let payment_method = PaymentMethodContainer::try_from(pmt)?; let notifications: NotificationContainer = NotificationContainer { format: NotificationFormat::JsonSigned, notification: vec![Notification { url: Some(item.router_data.request.get_webhook_url()?), }], }; let transaction_type = if request.is_auto_capture()? { GetnetTransactionType::Purchase } else { GetnetTransactionType::Authorization }; let payment_data = PaymentData { merchant_account_id, request_id: item.router_data.payment_id.clone(), transaction_type, requested_amount, account_holder: Some(account_holder), card, ip_address: Some(request.get_browser_info()?.get_ip_address()?), payment_methods: payment_method, notifications: Some(notifications), }; Ok(Self { payment: payment_data, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } pub struct GetnetAuthType { pub username: Secret<String>, pub password: Secret<String>, pub merchant_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for GetnetAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { username: key1.to_owned(), password: api_key.to_owned(), merchant_id: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum GetnetPaymentStatus { Success, Failed, #[default] InProgress, } impl From<GetnetPaymentStatus> for AttemptStatus { fn from(item: GetnetPaymentStatus) -> Self { match item { GetnetPaymentStatus::Success => Self::Charged, GetnetPaymentStatus::Failed => Self::Failure, GetnetPaymentStatus::InProgress => Self::Pending, } } } #[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Status { pub code: String, pub description: String, pub severity: String, } #[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Statuses { pub status: Vec<Status>, } #[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct CardToken { #[serde(rename = "token-id")] pub token_id: Secret<String>, #[serde(rename = "masked-account-number")] pub masked_account_number: Secret<String>, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct PaymentResponseData { pub statuses: Statuses, pub descriptor: Option<String>, pub notifications: NotificationContainer, #[serde(rename = "merchant-account-id")] pub merchant_account_id: MerchantAccountId, #[serde(rename = "transaction-id")] pub transaction_id: String, #[serde(rename = "request-id")] pub request_id: String, #[serde(rename = "transaction-type")] pub transaction_type: GetnetTransactionType, #[serde(rename = "transaction-state")] pub transaction_state: GetnetPaymentStatus, #[serde(rename = "completion-time-stamp")] pub completion_time_stamp: Option<i64>, #[serde(rename = "requested-amount")] pub requested_amount: Amount, #[serde(rename = "account-holder")] pub account_holder: Option<AccountHolder>, #[serde(rename = "card-token")] pub card_token: CardToken, #[serde(rename = "ip-address")] pub ip_address: Option<Secret<String, IpAddress>>, #[serde(rename = "payment-methods")] pub payment_methods: PaymentMethodContainer, #[serde(rename = "api-id")] pub api_id: String, #[serde(rename = "self")] pub self_url: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentsResponse { payment: PaymentResponseData, } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum GetnetPaymentsResponse { PaymentsResponse(Box<PaymentsResponse>), GetnetWebhookNotificationResponse(Box<GetnetWebhookNotificationResponseBody>), } pub fn authorization_attempt_status_from_transaction_state( getnet_status: GetnetPaymentStatus, is_auto_capture: bool, ) -> AttemptStatus { match getnet_status { GetnetPaymentStatus::Success => { if is_auto_capture { AttemptStatus::Charged } else { AttemptStatus::Authorized } } GetnetPaymentStatus::InProgress => AttemptStatus::Pending, GetnetPaymentStatus::Failed => AttemptStatus::Failure, } } impl<F> TryFrom< ResponseRouterData<F, GetnetPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData>, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, GetnetPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response { GetnetPaymentsResponse::PaymentsResponse(ref payment_response) => Ok(Self { status: authorization_attempt_status_from_transaction_state( payment_response.payment.transaction_state.clone(), item.data.request.is_auto_capture()?, ), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( payment_response.payment.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), _ => Err(error_stack::Report::new( errors::ConnectorError::ResponseHandlingFailed, )), } } } pub fn psync_attempt_status_from_transaction_state( getnet_status: GetnetPaymentStatus, is_auto_capture: bool, transaction_type: GetnetTransactionType, ) -> AttemptStatus { match getnet_status { GetnetPaymentStatus::Success => { if is_auto_capture && transaction_type == GetnetTransactionType::CaptureAuthorization { AttemptStatus::Charged } else { AttemptStatus::Authorized } } GetnetPaymentStatus::InProgress => AttemptStatus::Pending, GetnetPaymentStatus::Failed => AttemptStatus::Failure, } } impl TryFrom<PaymentsSyncResponseRouterData<GetnetPaymentsResponse>> for PaymentsSyncRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsSyncResponseRouterData<GetnetPaymentsResponse>, ) -> Result<Self, Self::Error> { match item.response { GetnetPaymentsResponse::PaymentsResponse(ref payment_response) => Ok(Self { status: authorization_attempt_status_from_transaction_state( payment_response.payment.transaction_state.clone(), item.data.request.is_auto_capture()?, ), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( payment_response.payment.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), GetnetPaymentsResponse::GetnetWebhookNotificationResponse(ref webhook_response) => { Ok(Self { status: psync_attempt_status_from_transaction_state( webhook_response.payment.transaction_state.clone(), item.data.request.is_auto_capture()?, webhook_response.payment.transaction_type.clone(), ), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( webhook_response.payment.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } } } #[derive(Debug, Serialize, PartialEq)] pub struct CapturePaymentData { #[serde(rename = "merchant-account-id")] pub merchant_account_id: MerchantAccountId, #[serde(rename = "request-id")] pub request_id: String, #[serde(rename = "transaction-type")] pub transaction_type: GetnetTransactionType, #[serde(rename = "parent-transaction-id")] pub parent_transaction_id: String, #[serde(rename = "requested-amount")] pub requested_amount: Amount, pub notifications: NotificationContainer, #[serde(rename = "ip-address")] pub ip_address: Option<Secret<String, IpAddress>>, } #[derive(Debug, Serialize)] pub struct GetnetCaptureRequest { pub payment: CapturePaymentData, } impl TryFrom<&GetnetRouterData<&PaymentsCaptureRouterData>> for GetnetCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &GetnetRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { let request = &item.router_data.request; let auth_type = GetnetAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let merchant_account_id = MerchantAccountId { value: auth_type.merchant_id, }; let requested_amount = Amount { value: item.amount, currency: request.currency, }; let req = &item.router_data.request; let webhook_url = &req.webhook_url; let notifications = NotificationContainer { format: NotificationFormat::JsonSigned, notification: vec![Notification { url: webhook_url.clone(), }], }; let transaction_type = GetnetTransactionType::CaptureAuthorization; let ip_address = req .browser_info .as_ref() .and_then(|info| info.ip_address.as_ref()) .map(|ip| Secret::new(ip.to_string())); let request_id = item.router_data.connector_request_reference_id.clone(); let parent_transaction_id = item.router_data.request.connector_transaction_id.clone(); let capture_payment_data = CapturePaymentData { merchant_account_id, request_id, transaction_type, parent_transaction_id, requested_amount, notifications, ip_address, }; Ok(Self { payment: capture_payment_data, }) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CaptureResponseData { pub statuses: Statuses, pub descriptor: String, pub notifications: NotificationContainer, #[serde(rename = "merchant-account-id")] pub merchant_account_id: MerchantAccountId, #[serde(rename = "transaction-id")] pub transaction_id: String, #[serde(rename = "request-id")] pub request_id: String, #[serde(rename = "transaction-type")] pub transaction_type: GetnetTransactionType, #[serde(rename = "transaction-state")] pub transaction_state: GetnetPaymentStatus, #[serde(rename = "completion-time-stamp")] pub completion_time_stamp: Option<i64>, #[serde(rename = "requested-amount")] pub requested_amount: Amount, #[serde(rename = "parent-transaction-id")] pub parent_transaction_id: String, #[serde(rename = "account-holder")] pub account_holder: Option<AccountHolder>, #[serde(rename = "card-token")] pub card_token: CardToken, #[serde(rename = "ip-address")] pub ip_address: Option<Secret<String, IpAddress>>, #[serde(rename = "payment-methods")] pub payment_methods: PaymentMethodContainer, #[serde(rename = "parent-transaction-amount")] pub parent_transaction_amount: Amount, #[serde(rename = "authorization-code")] pub authorization_code: String, #[serde(rename = "api-id")] pub api_id: String, #[serde(rename = "self")] pub self_url: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct GetnetCaptureResponse { payment: CaptureResponseData, } pub fn capture_status_from_transaction_state(getnet_status: GetnetPaymentStatus) -> AttemptStatus { match getnet_status { GetnetPaymentStatus::Success => AttemptStatus::Charged, GetnetPaymentStatus::InProgress => AttemptStatus::Pending, GetnetPaymentStatus::Failed => AttemptStatus::Authorized, } } impl<F> TryFrom<ResponseRouterData<F, GetnetCaptureResponse, PaymentsCaptureData, PaymentsResponseData>> for RouterData<F, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, GetnetCaptureResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { status: capture_status_from_transaction_state(item.response.payment.transaction_state), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.payment.transaction_id, ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Serialize, PartialEq)] pub struct RefundPaymentData { #[serde(rename = "merchant-account-id")] pub merchant_account_id: MerchantAccountId, #[serde(rename = "request-id")] pub request_id: String, #[serde(rename = "transaction-type")] pub transaction_type: GetnetTransactionType, #[serde(rename = "parent-transaction-id")] pub parent_transaction_id: String, pub notifications: NotificationContainer, #[serde(rename = "ip-address")] pub ip_address: Option<Secret<String, IpAddress>>, } #[derive(Debug, Serialize)] pub struct GetnetRefundRequest { pub payment: RefundPaymentData, } impl<F> TryFrom<&GetnetRouterData<&RefundsRouterData<F>>> for GetnetRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &GetnetRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let request = &item.router_data.request; let auth_type = GetnetAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let url = request.webhook_url.clone(); let merchant_account_id = MerchantAccountId { value: auth_type.merchant_id, }; let notifications = NotificationContainer { format: NotificationFormat::JsonSigned, notification: vec![Notification { url }], }; let capture_method = request.capture_method; let transaction_type = match capture_method { Some(CaptureMethod::Automatic) => GetnetTransactionType::RefundPurchase, Some(CaptureMethod::Manual) => GetnetTransactionType::RefundCapture, Some(CaptureMethod::ManualMultiple) | Some(CaptureMethod::Scheduled) | Some(CaptureMethod::SequentialAutomatic) | None => { return Err(errors::ConnectorError::CaptureMethodNotSupported {}.into()); } }; let ip_address = request .browser_info .as_ref() .and_then(|browser_info| browser_info.ip_address.as_ref()) .map(|ip| Secret::new(ip.to_string())); let request_id = item .router_data .refund_id .clone() .ok_or(errors::ConnectorError::MissingConnectorRefundID)?; let parent_transaction_id = item.router_data.request.connector_transaction_id.clone(); let refund_payment_data = RefundPaymentData { merchant_account_id, request_id, transaction_type, parent_transaction_id, notifications, ip_address, }; Ok(Self { payment: refund_payment_data, }) } } #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)] #[serde(rename_all = "lowercase")] pub enum RefundStatus { Success, Failed, #[default] InProgress, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Success => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::InProgress => Self::Pending, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct RefundResponseData { pub statuses: Statuses, pub descriptor: String, pub notifications: NotificationContainer, #[serde(rename = "merchant-account-id")] pub merchant_account_id: MerchantAccountId, #[serde(rename = "transaction-id")] pub transaction_id: String, #[serde(rename = "request-id")] pub request_id: String, #[serde(rename = "transaction-type")] pub transaction_type: GetnetTransactionType, #[serde(rename = "transaction-state")] pub transaction_state: RefundStatus, #[serde(rename = "completion-time-stamp")] pub completion_time_stamp: Option<i64>, #[serde(rename = "requested-amount")] pub requested_amount: Amount, #[serde(rename = "parent-transaction-id")] #[serde(skip_serializing_if = "Option::is_none")] pub parent_transaction_id: Option<String>, #[serde(rename = "account-holder")] pub account_holder: Option<AccountHolder>, #[serde(rename = "card-token")] pub card_token: CardToken, #[serde(rename = "ip-address")] pub ip_address: Option<Secret<String, IpAddress>>, #[serde(rename = "payment-methods")] pub payment_methods: PaymentMethodContainer, #[serde(rename = "parent-transaction-amount")] #[serde(skip_serializing_if = "Option::is_none")] pub parent_transaction_amount: Option<Amount>, #[serde(rename = "api-id")] pub api_id: String, #[serde(rename = "self")] pub self_url: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { payment: RefundResponseData, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.payment.transaction_id, refund_status: enums::RefundStatus::from(item.response.payment.transaction_state), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.payment.transaction_id, refund_status: enums::RefundStatus::from(item.response.payment.transaction_state), }), ..item.data }) } } #[derive(Debug, Serialize, PartialEq)] pub struct CancelPaymentData { #[serde(rename = "merchant-account-id")] pub merchant_account_id: MerchantAccountId, #[serde(rename = "request-id")] pub request_id: String, #[serde(rename = "transaction-type")] pub transaction_type: GetnetTransactionType, #[serde(rename = "parent-transaction-id")] pub parent_transaction_id: String, pub notifications: NotificationContainer, #[serde(rename = "ip-address")] pub ip_address: Option<Secret<String, IpAddress>>, } #[derive(Debug, Serialize)] pub struct GetnetCancelRequest { pub payment: CancelPaymentData, } impl TryFrom<&PaymentsCancelRouterData> for GetnetCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let request = &item.request; let auth_type = GetnetAuthType::try_from(&item.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let merchant_account_id = MerchantAccountId { value: auth_type.merchant_id, }; let webhook_url = &item.request.webhook_url; let notifications = NotificationContainer { format: NotificationFormat::JsonSigned, notification: vec![Notification { url: webhook_url.clone(), }], }; let capture_method = &item.request.capture_method; let transaction_type = match capture_method { Some(CaptureMethod::Automatic) => GetnetTransactionType::VoidPurchase, Some(CaptureMethod::Manual) => GetnetTransactionType::VoidAuthorization, Some(CaptureMethod::ManualMultiple) | Some(CaptureMethod::Scheduled) | Some(CaptureMethod::SequentialAutomatic) => { return Err(errors::ConnectorError::CaptureMethodNotSupported {}.into()); } None => { return Err(errors::ConnectorError::CaptureMethodNotSupported {}.into()); } }; let ip_address = request .browser_info .as_ref() .and_then(|browser_info| browser_info.ip_address.as_ref()) .map(|ip| Secret::new(ip.to_string())); let request_id = &item.connector_request_reference_id.clone(); let parent_transaction_id = item.request.connector_transaction_id.clone(); let cancel_payment_data = CancelPaymentData { merchant_account_id, request_id: request_id.to_string(), transaction_type, parent_transaction_id, notifications, ip_address, }; Ok(Self { payment: cancel_payment_data, }) } } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum GetnetTransactionType { Purchase, #[serde(rename = "capture-authorization")] CaptureAuthorization, #[serde(rename = "refund-purchase")] RefundPurchase, #[serde(rename = "refund-capture")] RefundCapture, #[serde(rename = "void-authorization")] VoidAuthorization, #[serde(rename = "void-purchase")] VoidPurchase, Authorization, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub struct CancelResponseData { pub statuses: Statuses, pub descriptor: String, pub notifications: NotificationContainer, #[serde(rename = "merchant-account-id")] pub merchant_account_id: MerchantAccountId, #[serde(rename = "transaction-id")] pub transaction_id: String, #[serde(rename = "request-id")] pub request_id: String, #[serde(rename = "transaction-type")] pub transaction_type: GetnetTransactionType, #[serde(rename = "transaction-state")] pub transaction_state: GetnetPaymentStatus, #[serde(rename = "completion-time-stamp")] pub completion_time_stamp: Option<i64>, #[serde(rename = "requested-amount")] pub requested_amount: Amount, #[serde(rename = "parent-transaction-id")] pub parent_transaction_id: String, #[serde(rename = "account-holder")] pub account_holder: Option<AccountHolder>, #[serde(rename = "card-token")] pub card_token: CardToken, #[serde(rename = "ip-address")] pub ip_address: Option<Secret<String, IpAddress>>, #[serde(rename = "payment-methods")] pub payment_methods: PaymentMethodContainer, #[serde(rename = "parent-transaction-amount")] pub parent_transaction_amount: Amount, #[serde(rename = "api-id")] pub api_id: String, #[serde(rename = "self")] pub self_url: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct GetnetCancelResponse { payment: CancelResponseData, } pub fn cancel_status_from_transaction_state(getnet_status: GetnetPaymentStatus) -> AttemptStatus { match getnet_status { GetnetPaymentStatus::Success => AttemptStatus::Voided, GetnetPaymentStatus::InProgress => AttemptStatus::Pending, GetnetPaymentStatus::Failed => AttemptStatus::VoidFailed, } } impl<F> TryFrom<ResponseRouterData<F, GetnetCancelResponse, PaymentsCancelData, PaymentsResponseData>> for RouterData<F, PaymentsCancelData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, GetnetCancelResponse, PaymentsCancelData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: cancel_status_from_transaction_state(item.response.payment.transaction_state), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.payment.transaction_id, ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct GetnetErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, } #[derive(Serialize, Deserialize, Debug)] pub struct GetnetWebhookNotificationResponse { #[serde(rename = "response-signature-base64")] pub response_signature_base64: Secret<String>, #[serde(rename = "response-signature-algorithm")] pub response_signature_algorithm: Secret<String>, #[serde(rename = "response-base64")] pub response_base64: Secret<String>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct WebhookResponseData { pub statuses: Statuses, pub descriptor: String, pub notifications: NotificationContainer, #[serde(rename = "merchant-account-id")] pub merchant_account_id: MerchantAccountId, #[serde(rename = "transaction-id")] pub transaction_id: String, #[serde(rename = "request-id")] pub request_id: String, #[serde(rename = "transaction-type")] pub transaction_type: GetnetTransactionType, #[serde(rename = "transaction-state")] pub transaction_state: GetnetPaymentStatus, #[serde(rename = "completion-time-stamp")] pub completion_time_stamp: u64, #[serde(rename = "requested-amount")] pub requested_amount: Amount, #[serde(rename = "parent-transaction-id")] #[serde(skip_serializing_if = "Option::is_none")] pub parent_transaction_id: Option<String>, #[serde(rename = "account-holder")] pub account_holder: Option<AccountHolder>, #[serde(rename = "card-token")] pub card_token: CardToken, #[serde(rename = "ip-address")] pub ip_address: Option<Secret<String, IpAddress>>, #[serde(rename = "payment-methods")] pub payment_methods: PaymentMethodContainer, #[serde(rename = "parent-transaction-amount")] #[serde(skip_serializing_if = "Option::is_none")] pub parent_transaction_amount: Option<Amount>, #[serde(rename = "authorization-code")] #[serde(skip_serializing_if = "Option::is_none")] pub authorization_code: Option<String>, #[serde(rename = "api-id")] pub api_id: String, #[serde(rename = "provider-account-id")] #[serde(skip_serializing_if = "Option::is_none")] pub provider_account_id: Option<String>, } #[derive(Serialize, Deserialize, Debug)] pub struct GetnetWebhookNotificationResponseBody { pub payment: WebhookResponseData, } pub fn is_refund_event(transaction_type: &GetnetTransactionType) -> bool { matches!( transaction_type, GetnetTransactionType::RefundPurchase | GetnetTransactionType::RefundCapture ) } pub fn get_webhook_object_from_body( body: &[u8], ) -> CustomResult<GetnetWebhookNotificationResponseBody, errors::ConnectorError> { let body_bytes = bytes::Bytes::copy_from_slice(body); let parsed_param: GetnetWebhookNotificationResponse = parse_url_encoded_to_struct(body_bytes) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let response_base64 = &parsed_param.response_base64.peek(); let decoded_response = BASE64_ENGINE .decode(response_base64) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let getnet_webhook_notification_response: GetnetWebhookNotificationResponseBody = match serde_json::from_slice::<GetnetWebhookNotificationResponseBody>(&decoded_response) { Ok(response) => response, Err(_e) => { return Err(errors::ConnectorError::WebhookBodyDecodingFailed)?; } }; Ok(getnet_webhook_notification_response) } pub fn get_webhook_response( body: &[u8], ) -> CustomResult<GetnetWebhookNotificationResponse, errors::ConnectorError> { let body_bytes = bytes::Bytes::copy_from_slice(body); let parsed_param: GetnetWebhookNotificationResponse = parse_url_encoded_to_struct(body_bytes) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(parsed_param) } pub fn get_incoming_webhook_event( transaction_type: GetnetTransactionType, transaction_status: GetnetPaymentStatus, ) -> IncomingWebhookEvent { match transaction_type { GetnetTransactionType::Purchase => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentSuccess, GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentProcessing, }, GetnetTransactionType::Authorization => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentAuthorizationSuccess, GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentAuthorizationFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentProcessing, }, GetnetTransactionType::CaptureAuthorization => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentCaptureSuccess, GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentCaptureFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentCaptureFailure, }, GetnetTransactionType::RefundPurchase => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::RefundSuccess, GetnetPaymentStatus::Failed => IncomingWebhookEvent::RefundFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::RefundFailure, }, GetnetTransactionType::RefundCapture => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::RefundSuccess, GetnetPaymentStatus::Failed => IncomingWebhookEvent::RefundFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::RefundFailure, }, GetnetTransactionType::VoidAuthorization => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentCancelled, GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentCancelFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentCancelFailure, }, GetnetTransactionType::VoidPurchase => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentCancelled, GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentCancelFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentCancelFailure, }, } }
crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
hyperswitch_connectors::src::connectors::getnet::transformers
8,713
true
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs // Module: hyperswitch_connectors::src::connectors::paypal::transformers #[cfg(feature = "payouts")] use api_models::payouts::{PayoutMethodData, Wallet as WalletPayout}; use api_models::{enums, webhooks::IncomingWebhookEvent}; use base64::Engine; use common_enums::enums as storage_enums; #[cfg(feature = "payouts")] use common_utils::pii::Email; use common_utils::{consts, errors::CustomResult, request::Method, types::StringMajorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{ BankDebitData, BankRedirectData, BankTransferData, CardRedirectData, GiftCardData, PayLaterData, PaymentMethodData, VoucherData, WalletData, }, router_data::{ AccessToken, ConnectorAuthType, ConnectorResponseData, ErrorResponse, ExtendedAuthorizationResponseData, RouterData, }, router_flow_types::{ payments::{Authorize, PostSessionTokens}, refunds::{Execute, RSync}, VerifyWebhookSource, }, router_request_types::{ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostSessionTokensData, PaymentsSyncData, ResponseId, VerifyWebhookSourceRequestData, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, VerifyWebhookSourceResponseData, VerifyWebhookStatus, }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsExtendAuthorizationRouterData, PaymentsIncrementalAuthorizationRouterData, PaymentsPostSessionTokensRouterData, RefreshTokenRouterData, RefundsRouterData, SdkSessionUpdateRouterData, SetupMandateRouterData, VerifyWebhookSourceRouterData, }, }; #[cfg(feature = "payouts")] use hyperswitch_domain_models::{ router_flow_types::PoFulfill, router_response_types::PayoutsResponseData, types::PayoutsRouterData, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use url::Url; use utils::ForeignTryFrom; #[cfg(feature = "payouts")] use crate::{constants, types::PayoutsResponseRouterData}; use crate::{ types::{PaymentsCaptureResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ self, is_payment_failure, missing_field_err, to_connector_meta, AccessTokenRequestInfo, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, PaymentsPostSessionTokensRequestData, RouterData as OtherRouterData, }, }; trait GetRequestIncrementalAuthorization { fn get_request_incremental_authorization(&self) -> Option<bool>; } impl GetRequestIncrementalAuthorization for PaymentsAuthorizeData { fn get_request_incremental_authorization(&self) -> Option<bool> { Some(self.request_incremental_authorization) } } impl GetRequestIncrementalAuthorization for CompleteAuthorizeData { fn get_request_incremental_authorization(&self) -> Option<bool> { None } } impl GetRequestIncrementalAuthorization for PaymentsSyncData { fn get_request_incremental_authorization(&self) -> Option<bool> { None } } #[derive(Debug, Serialize)] pub struct PaypalRouterData<T> { pub amount: StringMajorUnit, pub shipping_cost: Option<StringMajorUnit>, pub order_tax_amount: Option<StringMajorUnit>, pub order_amount: Option<StringMajorUnit>, pub router_data: T, } impl<T> TryFrom<( StringMajorUnit, Option<StringMajorUnit>, Option<StringMajorUnit>, Option<StringMajorUnit>, T, )> for PaypalRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (amount, shipping_cost, order_tax_amount, order_amount, item): ( StringMajorUnit, Option<StringMajorUnit>, Option<StringMajorUnit>, Option<StringMajorUnit>, T, ), ) -> Result<Self, Self::Error> { Ok(Self { amount, shipping_cost, order_tax_amount, order_amount, router_data: item, }) } } mod webhook_headers { pub const PAYPAL_TRANSMISSION_ID: &str = "paypal-transmission-id"; pub const PAYPAL_TRANSMISSION_TIME: &str = "paypal-transmission-time"; pub const PAYPAL_TRANSMISSION_SIG: &str = "paypal-transmission-sig"; pub const PAYPAL_CERT_URL: &str = "paypal-cert-url"; pub const PAYPAL_AUTH_ALGO: &str = "paypal-auth-algo"; } pub mod auth_headers { pub const PAYPAL_PARTNER_ATTRIBUTION_ID: &str = "PayPal-Partner-Attribution-Id"; pub const PREFER: &str = "Prefer"; pub const PAYPAL_REQUEST_ID: &str = "PayPal-Request-Id"; pub const PAYPAL_AUTH_ASSERTION: &str = "PayPal-Auth-Assertion"; } const ORDER_QUANTITY: u16 = 1; #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum PaypalPaymentIntent { Capture, Authorize, Authenticate, } #[derive(Default, Debug, Clone, Serialize, Eq, PartialEq, Deserialize)] pub struct OrderAmount { pub currency_code: storage_enums::Currency, pub value: StringMajorUnit, } #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)] pub struct OrderRequestAmount { pub currency_code: storage_enums::Currency, pub value: StringMajorUnit, pub breakdown: AmountBreakdown, } impl From<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for OrderRequestAmount { fn from(item: &PaypalRouterData<&PaymentsAuthorizeRouterData>) -> Self { Self { currency_code: item.router_data.request.currency, value: item.amount.clone(), breakdown: AmountBreakdown { item_total: OrderAmount { currency_code: item.router_data.request.currency, value: item.amount.clone(), }, tax_total: None, shipping: Some(OrderAmount { currency_code: item.router_data.request.currency, value: item .shipping_cost .clone() .unwrap_or(StringMajorUnit::zero()), }), }, } } } impl TryFrom<&PaypalRouterData<&PaymentsPostSessionTokensRouterData>> for OrderRequestAmount { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaypalRouterData<&PaymentsPostSessionTokensRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { currency_code: item.router_data.request.currency, value: item.amount.clone(), breakdown: AmountBreakdown { item_total: OrderAmount { currency_code: item.router_data.request.currency, value: item.order_amount.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "order_amount", }, )?, }, tax_total: None, shipping: Some(OrderAmount { currency_code: item.router_data.request.currency, value: item .shipping_cost .clone() .unwrap_or(StringMajorUnit::zero()), }), }, }) } } impl TryFrom<&PaypalRouterData<&SdkSessionUpdateRouterData>> for OrderRequestAmount { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaypalRouterData<&SdkSessionUpdateRouterData>) -> Result<Self, Self::Error> { Ok(Self { currency_code: item.router_data.request.currency, value: item.amount.clone(), breakdown: AmountBreakdown { item_total: OrderAmount { currency_code: item.router_data.request.currency, value: item.order_amount.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "order_amount", }, )?, }, tax_total: Some(OrderAmount { currency_code: item.router_data.request.currency, value: item.order_tax_amount.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "order_tax_amount", }, )?, }), shipping: Some(OrderAmount { currency_code: item.router_data.request.currency, value: item .shipping_cost .clone() .unwrap_or(StringMajorUnit::zero()), }), }, }) } } #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)] pub struct AmountBreakdown { item_total: OrderAmount, tax_total: Option<OrderAmount>, shipping: Option<OrderAmount>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct PurchaseUnitRequest { reference_id: Option<String>, //reference for an item in purchase_units invoice_id: Option<String>, //The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. custom_id: Option<String>, //Used to reconcile client transactions with PayPal transactions. amount: OrderRequestAmount, #[serde(skip_serializing_if = "Option::is_none")] payee: Option<Payee>, shipping: Option<ShippingAddress>, items: Vec<ItemDetails>, } #[derive(Default, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct Payee { merchant_id: Secret<String>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct ItemDetails { name: String, quantity: u16, unit_amount: OrderAmount, tax: Option<OrderAmount>, } impl From<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for ItemDetails { fn from(item: &PaypalRouterData<&PaymentsAuthorizeRouterData>) -> Self { Self { name: format!( "Payment for invoice {}", item.router_data.connector_request_reference_id ), quantity: ORDER_QUANTITY, unit_amount: OrderAmount { currency_code: item.router_data.request.currency, value: item.amount.clone(), }, tax: None, } } } impl TryFrom<&PaypalRouterData<&PaymentsPostSessionTokensRouterData>> for ItemDetails { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaypalRouterData<&PaymentsPostSessionTokensRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { name: format!( "Payment for invoice {}", item.router_data.connector_request_reference_id ), quantity: ORDER_QUANTITY, unit_amount: OrderAmount { currency_code: item.router_data.request.currency, value: item.order_amount.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "order_amount", }, )?, }, tax: None, }) } } impl TryFrom<&PaypalRouterData<&SdkSessionUpdateRouterData>> for ItemDetails { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaypalRouterData<&SdkSessionUpdateRouterData>) -> Result<Self, Self::Error> { Ok(Self { name: format!( "Payment for invoice {}", item.router_data.connector_request_reference_id ), quantity: ORDER_QUANTITY, unit_amount: OrderAmount { currency_code: item.router_data.request.currency, value: item.order_amount.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "order_amount", }, )?, }, tax: Some(OrderAmount { currency_code: item.router_data.request.currency, value: item.order_tax_amount.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "order_tax_amount", }, )?, }), }) } } #[derive(Default, Debug, Serialize, Eq, PartialEq, Deserialize)] pub struct Address { address_line_1: Option<Secret<String>>, postal_code: Option<Secret<String>>, country_code: enums::CountryAlpha2, admin_area_2: Option<String>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct ShippingAddress { address: Option<Address>, name: Option<ShippingName>, } impl From<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for ShippingAddress { fn from(item: &PaypalRouterData<&PaymentsAuthorizeRouterData>) -> Self { Self { address: get_address_info(item.router_data.get_optional_shipping()), name: Some(ShippingName { full_name: item .router_data .get_optional_shipping() .and_then(|inner_data| inner_data.address.as_ref()) .and_then(|inner_data| inner_data.first_name.clone()), }), } } } impl From<&PaypalRouterData<&PaymentsPostSessionTokensRouterData>> for ShippingAddress { fn from(item: &PaypalRouterData<&PaymentsPostSessionTokensRouterData>) -> Self { Self { address: get_address_info(item.router_data.get_optional_shipping()), name: Some(ShippingName { full_name: item .router_data .get_optional_shipping() .and_then(|inner_data| inner_data.address.as_ref()) .and_then(|inner_data| inner_data.first_name.clone()), }), } } } #[derive(Debug, Serialize, PartialEq, Eq)] pub struct PaypalUpdateOrderRequest(Vec<Operation>); impl PaypalUpdateOrderRequest { pub fn get_inner_value(self) -> Vec<Operation> { self.0 } } #[derive(Debug, Serialize, PartialEq, Eq)] pub struct Operation { pub op: PaypalOperationType, pub path: String, pub value: Value, } #[derive(Debug, Serialize, PartialEq, Eq, Clone)] #[serde(rename_all = "lowercase")] pub enum PaypalOperationType { Add, Remove, Replace, Move, Copy, Test, } #[derive(Debug, Serialize, PartialEq, Eq)] #[serde(untagged)] pub enum Value { Amount(OrderRequestAmount), Items(Vec<ItemDetails>), } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct ShippingName { full_name: Option<Secret<String>>, } #[derive(Debug, Serialize)] pub struct CardRequestStruct { billing_address: Option<Address>, expiry: Option<Secret<String>>, name: Option<Secret<String>>, number: Option<cards::CardNumber>, security_code: Option<Secret<String>>, attributes: Option<CardRequestAttributes>, } #[derive(Debug, Serialize, Deserialize)] pub struct VaultStruct { vault_id: Secret<String>, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum CardRequest { CardRequestStruct(CardRequestStruct), CardVaultStruct(VaultStruct), } #[derive(Debug, Serialize)] pub struct CardRequestAttributes { vault: Option<PaypalVault>, verification: Option<ThreeDsMethod>, } #[derive(Debug, Serialize)] pub struct ThreeDsMethod { method: ThreeDsType, } #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum ThreeDsType { ScaAlways, } #[derive(Debug, Serialize)] pub struct RedirectRequest { name: Secret<String>, country_code: enums::CountryAlpha2, experience_context: ContextStruct, } #[derive(Debug, Serialize, Deserialize)] pub struct ContextStruct { return_url: Option<String>, cancel_url: Option<String>, user_action: Option<UserAction>, shipping_preference: ShippingPreference, } #[derive(Debug, Serialize, Deserialize)] pub enum UserAction { #[serde(rename = "PAY_NOW")] PayNow, } #[derive(Debug, Serialize, Deserialize)] pub enum ShippingPreference { #[serde(rename = "SET_PROVIDED_ADDRESS")] SetProvidedAddress, #[serde(rename = "GET_FROM_FILE")] GetFromFile, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaypalRedirectionRequest { PaypalRedirectionStruct(PaypalRedirectionStruct), PaypalVaultStruct(VaultStruct), } #[derive(Debug, Serialize)] pub struct PaypalRedirectionStruct { experience_context: ContextStruct, attributes: Option<Attributes>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Attributes { vault: PaypalVault, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct PaypalRedirectionResponse { attributes: Option<AttributeResponse>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct EpsRedirectionResponse { name: Option<Secret<String>>, country_code: Option<enums::CountryAlpha2>, bic: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct IdealRedirectionResponse { name: Option<Secret<String>>, country_code: Option<enums::CountryAlpha2>, bic: Option<Secret<String>>, iban_last_chars: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct AttributeResponse { vault: PaypalVaultResponse, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct PaypalVault { store_in_vault: StoreInVault, usage_type: UsageType, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct PaypalVaultResponse { id: String, status: String, customer: CustomerId, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct CustomerId { id: String, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum StoreInVault { OnSuccess, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum UsageType { Merchant, } #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] pub enum PaymentSourceItem { Card(CardRequest), Paypal(PaypalRedirectionRequest), IDeal(RedirectRequest), Eps(RedirectRequest), Giropay(RedirectRequest), Sofort(RedirectRequest), } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct CardVaultResponse { attributes: Option<AttributeResponse>, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "lowercase")] pub enum PaymentSourceItemResponse { Card(CardVaultResponse), Paypal(PaypalRedirectionResponse), Eps(EpsRedirectionResponse), Ideal(IdealRedirectionResponse), } #[derive(Debug, Serialize)] pub struct PaypalPaymentsRequest { intent: PaypalPaymentIntent, purchase_units: Vec<PurchaseUnitRequest>, payment_source: Option<PaymentSourceItem>, } #[derive(Debug, Serialize)] pub struct PaypalZeroMandateRequest { payment_source: ZeroMandateSourceItem, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum ZeroMandateSourceItem { Card(CardMandateRequest), Paypal(PaypalMandateStruct), } #[derive(Debug, Serialize, Deserialize)] pub struct PaypalMandateStruct { experience_context: Option<ContextStruct>, usage_type: UsageType, } #[derive(Debug, Deserialize, Serialize)] pub struct CardMandateRequest { billing_address: Option<Address>, expiry: Option<Secret<String>>, name: Option<Secret<String>>, number: Option<cards::CardNumber>, } #[derive(Debug, Deserialize, Serialize)] pub struct PaypalSetupMandatesResponse { id: String, customer: Customer, payment_source: ZeroMandateSourceItem, links: Vec<PaypalLinks>, } #[derive(Debug, Serialize, Deserialize)] pub struct Customer { id: String, } impl<F, T> TryFrom<ResponseRouterData<F, PaypalSetupMandatesResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaypalSetupMandatesResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let info_response = item.response; let mandate_reference = Some(MandateReference { connector_mandate_id: Some(info_response.id.clone()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }); // https://developer.paypal.com/docs/api/payment-tokens/v3/#payment-tokens_create // If 201 status code, then order is captured, other status codes are handled by the error handler let status = if item.http_code == 201 { enums::AttemptStatus::Charged } else { enums::AttemptStatus::Failure }; Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(info_response.id.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl TryFrom<&SetupMandateRouterData> for PaypalZeroMandateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> { let payment_source = match item.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => ZeroMandateSourceItem::Card(CardMandateRequest { billing_address: get_address_info(item.get_optional_billing()), expiry: Some(ccard.get_expiry_date_as_yyyymm("-")), name: item.get_optional_billing_full_name(), number: Some(ccard.card_number), }), PaymentMethodData::Wallet(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::MobilePayment(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ))?, }; Ok(Self { payment_source }) } } fn get_address_info( payment_address: Option<&hyperswitch_domain_models::address::Address>, ) -> Option<Address> { let address = payment_address.and_then(|payment_address| payment_address.address.as_ref()); match address { Some(address) => address.get_optional_country().map(|country| Address { country_code: country.to_owned(), address_line_1: address.line1.clone(), postal_code: address.zip.clone(), admin_area_2: address.city.clone(), }), None => None, } } fn get_payment_source( item: &PaymentsAuthorizeRouterData, bank_redirection_data: &BankRedirectData, ) -> Result<PaymentSourceItem, error_stack::Report<errors::ConnectorError>> { match bank_redirection_data { BankRedirectData::Eps { bank_name: _, .. } => Ok(PaymentSourceItem::Eps(RedirectRequest { name: item.get_billing_full_name()?, country_code: item.get_billing_country()?, experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), cancel_url: item.request.complete_authorize_url.clone(), shipping_preference: if item.get_optional_shipping_country().is_some() { ShippingPreference::SetProvidedAddress } else { ShippingPreference::GetFromFile }, user_action: Some(UserAction::PayNow), }, })), BankRedirectData::Giropay { .. } => Ok(PaymentSourceItem::Giropay(RedirectRequest { name: item.get_billing_full_name()?, country_code: item.get_billing_country()?, experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), cancel_url: item.request.complete_authorize_url.clone(), shipping_preference: if item.get_optional_shipping_country().is_some() { ShippingPreference::SetProvidedAddress } else { ShippingPreference::GetFromFile }, user_action: Some(UserAction::PayNow), }, })), BankRedirectData::Ideal { bank_name: _, .. } => { Ok(PaymentSourceItem::IDeal(RedirectRequest { name: item.get_billing_full_name()?, country_code: item.get_billing_country()?, experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), cancel_url: item.request.complete_authorize_url.clone(), shipping_preference: if item.get_optional_shipping_country().is_some() { ShippingPreference::SetProvidedAddress } else { ShippingPreference::GetFromFile }, user_action: Some(UserAction::PayNow), }, })) } BankRedirectData::Sofort { preferred_language: _, .. } => Ok(PaymentSourceItem::Sofort(RedirectRequest { name: item.get_billing_full_name()?, country_code: item.get_billing_country()?, experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), cancel_url: item.request.complete_authorize_url.clone(), shipping_preference: if item.get_optional_shipping_country().is_some() { ShippingPreference::SetProvidedAddress } else { ShippingPreference::GetFromFile }, user_action: Some(UserAction::PayNow), }, })), BankRedirectData::BancontactCard { .. } | BankRedirectData::Blik { .. } | BankRedirectData::Przelewy24 { .. } => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ) .into()), BankRedirectData::Bizum {} | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::Trustly { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::LocalBankRedirect {} => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ))?, } } fn get_payee(auth_type: &PaypalAuthType) -> Option<Payee> { auth_type .get_credentials() .ok() .and_then(|credentials| credentials.get_payer_id()) .map(|payer_id| Payee { merchant_id: payer_id, }) } impl TryFrom<&PaypalRouterData<&PaymentsPostSessionTokensRouterData>> for PaypalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaypalRouterData<&PaymentsPostSessionTokensRouterData>, ) -> Result<Self, Self::Error> { let intent = if item.router_data.request.is_auto_capture()? { PaypalPaymentIntent::Capture } else { PaypalPaymentIntent::Authorize }; let paypal_auth: PaypalAuthType = PaypalAuthType::try_from(&item.router_data.connector_auth_type)?; let payee = get_payee(&paypal_auth); let amount = OrderRequestAmount::try_from(item)?; let connector_request_reference_id = item.router_data.connector_request_reference_id.clone(); let shipping_address = ShippingAddress::from(item); let item_details = vec![ItemDetails::try_from(item)?]; let purchase_units = vec![PurchaseUnitRequest { reference_id: Some(connector_request_reference_id.clone()), custom_id: item.router_data.request.merchant_order_reference_id.clone(), invoice_id: Some(connector_request_reference_id), amount, payee, shipping: Some(shipping_address), items: item_details, }]; let payment_source = Some(PaymentSourceItem::Paypal( PaypalRedirectionRequest::PaypalRedirectionStruct(PaypalRedirectionStruct { experience_context: ContextStruct { return_url: item.router_data.request.router_return_url.clone(), cancel_url: item.router_data.request.router_return_url.clone(), shipping_preference: ShippingPreference::GetFromFile, user_action: Some(UserAction::PayNow), }, attributes: match item.router_data.request.setup_future_usage { Some(setup_future_usage) => match setup_future_usage { enums::FutureUsage::OffSession => Some(Attributes { vault: PaypalVault { store_in_vault: StoreInVault::OnSuccess, usage_type: UsageType::Merchant, }, }), enums::FutureUsage::OnSession => None, }, None => None, }, }), )); Ok(Self { intent, purchase_units, payment_source, }) } } impl TryFrom<&PaypalRouterData<&SdkSessionUpdateRouterData>> for PaypalUpdateOrderRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaypalRouterData<&SdkSessionUpdateRouterData>) -> Result<Self, Self::Error> { let op = PaypalOperationType::Replace; // Create separate paths for amount and items let reference_id = &item.router_data.connector_request_reference_id; let amount_path = format!("/purchase_units/@reference_id=='{reference_id}'/amount"); let items_path = format!("/purchase_units/@reference_id=='{reference_id}'/items"); let amount_value = Value::Amount(OrderRequestAmount::try_from(item)?); let items_value = Value::Items(vec![ItemDetails::try_from(item)?]); Ok(Self(vec![ Operation { op: op.clone(), path: amount_path, value: amount_value, }, Operation { op, path: items_path, value: items_value, }, ])) } } #[derive(Debug, Serialize)] pub struct PaypalExtendAuthorizationRequest { amount: OrderAmount, } impl TryFrom<&PaypalRouterData<&PaymentsExtendAuthorizationRouterData>> for PaypalExtendAuthorizationRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaypalRouterData<&PaymentsExtendAuthorizationRouterData>, ) -> Result<Self, Self::Error> { let amount = OrderAmount { currency_code: item.router_data.request.currency, value: item.amount.clone(), }; Ok(Self { amount }) } } impl TryFrom<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for PaypalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaypalRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let paypal_auth: PaypalAuthType = PaypalAuthType::try_from(&item.router_data.connector_auth_type)?; let payee = get_payee(&paypal_auth); let amount = OrderRequestAmount::from(item); let intent = if item.router_data.request.is_auto_capture()? { PaypalPaymentIntent::Capture } else { PaypalPaymentIntent::Authorize }; let connector_request_reference_id = item.router_data.connector_request_reference_id.clone(); let shipping_address = ShippingAddress::from(item); let item_details = vec![ItemDetails::from(item)]; let purchase_units = vec![PurchaseUnitRequest { reference_id: Some(connector_request_reference_id.clone()), custom_id: item.router_data.request.merchant_order_reference_id.clone(), invoice_id: Some(connector_request_reference_id), amount, payee, shipping: Some(shipping_address), items: item_details, }]; match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref ccard) => { let card = item.router_data.request.get_card()?; let expiry = Some(card.get_expiry_date_as_yyyymm("-")); let verification = match item.router_data.auth_type { enums::AuthenticationType::ThreeDs => Some(ThreeDsMethod { method: ThreeDsType::ScaAlways, }), enums::AuthenticationType::NoThreeDs => None, }; let payment_source = Some(PaymentSourceItem::Card(CardRequest::CardRequestStruct( CardRequestStruct { billing_address: get_address_info(item.router_data.get_optional_billing()), expiry, name: item.router_data.get_optional_billing_full_name(), number: Some(ccard.card_number.clone()), security_code: Some(ccard.card_cvc.clone()), attributes: Some(CardRequestAttributes { vault: match item.router_data.request.setup_future_usage { Some(setup_future_usage) => match setup_future_usage { enums::FutureUsage::OffSession => Some(PaypalVault { store_in_vault: StoreInVault::OnSuccess, usage_type: UsageType::Merchant, }), enums::FutureUsage::OnSession => None, }, None => None, }, verification, }), }, ))); Ok(Self { intent, purchase_units, payment_source, }) } PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { WalletData::PaypalRedirect(_) => { let payment_source = Some(PaymentSourceItem::Paypal( PaypalRedirectionRequest::PaypalRedirectionStruct( PaypalRedirectionStruct { experience_context: ContextStruct { return_url: item .router_data .request .complete_authorize_url .clone(), cancel_url: item .router_data .request .complete_authorize_url .clone(), shipping_preference: if item .router_data .get_optional_shipping() .is_some() { ShippingPreference::SetProvidedAddress } else { ShippingPreference::GetFromFile }, user_action: Some(UserAction::PayNow), }, attributes: match item.router_data.request.setup_future_usage { Some(setup_future_usage) => match setup_future_usage { enums::FutureUsage::OffSession => Some(Attributes { vault: PaypalVault { store_in_vault: StoreInVault::OnSuccess, usage_type: UsageType::Merchant, }, }), enums::FutureUsage::OnSession => None, }, None => None, }, }, ), )); Ok(Self { intent, purchase_units, payment_source, }) } WalletData::PaypalSdk(_) => { let payment_source = Some(PaymentSourceItem::Paypal( PaypalRedirectionRequest::PaypalRedirectionStruct( PaypalRedirectionStruct { experience_context: ContextStruct { return_url: None, cancel_url: None, shipping_preference: ShippingPreference::GetFromFile, user_action: Some(UserAction::PayNow), }, attributes: match item.router_data.request.setup_future_usage { Some(setup_future_usage) => match setup_future_usage { enums::FutureUsage::OffSession => Some(Attributes { vault: PaypalVault { store_in_vault: StoreInVault::OnSuccess, usage_type: UsageType::Merchant, }, }), enums::FutureUsage::OnSession => None, }, None => None, }, }, ), )); Ok(Self { intent, purchase_units, payment_source, }) } WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::AmazonPay(_) | WalletData::ApplePay(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePay(_) | WalletData::BluecodeRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) | WalletData::Paze(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ))?, }, PaymentMethodData::BankRedirect(ref bank_redirection_data) => { let bank_redirect_intent = if item.router_data.request.is_auto_capture()? { PaypalPaymentIntent::Capture } else { Err(errors::ConnectorError::FlowNotSupported { flow: "Manual capture method for Bank Redirect".to_string(), connector: "Paypal".to_string(), })? }; let payment_source = Some(get_payment_source(item.router_data, bank_redirection_data)?); Ok(Self { intent: bank_redirect_intent, purchase_units, payment_source, }) } PaymentMethodData::CardRedirect(ref card_redirect_data) => { Self::try_from(card_redirect_data) } PaymentMethodData::PayLater(ref paylater_data) => Self::try_from(paylater_data), PaymentMethodData::BankDebit(ref bank_debit_data) => Self::try_from(bank_debit_data), PaymentMethodData::BankTransfer(ref bank_transfer_data) => { Self::try_from(bank_transfer_data.as_ref()) } PaymentMethodData::Voucher(ref voucher_data) => Self::try_from(voucher_data), PaymentMethodData::GiftCard(ref giftcard_data) => { Self::try_from(giftcard_data.as_ref()) } PaymentMethodData::MandatePayment => { let payment_method_type = item .router_data .get_recurring_mandate_payment_data()? .payment_method_type .ok_or_else(missing_field_err("payment_method_type"))?; let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "connector_mandate_id", }, )?; let payment_source = match payment_method_type { #[cfg(feature = "v1")] enums::PaymentMethodType::Credit | enums::PaymentMethodType::Debit => Ok(Some( PaymentSourceItem::Card(CardRequest::CardVaultStruct(VaultStruct { vault_id: connector_mandate_id.into(), })), )), #[cfg(feature = "v2")] enums::PaymentMethodType::Credit | enums::PaymentMethodType::Debit | enums::PaymentMethodType::Card => Ok(Some(PaymentSourceItem::Card( CardRequest::CardVaultStruct(VaultStruct { vault_id: connector_mandate_id.into(), }), ))), enums::PaymentMethodType::Paypal => Ok(Some(PaymentSourceItem::Paypal( PaypalRedirectionRequest::PaypalVaultStruct(VaultStruct { vault_id: connector_mandate_id.into(), }), ))), enums::PaymentMethodType::Ach | enums::PaymentMethodType::Affirm | enums::PaymentMethodType::AfterpayClearpay | enums::PaymentMethodType::Alfamart | enums::PaymentMethodType::AliPay | enums::PaymentMethodType::AliPayHk | enums::PaymentMethodType::Alma | enums::PaymentMethodType::AmazonPay | enums::PaymentMethodType::Paysera | enums::PaymentMethodType::Skrill | enums::PaymentMethodType::ApplePay | enums::PaymentMethodType::Atome | enums::PaymentMethodType::Bacs | enums::PaymentMethodType::BancontactCard | enums::PaymentMethodType::Becs | enums::PaymentMethodType::Benefit | enums::PaymentMethodType::Bizum | enums::PaymentMethodType::BhnCardNetwork | enums::PaymentMethodType::Blik | enums::PaymentMethodType::Boleto | enums::PaymentMethodType::BcaBankTransfer | enums::PaymentMethodType::BniVa | enums::PaymentMethodType::BriVa | enums::PaymentMethodType::CardRedirect | enums::PaymentMethodType::CimbVa | enums::PaymentMethodType::ClassicReward | enums::PaymentMethodType::CryptoCurrency | enums::PaymentMethodType::Cashapp | enums::PaymentMethodType::Dana | enums::PaymentMethodType::DanamonVa | enums::PaymentMethodType::DirectCarrierBilling | enums::PaymentMethodType::DuitNow | enums::PaymentMethodType::Efecty | enums::PaymentMethodType::Eft | enums::PaymentMethodType::Eps | enums::PaymentMethodType::Bluecode | enums::PaymentMethodType::Fps | enums::PaymentMethodType::Evoucher | enums::PaymentMethodType::Giropay | enums::PaymentMethodType::Givex | enums::PaymentMethodType::GooglePay | enums::PaymentMethodType::GoPay | enums::PaymentMethodType::Gcash | enums::PaymentMethodType::Ideal | enums::PaymentMethodType::Interac | enums::PaymentMethodType::Indomaret | enums::PaymentMethodType::Klarna | enums::PaymentMethodType::KakaoPay | enums::PaymentMethodType::LocalBankRedirect | enums::PaymentMethodType::MandiriVa | enums::PaymentMethodType::Knet | enums::PaymentMethodType::MbWay | enums::PaymentMethodType::MobilePay | enums::PaymentMethodType::Momo | enums::PaymentMethodType::MomoAtm | enums::PaymentMethodType::Multibanco | enums::PaymentMethodType::OnlineBankingThailand | enums::PaymentMethodType::OnlineBankingCzechRepublic | enums::PaymentMethodType::OnlineBankingFinland | enums::PaymentMethodType::OnlineBankingFpx | enums::PaymentMethodType::OnlineBankingPoland | enums::PaymentMethodType::OnlineBankingSlovakia | enums::PaymentMethodType::OpenBankingPIS | enums::PaymentMethodType::Oxxo | enums::PaymentMethodType::PagoEfectivo | enums::PaymentMethodType::PermataBankTransfer | enums::PaymentMethodType::OpenBankingUk | enums::PaymentMethodType::PayBright | enums::PaymentMethodType::Pix | enums::PaymentMethodType::PaySafeCard | enums::PaymentMethodType::Przelewy24 | enums::PaymentMethodType::PromptPay | enums::PaymentMethodType::Pse | enums::PaymentMethodType::RedCompra | enums::PaymentMethodType::RedPagos | enums::PaymentMethodType::SamsungPay | enums::PaymentMethodType::Sepa | enums::PaymentMethodType::SepaGuarenteedDebit | enums::PaymentMethodType::SepaBankTransfer | enums::PaymentMethodType::Sofort | enums::PaymentMethodType::Swish | enums::PaymentMethodType::TouchNGo | enums::PaymentMethodType::Trustly | enums::PaymentMethodType::Twint | enums::PaymentMethodType::UpiCollect | enums::PaymentMethodType::UpiIntent | enums::PaymentMethodType::Vipps | enums::PaymentMethodType::VietQr | enums::PaymentMethodType::Venmo | enums::PaymentMethodType::Walley | enums::PaymentMethodType::WeChatPay | enums::PaymentMethodType::SevenEleven | enums::PaymentMethodType::Lawson | enums::PaymentMethodType::MiniStop | enums::PaymentMethodType::FamilyMart | enums::PaymentMethodType::Seicomart | enums::PaymentMethodType::PayEasy | enums::PaymentMethodType::LocalBankTransfer | enums::PaymentMethodType::InstantBankTransfer | enums::PaymentMethodType::InstantBankTransferFinland | enums::PaymentMethodType::InstantBankTransferPoland | enums::PaymentMethodType::Mifinity | enums::PaymentMethodType::Paze | enums::PaymentMethodType::IndonesianBankTransfer | enums::PaymentMethodType::Flexiti | enums::PaymentMethodType::RevolutPay | enums::PaymentMethodType::Breadpay | enums::PaymentMethodType::UpiQr => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("paypal"), )) } }; Ok(Self { intent, purchase_units, payment_source: payment_source?, }) } PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::Upi(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ) .into()) } } } } impl TryFrom<&CardRedirectData> for PaypalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: &CardRedirectData) -> Result<Self, Self::Error> { match value { CardRedirectData::Knet {} | CardRedirectData::Benefit {} | CardRedirectData::MomoAtm {} | CardRedirectData::CardRedirect {} => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ) .into()), } } } impl TryFrom<&PayLaterData> for PaypalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: &PayLaterData) -> Result<Self, Self::Error> { match value { PayLaterData::KlarnaRedirect { .. } | PayLaterData::KlarnaSdk { .. } | PayLaterData::AffirmRedirect {} | PayLaterData::AfterpayClearpayRedirect { .. } | PayLaterData::PayBrightRedirect {} | PayLaterData::WalleyRedirect {} | PayLaterData::FlexitiRedirect {} | PayLaterData::AlmaRedirect {} | PayLaterData::AtomeRedirect {} | PayLaterData::BreadpayRedirect {} => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ) .into()), } } } impl TryFrom<&BankDebitData> for PaypalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: &BankDebitData) -> Result<Self, Self::Error> { match value { BankDebitData::AchBankDebit { .. } | BankDebitData::SepaBankDebit { .. } | BankDebitData::BecsBankDebit { .. } | BankDebitData::BacsBankDebit { .. } | BankDebitData::SepaGuarenteedBankDebit { .. } => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ) .into()) } } } } impl TryFrom<&BankTransferData> for PaypalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: &BankTransferData) -> Result<Self, Self::Error> { match value { BankTransferData::AchBankTransfer { .. } | BankTransferData::SepaBankTransfer { .. } | BankTransferData::BacsBankTransfer { .. } | BankTransferData::MultibancoBankTransfer { .. } | BankTransferData::PermataBankTransfer { .. } | BankTransferData::BcaBankTransfer { .. } | BankTransferData::BniVaBankTransfer { .. } | BankTransferData::BriVaBankTransfer { .. } | BankTransferData::CimbVaBankTransfer { .. } | BankTransferData::DanamonVaBankTransfer { .. } | BankTransferData::MandiriVaBankTransfer { .. } | BankTransferData::Pix { .. } | BankTransferData::Pse {} | BankTransferData::InstantBankTransfer {} | BankTransferData::InstantBankTransferFinland {} | BankTransferData::InstantBankTransferPoland {} | BankTransferData::IndonesianBankTransfer { .. } | BankTransferData::LocalBankTransfer { .. } => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ) .into()) } } } } impl TryFrom<&VoucherData> for PaypalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: &VoucherData) -> Result<Self, Self::Error> { match value { VoucherData::Boleto(_) | VoucherData::Efecty | VoucherData::PagoEfectivo | VoucherData::RedCompra | VoucherData::RedPagos | VoucherData::Alfamart(_) | VoucherData::Indomaret(_) | VoucherData::Oxxo | VoucherData::SevenEleven(_) | VoucherData::Lawson(_) | VoucherData::MiniStop(_) | VoucherData::FamilyMart(_) | VoucherData::Seicomart(_) | VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ) .into()), } } } impl TryFrom<&GiftCardData> for PaypalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: &GiftCardData) -> Result<Self, Self::Error> { match value { GiftCardData::Givex(_) | GiftCardData::PaySafeCard {} | GiftCardData::BhnCardNetwork(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ) .into()), } } } #[derive(Debug, Clone, Serialize, PartialEq)] pub struct PaypalAuthUpdateRequest { grant_type: String, client_id: Secret<String>, client_secret: Secret<String>, } impl TryFrom<&RefreshTokenRouterData> for PaypalAuthUpdateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> { Ok(Self { grant_type: "client_credentials".to_string(), client_id: item.get_request_id()?, client_secret: item.request.app_id.clone(), }) } } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct PaypalAuthUpdateResponse { pub access_token: Secret<String>, pub token_type: String, pub expires_in: i64, } impl<F, T> TryFrom<ResponseRouterData<F, PaypalAuthUpdateResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaypalAuthUpdateResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(AccessToken { token: item.response.access_token, expires: item.response.expires_in, }), ..item.data }) } } #[derive(Debug, Serialize)] pub struct PaypalIncrementalAuthRequest { amount: OrderAmount, } impl TryFrom<&PaypalRouterData<&PaymentsIncrementalAuthorizationRouterData>> for PaypalIncrementalAuthRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaypalRouterData<&PaymentsIncrementalAuthorizationRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { amount: OrderAmount { currency_code: item.router_data.request.currency, value: item.amount.clone(), }, }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub struct PaypalExtendedAuthResponse { status: PaypalIncrementalStatus, status_details: Option<PaypalIncrementalAuthStatusDetails>, id: String, links: Vec<PaypalLinks>, expiration_time: Option<PrimitiveDateTime>, create_time: Option<PrimitiveDateTime>, update_time: Option<PrimitiveDateTime>, } #[derive(Debug, Deserialize, Serialize)] pub struct PaypalIncrementalAuthResponse { status: PaypalIncrementalStatus, status_details: PaypalIncrementalAuthStatusDetails, id: String, invoice_id: String, custom_id: String, links: Vec<PaypalLinks>, amount: OrderAmount, network_transaction_reference: PaypalNetworkTransactionReference, expiration_time: String, create_time: String, update_time: String, supplementary_data: PaypalSupplementaryData, payee: Payee, name: Option<String>, message: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaypalIncrementalStatus { CREATED, CAPTURED, DENIED, PARTIALLYCAPTURED, VOIDED, PENDING, } #[derive(Debug, Deserialize, Serialize)] pub struct PaypalNetworkTransactionReference { id: String, } #[derive(Debug, Deserialize, Serialize)] pub struct PaypalIncrementalAuthStatusDetails { reason: Option<PaypalStatusPendingReason>, } #[derive(Debug, Deserialize, Serialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaypalStatusPendingReason { PENDINGREVIEW, DECLINEDBYRISKFRAUDFILTERS, } impl From<PaypalIncrementalStatus> for common_enums::AuthorizationStatus { fn from(item: PaypalIncrementalStatus) -> Self { match item { PaypalIncrementalStatus::CREATED | PaypalIncrementalStatus::CAPTURED | PaypalIncrementalStatus::PARTIALLYCAPTURED => Self::Success, PaypalIncrementalStatus::PENDING => Self::Processing, PaypalIncrementalStatus::DENIED | PaypalIncrementalStatus::VOIDED => Self::Failure, } } } impl From<PaypalIncrementalStatus> for common_enums::AttemptStatus { fn from(item: PaypalIncrementalStatus) -> Self { match item { PaypalIncrementalStatus::CREATED | PaypalIncrementalStatus::CAPTURED | PaypalIncrementalStatus::PARTIALLYCAPTURED => Self::Authorized, PaypalIncrementalStatus::PENDING => Self::Pending, PaypalIncrementalStatus::DENIED | PaypalIncrementalStatus::VOIDED => Self::Failure, } } } fn is_extend_authorization_applied( item: PaypalIncrementalStatus, ) -> Option<common_types::primitive_wrappers::ExtendedAuthorizationAppliedBool> { match item { PaypalIncrementalStatus::CREATED | PaypalIncrementalStatus::CAPTURED | PaypalIncrementalStatus::PARTIALLYCAPTURED => { Some(common_types::primitive_wrappers::ExtendedAuthorizationAppliedBool::from(true)) } PaypalIncrementalStatus::PENDING => None, PaypalIncrementalStatus::DENIED | PaypalIncrementalStatus::VOIDED => { Some(common_types::primitive_wrappers::ExtendedAuthorizationAppliedBool::from(false)) } } } impl<F> TryFrom< ResponseRouterData< F, PaypalIncrementalAuthResponse, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >, > for RouterData<F, PaymentsIncrementalAuthorizationData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, PaypalIncrementalAuthResponse, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = common_enums::AuthorizationStatus::from(item.response.status); Ok(Self { response: Ok(PaymentsResponseData::IncrementalAuthorizationResponse { status, error_code: None, error_message: None, connector_authorization_id: Some(item.response.id), }), ..item.data }) } } impl<F> TryFrom< ResponseRouterData< F, PaypalExtendedAuthResponse, PaymentsExtendAuthorizationData, PaymentsResponseData, >, > for RouterData<F, PaymentsExtendAuthorizationData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, PaypalExtendedAuthResponse, PaymentsExtendAuthorizationData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let extend_authorization_response = ExtendedAuthorizationResponseData { extended_authentication_applied: is_extend_authorization_applied( item.response.status.clone(), ), capture_before: item.response.expiration_time, }; let connector_response = Some(ConnectorResponseData::new( None, None, Some(extend_authorization_response), )); let status = common_enums::AttemptStatus::from(item.response.status.clone()); let response = if is_payment_failure(status) { let reason = item .response .status_details .and_then(|status_details| status_details.reason.map(|reason| reason.to_string())); Err(ErrorResponse { code: reason .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: reason .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) }; Ok(Self { status, response, connector_response, ..item.data }) } } #[derive(Debug)] pub enum PaypalAuthType { TemporaryAuth, AuthWithDetails(PaypalConnectorCredentials), } #[derive(Debug)] pub enum PaypalConnectorCredentials { StandardIntegration(StandardFlowCredentials), PartnerIntegration(PartnerFlowCredentials), } impl PaypalConnectorCredentials { pub fn get_client_id(&self) -> Secret<String> { match self { Self::StandardIntegration(item) => item.client_id.clone(), Self::PartnerIntegration(item) => item.client_id.clone(), } } pub fn get_client_secret(&self) -> Secret<String> { match self { Self::StandardIntegration(item) => item.client_secret.clone(), Self::PartnerIntegration(item) => item.client_secret.clone(), } } pub fn get_payer_id(&self) -> Option<Secret<String>> { match self { Self::StandardIntegration(_) => None, Self::PartnerIntegration(item) => Some(item.payer_id.clone()), } } pub fn generate_authorization_value(&self) -> String { let auth_id = format!( "{}:{}", self.get_client_id().expose(), self.get_client_secret().expose(), ); format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id)) } } #[derive(Debug)] pub struct StandardFlowCredentials { pub(super) client_id: Secret<String>, pub(super) client_secret: Secret<String>, } #[derive(Debug)] pub struct PartnerFlowCredentials { pub(super) client_id: Secret<String>, pub(super) client_secret: Secret<String>, pub(super) payer_id: Secret<String>, } impl PaypalAuthType { pub fn get_credentials( &self, ) -> CustomResult<&PaypalConnectorCredentials, errors::ConnectorError> { match self { Self::TemporaryAuth => Err(errors::ConnectorError::InvalidConnectorConfig { config: "TemporaryAuth found in connector_account_details", } .into()), Self::AuthWithDetails(credentials) => Ok(credentials), } } } impl TryFrom<&ConnectorAuthType> for PaypalAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self::AuthWithDetails( PaypalConnectorCredentials::StandardIntegration(StandardFlowCredentials { client_id: key1.to_owned(), client_secret: api_key.to_owned(), }), )), ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self::AuthWithDetails( PaypalConnectorCredentials::PartnerIntegration(PartnerFlowCredentials { client_id: key1.to_owned(), client_secret: api_key.to_owned(), payer_id: api_secret.to_owned(), }), )), ConnectorAuthType::TemporaryAuth => Ok(Self::TemporaryAuth), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaypalOrderStatus { Pending, Completed, Voided, Created, Saved, PayerActionRequired, Approved, } pub(crate) fn get_order_status( item: PaypalOrderStatus, intent: PaypalPaymentIntent, ) -> storage_enums::AttemptStatus { match item { PaypalOrderStatus::Completed => { if intent == PaypalPaymentIntent::Authorize { storage_enums::AttemptStatus::Authorized } else { storage_enums::AttemptStatus::Charged } } PaypalOrderStatus::Voided => storage_enums::AttemptStatus::Voided, PaypalOrderStatus::Created | PaypalOrderStatus::Saved | PaypalOrderStatus::Pending => { storage_enums::AttemptStatus::Pending } PaypalOrderStatus::Approved => storage_enums::AttemptStatus::AuthenticationSuccessful, PaypalOrderStatus::PayerActionRequired => { storage_enums::AttemptStatus::AuthenticationPending } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentsCollectionItem { amount: OrderAmount, expiration_time: Option<String>, id: String, final_capture: Option<bool>, status: PaypalPaymentStatus, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct PaymentsCollection { authorizations: Option<Vec<PaymentsCollectionItem>>, captures: Option<Vec<PaymentsCollectionItem>>, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct PurchaseUnitItem { pub reference_id: Option<String>, pub invoice_id: Option<String>, pub payments: PaymentsCollection, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaypalThreeDsResponse { id: String, status: PaypalOrderStatus, links: Vec<PaypalLinks>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum PaypalPreProcessingResponse { PaypalLiabilityResponse(PaypalLiabilityResponse), PaypalNonLiabilityResponse(PaypalNonLiabilityResponse), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaypalLiabilityResponse { pub payment_source: CardParams, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaypalNonLiabilityResponse { payment_source: CardsData, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CardParams { pub card: AuthResult, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AuthResult { pub authentication_result: PaypalThreeDsParams, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaypalThreeDsParams { pub liability_shift: LiabilityShift, pub three_d_secure: ThreeDsCheck, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ThreeDsCheck { pub enrollment_status: Option<EnrollmentStatus>, pub authentication_status: Option<AuthenticationStatus>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum LiabilityShift { Possible, No, Unknown, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum EnrollmentStatus { Null, #[serde(rename = "Y")] Ready, #[serde(rename = "N")] NotReady, #[serde(rename = "U")] Unavailable, #[serde(rename = "B")] Bypassed, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum AuthenticationStatus { Null, #[serde(rename = "Y")] Success, #[serde(rename = "N")] Failed, #[serde(rename = "R")] Rejected, #[serde(rename = "A")] Attempted, #[serde(rename = "U")] Unable, #[serde(rename = "C")] ChallengeRequired, #[serde(rename = "I")] InfoOnly, #[serde(rename = "D")] Decoupled, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaypalOrdersResponse { id: String, intent: PaypalPaymentIntent, status: PaypalOrderStatus, purchase_units: Vec<PurchaseUnitItem>, payment_source: Option<PaymentSourceItemResponse>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaypalLinks { href: Option<Url>, rel: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RedirectPurchaseUnitItem { pub invoice_id: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaypalRedirectResponse { id: String, intent: PaypalPaymentIntent, status: PaypalOrderStatus, purchase_units: Vec<RedirectPurchaseUnitItem>, links: Vec<PaypalLinks>, payment_source: Option<PaymentSourceItemResponse>, } // Note: Don't change order of deserialization of variant, priority is in descending order #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum PaypalAuthResponse { PaypalOrdersResponse(PaypalOrdersResponse), PaypalRedirectResponse(PaypalRedirectResponse), PaypalThreeDsResponse(PaypalThreeDsResponse), } // Note: Don't change order of deserialization of variant, priority is in descending order #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum PaypalSyncResponse { PaypalOrdersSyncResponse(PaypalOrdersResponse), PaypalThreeDsSyncResponse(PaypalThreeDsSyncResponse), PaypalRedirectSyncResponse(PaypalRedirectResponse), PaypalPaymentsSyncResponse(PaypalPaymentsSyncResponse), } #[derive(Debug, Serialize, Deserialize)] pub struct PaypalPaymentsSyncResponse { id: String, status: PaypalPaymentStatus, amount: OrderAmount, invoice_id: Option<String>, supplementary_data: PaypalSupplementaryData, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaypalThreeDsSyncResponse { id: String, status: PaypalOrderStatus, // provided to separated response of card's 3DS from other payment_source: CardsData, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CardsData { card: CardDetails, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CardDetails { last_digits: String, } #[derive(Debug, Serialize, Deserialize)] pub struct PaypalMeta { pub authorize_id: Option<String>, pub capture_id: Option<String>, pub incremental_authorization_id: Option<String>, pub psync_flow: PaypalPaymentIntent, pub next_action: Option<api_models::payments::NextActionCall>, pub order_id: Option<String>, } fn get_id_based_on_intent( intent: &PaypalPaymentIntent, purchase_unit: &PurchaseUnitItem, ) -> CustomResult<String, errors::ConnectorError> { || -> _ { match intent { PaypalPaymentIntent::Capture => Some( purchase_unit .payments .captures .clone()? .into_iter() .next()? .id, ), PaypalPaymentIntent::Authorize => Some( purchase_unit .payments .authorizations .clone()? .into_iter() .next()? .id, ), PaypalPaymentIntent::Authenticate => None, } }() .ok_or_else(|| errors::ConnectorError::MissingConnectorTransactionID.into()) } fn extract_incremental_authorization_id(response: &PaypalOrdersResponse) -> Option<String> { for unit in &response.purchase_units { if let Some(authorizations) = &unit.payments.authorizations { if let Some(first_auth) = authorizations.first() { return Some(first_auth.id.clone()); } } } None } impl<F, Req> TryFrom<ResponseRouterData<F, PaypalOrdersResponse, Req, PaymentsResponseData>> for RouterData<F, Req, PaymentsResponseData> where Req: GetRequestIncrementalAuthorization, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaypalOrdersResponse, Req, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let purchase_units = item .response .purchase_units .first() .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?; let id = get_id_based_on_intent(&item.response.intent, purchase_units)?; let (connector_meta, order_id) = match item.response.intent.clone() { PaypalPaymentIntent::Capture => ( serde_json::json!(PaypalMeta { authorize_id: None, capture_id: Some(id), incremental_authorization_id: None, psync_flow: item.response.intent.clone(), next_action: None, order_id: None, }), ResponseId::ConnectorTransactionId(item.response.id.clone()), ), PaypalPaymentIntent::Authorize => ( serde_json::json!(PaypalMeta { authorize_id: Some(id), capture_id: None, incremental_authorization_id: extract_incremental_authorization_id( &item.response ), psync_flow: item.response.intent.clone(), next_action: None, order_id: None, }), ResponseId::ConnectorTransactionId(item.response.id.clone()), ), PaypalPaymentIntent::Authenticate => { Err(errors::ConnectorError::ResponseDeserializationFailed)? } }; //payment collection will always have only one element as we only make one transaction per order. let payment_collection = &item .response .purchase_units .first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)? .payments; //payment collection item will either have "authorizations" field or "capture" field, not both at a time. let payment_collection_item = match ( &payment_collection.authorizations, &payment_collection.captures, ) { (Some(authorizations), None) => authorizations.first(), (None, Some(captures)) => captures.first(), (Some(_), Some(captures)) => captures.first(), _ => None, } .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; let status = payment_collection_item.status.clone(); let status = storage_enums::AttemptStatus::from(status); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: order_id, redirection_data: Box::new(None), mandate_reference: Box::new(Some(MandateReference { connector_mandate_id: match item.response.payment_source.clone() { Some(paypal_source) => match paypal_source { PaymentSourceItemResponse::Paypal(paypal_source) => { paypal_source.attributes.map(|attr| attr.vault.id) } PaymentSourceItemResponse::Card(card) => { card.attributes.map(|attr| attr.vault.id) } PaymentSourceItemResponse::Eps(_) | PaymentSourceItemResponse::Ideal(_) => None, }, None => None, }, payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, })), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: purchase_units .invoice_id .clone() .or(Some(item.response.id)), incremental_authorization_allowed: item .data .request .get_request_incremental_authorization(), charges: None, }), ..item.data }) } } fn get_redirect_url( link_vec: Vec<PaypalLinks>, ) -> CustomResult<Option<Url>, errors::ConnectorError> { let mut link: Option<Url> = None; for item2 in link_vec.iter() { if item2.rel == "payer-action" { link.clone_from(&item2.href) } } Ok(link) } impl<F> ForeignTryFrom<( ResponseRouterData<F, PaypalSyncResponse, PaymentsSyncData, PaymentsResponseData>, Option<common_enums::PaymentExperience>, )> for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from( (item, payment_experience): ( ResponseRouterData<F, PaypalSyncResponse, PaymentsSyncData, PaymentsResponseData>, Option<common_enums::PaymentExperience>, ), ) -> Result<Self, Self::Error> { match item.response { PaypalSyncResponse::PaypalOrdersSyncResponse(response) => { Self::try_from(ResponseRouterData { response, data: item.data, http_code: item.http_code, }) } PaypalSyncResponse::PaypalRedirectSyncResponse(response) => Self::foreign_try_from(( ResponseRouterData { response, data: item.data, http_code: item.http_code, }, payment_experience, )), PaypalSyncResponse::PaypalPaymentsSyncResponse(response) => { Self::try_from(ResponseRouterData { response, data: item.data, http_code: item.http_code, }) } PaypalSyncResponse::PaypalThreeDsSyncResponse(response) => { Self::try_from(ResponseRouterData { response, data: item.data, http_code: item.http_code, }) } } } } impl<F, T> ForeignTryFrom<( ResponseRouterData<F, PaypalRedirectResponse, T, PaymentsResponseData>, Option<common_enums::PaymentExperience>, )> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from( (item, payment_experience): ( ResponseRouterData<F, PaypalRedirectResponse, T, PaymentsResponseData>, Option<common_enums::PaymentExperience>, ), ) -> Result<Self, Self::Error> { let status = get_order_status(item.response.clone().status, item.response.intent.clone()); let link = get_redirect_url(item.response.links.clone())?; // For Paypal SDK flow, we need to trigger SDK client and then complete authorize let next_action = if let Some(common_enums::PaymentExperience::InvokeSdkClient) = payment_experience { Some(api_models::payments::NextActionCall::CompleteAuthorize) } else { None }; let connector_meta = serde_json::json!(PaypalMeta { authorize_id: None, capture_id: None, incremental_authorization_id: None, psync_flow: item.response.intent, next_action, order_id: None, }); let purchase_units = item.response.purchase_units.first(); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(Some(RedirectForm::from(( link.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?, Method::Get, )))), mandate_reference: Box::new(None), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: Some( purchase_units.map_or(item.response.id, |item| item.invoice_id.clone()), ), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl TryFrom< ResponseRouterData< Authorize, PaypalRedirectResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for PaymentsAuthorizeRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Authorize, PaypalRedirectResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = get_order_status(item.response.clone().status, item.response.intent.clone()); let link = get_redirect_url(item.response.links.clone())?; let connector_meta = serde_json::json!(PaypalMeta { authorize_id: None, capture_id: None, incremental_authorization_id: None, psync_flow: item.response.intent, next_action: None, order_id: None, }); let purchase_units = item.response.purchase_units.first(); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(Some(RedirectForm::from(( link.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?, Method::Get, )))), mandate_reference: Box::new(None), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: Some( purchase_units.map_or(item.response.id, |item| item.invoice_id.clone()), ), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl TryFrom< ResponseRouterData< PostSessionTokens, PaypalRedirectResponse, PaymentsPostSessionTokensData, PaymentsResponseData, >, > for PaymentsPostSessionTokensRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< PostSessionTokens, PaypalRedirectResponse, PaymentsPostSessionTokensData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = get_order_status(item.response.clone().status, item.response.intent.clone()); // For Paypal SDK flow, we need to trigger SDK client and then Confirm let next_action = Some(api_models::payments::NextActionCall::Confirm); let connector_meta = serde_json::json!(PaypalMeta { authorize_id: None, capture_id: None, incremental_authorization_id: None, psync_flow: item.response.intent, next_action, order_id: Some(item.response.id.clone()), }); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl<F> TryFrom< ResponseRouterData<F, PaypalThreeDsSyncResponse, PaymentsSyncData, PaymentsResponseData>, > for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, PaypalThreeDsSyncResponse, PaymentsSyncData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { // status is hardcoded because this try_from will only be reached in card 3ds before the completion of complete authorize flow. // also force sync won't be hit in terminal status thus leaving us with only one status to get here. status: storage_enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl<F> TryFrom< ResponseRouterData<F, PaypalThreeDsResponse, PaymentsAuthorizeData, PaymentsResponseData>, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, PaypalThreeDsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let connector_meta = serde_json::json!(PaypalMeta { authorize_id: None, capture_id: None, incremental_authorization_id: None, psync_flow: PaypalPaymentIntent::Authenticate, // when there is no capture or auth id present next_action: None, order_id: None, }); let status = get_order_status( item.response.clone().status, PaypalPaymentIntent::Authenticate, ); let link = get_redirect_url(item.response.links.clone())?; Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(Some(paypal_threeds_link(( link, item.data.request.complete_authorize_url.clone(), ))?)), mandate_reference: Box::new(None), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } fn paypal_threeds_link( (redirect_url, complete_auth_url): (Option<Url>, Option<String>), ) -> CustomResult<RedirectForm, errors::ConnectorError> { let mut redirect_url = redirect_url.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; let complete_auth_url = complete_auth_url.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "complete_authorize_url", })?; let mut form_fields = std::collections::HashMap::from_iter( redirect_url .query_pairs() .map(|(key, value)| (key.to_string(), value.to_string())), ); // paypal requires return url to be passed as a field along with payer_action_url form_fields.insert(String::from("redirect_uri"), complete_auth_url); // Do not include query params in the endpoint redirect_url.set_query(None); Ok(RedirectForm::Form { endpoint: redirect_url.to_string(), method: Method::Get, form_fields, }) } impl<F, T> TryFrom<ResponseRouterData<F, PaypalPaymentsSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaypalPaymentsSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: storage_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response .supplementary_data .related_ids .order_id .clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item .response .invoice_id .clone() .or(Some(item.response.supplementary_data.related_ids.order_id)), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] pub struct PaypalFulfillRequest { sender_batch_header: PayoutBatchHeader, items: Vec<PaypalPayoutItem>, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] pub struct PayoutBatchHeader { sender_batch_id: String, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] pub struct PaypalPayoutItem { amount: PayoutAmount, note: Option<String>, notification_language: String, #[serde(flatten)] payout_method_data: PaypalPayoutMethodData, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] pub struct PaypalPayoutMethodData { recipient_type: PayoutRecipientType, recipient_wallet: PayoutWalletType, receiver: PaypalPayoutDataType, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayoutRecipientType { Email, PaypalId, Phone, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayoutWalletType { Paypal, Venmo, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaypalPayoutDataType { EmailType(Email), OtherType(Secret<String>), } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] pub struct PayoutAmount { value: StringMajorUnit, currency: storage_enums::Currency, } #[cfg(feature = "payouts")] impl TryFrom<&PaypalRouterData<&PayoutsRouterData<PoFulfill>>> for PaypalFulfillRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaypalRouterData<&PayoutsRouterData<PoFulfill>>, ) -> Result<Self, Self::Error> { let item_data = PaypalPayoutItem::try_from(item)?; Ok(Self { sender_batch_header: PayoutBatchHeader { sender_batch_id: item.router_data.connector_request_reference_id.to_owned(), }, items: vec![item_data], }) } } #[cfg(feature = "payouts")] impl TryFrom<&PaypalRouterData<&PayoutsRouterData<PoFulfill>>> for PaypalPayoutItem { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaypalRouterData<&PayoutsRouterData<PoFulfill>>, ) -> Result<Self, Self::Error> { let amount = PayoutAmount { value: item.amount.clone(), currency: item.router_data.request.destination_currency, }; let payout_method_data = match item.router_data.get_payout_method_data()? { PayoutMethodData::Wallet(wallet_data) => match wallet_data { WalletPayout::Paypal(data) => { let (recipient_type, receiver) = match (data.email, data.telephone_number, data.paypal_id) { (Some(email), _, _) => ( PayoutRecipientType::Email, PaypalPayoutDataType::EmailType(email), ), (_, Some(phone), _) => ( PayoutRecipientType::Phone, PaypalPayoutDataType::OtherType(phone), ), (_, _, Some(paypal_id)) => ( PayoutRecipientType::PaypalId, PaypalPayoutDataType::OtherType(paypal_id), ), _ => Err(errors::ConnectorError::MissingRequiredField { field_name: "receiver_data", })?, }; PaypalPayoutMethodData { recipient_type, recipient_wallet: PayoutWalletType::Paypal, receiver, } } WalletPayout::Venmo(data) => { let receiver = PaypalPayoutDataType::OtherType(data.telephone_number.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "telephone_number", }, )?); PaypalPayoutMethodData { recipient_type: PayoutRecipientType::Phone, recipient_wallet: PayoutWalletType::Venmo, receiver, } } WalletPayout::ApplePayDecrypt(_) => Err(errors::ConnectorError::NotSupported { message: "ApplePayDecrypt PayoutMethodType is not supported".to_string(), connector: "Paypal", })?, }, _ => Err(errors::ConnectorError::NotSupported { message: "PayoutMethodType is not supported".to_string(), connector: "Paypal", })?, }; Ok(Self { amount, payout_method_data, note: item.router_data.description.to_owned(), notification_language: constants::DEFAULT_NOTIFICATION_SCRIPT_LANGUAGE.to_string(), }) } } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] pub struct PaypalFulfillResponse { batch_header: PaypalBatchResponse, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] pub struct PaypalBatchResponse { pub payout_batch_id: String, pub batch_status: PaypalFulfillStatus, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] pub struct PaypalPayoutSyncResponse { batch_header: PaypalSyncBatchResponse, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] pub struct PaypalSyncBatchResponse { pub payout_batch_id: Option<String>, pub sender_batch_id: Option<String>, pub batch_status: PaypalFulfillStatus, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaypalFulfillStatus { Denied, Pending, Processing, Success, Cancelled, Failed, Refunded, Returned, } #[cfg(feature = "payouts")] pub(crate) fn get_payout_status(status: PaypalFulfillStatus) -> storage_enums::PayoutStatus { match status { PaypalFulfillStatus::Success => storage_enums::PayoutStatus::Success, PaypalFulfillStatus::Denied | PaypalFulfillStatus::Failed => { storage_enums::PayoutStatus::Failed } PaypalFulfillStatus::Cancelled => storage_enums::PayoutStatus::Cancelled, PaypalFulfillStatus::Pending | PaypalFulfillStatus::Processing => { storage_enums::PayoutStatus::Pending } PaypalFulfillStatus::Refunded | PaypalFulfillStatus::Returned => { storage_enums::PayoutStatus::Reversed } } } #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, PaypalFulfillResponse>> for PayoutsRouterData<F> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PayoutsResponseRouterData<F, PaypalFulfillResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PayoutsResponseData { status: Some(get_payout_status(item.response.batch_header.batch_status)), connector_payout_id: Some(item.response.batch_header.payout_batch_id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, PaypalPayoutSyncResponse>> for PayoutsRouterData<F> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PayoutsResponseRouterData<F, PaypalPayoutSyncResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PayoutsResponseData { status: Some(get_payout_status(item.response.batch_header.batch_status)), connector_payout_id: item.response.batch_header.payout_batch_id, payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } #[cfg(feature = "payouts")] impl TryFrom<PaypalBatchPayoutWebhooks> for PaypalPayoutSyncResponse { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(webhook_body: PaypalBatchPayoutWebhooks) -> Result<Self, Self::Error> { Ok(Self { batch_header: PaypalSyncBatchResponse { payout_batch_id: Some(webhook_body.batch_header.payout_batch_id), sender_batch_id: None, batch_status: webhook_body.batch_header.batch_status, }, }) } } #[cfg(feature = "payouts")] impl TryFrom<(PaypalItemPayoutWebhooks, PaypalWebhookEventType)> for PaypalPayoutSyncResponse { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (webhook_body, webhook_event): (PaypalItemPayoutWebhooks, PaypalWebhookEventType), ) -> Result<Self, Self::Error> { Ok(Self { batch_header: PaypalSyncBatchResponse { payout_batch_id: None, sender_batch_id: Some(webhook_body.sender_batch_id), batch_status: PaypalFulfillStatus::try_from(webhook_event) .attach_printable("Could not find suitable webhook event")?, }, }) } } #[derive(Debug, Serialize)] pub struct PaypalPaymentsCaptureRequest { amount: OrderAmount, final_capture: bool, } impl TryFrom<&PaypalRouterData<&PaymentsCaptureRouterData>> for PaypalPaymentsCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaypalRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { let amount = OrderAmount { currency_code: item.router_data.request.currency, value: item.amount.clone(), }; Ok(Self { amount, final_capture: true, }) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaypalPaymentStatus { Created, Captured, Completed, Declined, Voided, Failed, Pending, Denied, Expired, PartiallyCaptured, Refunded, } #[derive(Debug, Serialize, Deserialize)] pub struct PaypalCaptureResponse { id: String, status: PaypalPaymentStatus, amount: Option<OrderAmount>, invoice_id: Option<String>, final_capture: bool, payment_source: Option<PaymentSourceItemResponse>, } impl From<PaypalPaymentStatus> for storage_enums::AttemptStatus { fn from(item: PaypalPaymentStatus) -> Self { match item { PaypalPaymentStatus::Created => Self::Authorized, PaypalPaymentStatus::Completed | PaypalPaymentStatus::Captured | PaypalPaymentStatus::Refunded => Self::Charged, PaypalPaymentStatus::Declined => Self::Failure, PaypalPaymentStatus::Failed => Self::CaptureFailed, PaypalPaymentStatus::Pending => Self::Pending, PaypalPaymentStatus::Denied | PaypalPaymentStatus::Expired => Self::Failure, PaypalPaymentStatus::PartiallyCaptured => Self::PartialCharged, PaypalPaymentStatus::Voided => Self::Voided, } } } impl TryFrom<PaymentsCaptureResponseRouterData<PaypalCaptureResponse>> for PaymentsCaptureRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsCaptureResponseRouterData<PaypalCaptureResponse>, ) -> Result<Self, Self::Error> { let status = storage_enums::AttemptStatus::from(item.response.status); let amount_captured = match status { storage_enums::AttemptStatus::Pending | storage_enums::AttemptStatus::Authorized | storage_enums::AttemptStatus::Failure | storage_enums::AttemptStatus::RouterDeclined | storage_enums::AttemptStatus::AuthenticationFailed | storage_enums::AttemptStatus::CaptureFailed | storage_enums::AttemptStatus::Started | storage_enums::AttemptStatus::AuthenticationPending | storage_enums::AttemptStatus::AuthenticationSuccessful | storage_enums::AttemptStatus::AuthorizationFailed | storage_enums::AttemptStatus::Authorizing | storage_enums::AttemptStatus::VoidInitiated | storage_enums::AttemptStatus::CodInitiated | storage_enums::AttemptStatus::CaptureInitiated | storage_enums::AttemptStatus::VoidFailed | storage_enums::AttemptStatus::AutoRefunded | storage_enums::AttemptStatus::Unresolved | storage_enums::AttemptStatus::PaymentMethodAwaited | storage_enums::AttemptStatus::ConfirmationAwaited | storage_enums::AttemptStatus::DeviceDataCollectionPending | storage_enums::AttemptStatus::Voided | storage_enums::AttemptStatus::VoidedPostCharge | storage_enums::AttemptStatus::Expired | storage_enums::AttemptStatus::PartiallyAuthorized => 0, storage_enums::AttemptStatus::Charged | storage_enums::AttemptStatus::PartialCharged | storage_enums::AttemptStatus::PartialChargedAndChargeable | storage_enums::AttemptStatus::IntegrityFailure => item.data.request.amount_to_capture, }; let connector_payment_id: PaypalMeta = to_connector_meta(item.data.request.connector_meta.clone())?; Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.data.request.connector_transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!(PaypalMeta { authorize_id: connector_payment_id.authorize_id, capture_id: Some(item.response.id.clone()), incremental_authorization_id: None, psync_flow: PaypalPaymentIntent::Capture, next_action: None, order_id: None, })), network_txn_id: None, connector_response_reference_id: item .response .invoice_id .or(Some(item.response.id)), incremental_authorization_allowed: None, charges: None, }), amount_captured: Some(amount_captured), ..item.data }) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaypalCancelStatus { Voided, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct PaypalPaymentsCancelResponse { id: String, status: PaypalCancelStatus, amount: Option<OrderAmount>, invoice_id: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, PaypalPaymentsCancelResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaypalPaymentsCancelResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let status = match item.response.status { PaypalCancelStatus::Voided => storage_enums::AttemptStatus::Voided, }; Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item .response .invoice_id .or(Some(item.response.id)), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Default, Debug, Serialize)] pub struct PaypalRefundRequest { pub amount: OrderAmount, } impl<F> TryFrom<&PaypalRouterData<&RefundsRouterData<F>>> for PaypalRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaypalRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { amount: OrderAmount { currency_code: item.router_data.request.currency, value: item.amount.clone(), }, }) } } #[allow(dead_code)] #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "UPPERCASE")] pub enum RefundStatus { Completed, Failed, Cancelled, Pending, } impl From<RefundStatus> for storage_enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Completed => Self::Success, RefundStatus::Failed | RefundStatus::Cancelled => Self::Failure, RefundStatus::Pending => Self::Pending, } } } #[derive(Debug, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, amount: Option<OrderAmount>, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status: storage_enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct RefundSyncResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundSyncResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status: storage_enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct OrderErrorDetails { pub issue: String, pub description: String, pub value: Option<String>, pub field: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct PaypalOrderErrorResponse { pub name: Option<String>, pub message: String, pub debug_id: Option<String>, pub details: Option<Vec<OrderErrorDetails>>, } #[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct ErrorDetails { pub issue: String, pub description: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct PaypalPaymentErrorResponse { pub name: Option<String>, pub message: String, pub debug_id: Option<String>, pub details: Option<Vec<ErrorDetails>>, } #[derive(Deserialize, Debug, Serialize)] pub struct PaypalAccessTokenErrorResponse { pub error: String, pub error_description: String, } #[derive(Deserialize, Debug, Serialize)] pub struct PaypalWebhooksBody { pub event_type: PaypalWebhookEventType, pub resource: PaypalResource, } #[derive(Clone, Deserialize, Debug, strum::Display, Serialize)] pub enum PaypalWebhookEventType { #[serde(rename = "PAYMENT.AUTHORIZATION.CREATED")] PaymentAuthorizationCreated, #[serde(rename = "PAYMENT.AUTHORIZATION.VOIDED")] PaymentAuthorizationVoided, #[serde(rename = "PAYMENT.CAPTURE.DECLINED")] PaymentCaptureDeclined, #[serde(rename = "PAYMENT.CAPTURE.COMPLETED")] PaymentCaptureCompleted, #[serde(rename = "PAYMENT.CAPTURE.PENDING")] PaymentCapturePending, #[serde(rename = "PAYMENT.CAPTURE.REFUNDED")] PaymentCaptureRefunded, #[serde(rename = "CHECKOUT.ORDER.APPROVED")] CheckoutOrderApproved, #[serde(rename = "CHECKOUT.ORDER.COMPLETED")] CheckoutOrderCompleted, #[serde(rename = "CHECKOUT.ORDER.PROCESSED")] CheckoutOrderProcessed, #[serde(rename = "CUSTOMER.DISPUTE.CREATED")] CustomerDisputeCreated, #[serde(rename = "CUSTOMER.DISPUTE.RESOLVED")] CustomerDisputeResolved, #[serde(rename = "CUSTOMER.DISPUTE.UPDATED")] CustomerDisputedUpdated, #[serde(rename = "RISK.DISPUTE.CREATED")] RiskDisputeCreated, #[cfg(feature = "payouts")] #[serde(rename = "PAYMENT.PAYOUTSBATCH.SUCCESS")] PayoutsBatchSuccess, #[cfg(feature = "payouts")] #[serde(rename = "PAYMENT.PAYOUTSBATCH.PROCESSING")] PayoutsBatchProcessing, #[cfg(feature = "payouts")] #[serde(rename = "PAYMENT.PAYOUTSBATCH.DENIED")] PayoutsBatchDenied, #[cfg(feature = "payouts")] #[serde(rename = "PAYMENT.PAYOUTS-ITEM.SUCCEEDED")] PayoutsItemSuccess, #[cfg(feature = "payouts")] #[serde(rename = "PAYMENT.PAYOUTS-ITEM.FAILED")] PayoutsItemFailed, #[cfg(feature = "payouts")] #[serde(rename = "PAYMENT.PAYOUTS-ITEM.BLOCKED")] PayoutsItemBlocked, #[cfg(feature = "payouts")] #[serde(rename = "PAYMENT.PAYOUTS-ITEM.CANCELED")] PayoutsItemCanceled, #[cfg(feature = "payouts")] #[serde(rename = "PAYMENT.PAYOUTS-ITEM.DENIED")] PayoutsItemDenied, #[cfg(feature = "payouts")] #[serde(rename = "PAYMENT.PAYOUTS-ITEM.HELD")] PayoutsItemHeld, #[cfg(feature = "payouts")] #[serde(rename = "PAYMENT.PAYOUTS-ITEM.REFUNDED")] PayoutsItemRefunded, #[cfg(feature = "payouts")] #[serde(rename = "PAYMENT.PAYOUTS-ITEM.RETURNED")] PayoutsItemReturned, #[cfg(feature = "payouts")] #[serde(rename = "PAYMENT.PAYOUTS-ITEM.UNCLAIMED")] PayoutsItemUnclaimed, #[serde(other)] Unknown, } #[derive(Deserialize, Debug, Serialize)] #[serde(untagged)] pub enum PaypalResource { PaypalCardWebhooks(Box<PaypalCardWebhooks>), PaypalRedirectsWebhooks(Box<PaypalRedirectsWebhooks>), PaypalRefundWebhooks(Box<PaypalRefundWebhooks>), PaypalDisputeWebhooks(Box<PaypalDisputeWebhooks>), #[cfg(feature = "payouts")] PaypalBatchPayoutWebhooks(Box<PaypalBatchPayoutWebhooks>), #[cfg(feature = "payouts")] PaypalItemPayoutWebhooks(Box<PaypalItemPayoutWebhooks>), } #[cfg(feature = "payouts")] #[derive(Deserialize, Debug, Serialize)] pub struct PaypalBatchPayoutWebhooks { pub batch_header: PaypalBatchResponse, } #[cfg(feature = "payouts")] #[derive(Deserialize, Debug, Serialize)] pub struct PaypalItemPayoutWebhooks { pub sender_batch_id: String, pub transaction_status: PaypalFulfillStatus, } #[derive(Deserialize, Debug, Serialize)] pub struct PaypalDisputeWebhooks { pub dispute_id: String, pub disputed_transactions: Vec<DisputeTransaction>, pub dispute_amount: OrderAmount, pub dispute_outcome: Option<DisputeOutcome>, pub dispute_life_cycle_stage: DisputeLifeCycleStage, pub status: DisputeStatus, pub reason: Option<String>, pub external_reason_code: Option<String>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub seller_response_due_date: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub update_time: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub create_time: Option<PrimitiveDateTime>, } #[derive(Deserialize, Debug, Serialize)] pub struct DisputeTransaction { pub seller_transaction_id: String, } #[derive(Clone, Deserialize, Debug, strum::Display, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum DisputeLifeCycleStage { Inquiry, Chargeback, PreArbitration, Arbitration, } #[derive(Deserialize, Debug, strum::Display, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum DisputeStatus { Open, WaitingForBuyerResponse, WaitingForSellerResponse, UnderReview, Resolved, Other, } #[derive(Deserialize, Debug, Serialize)] pub struct DisputeOutcome { pub outcome_code: OutcomeCode, } #[derive(Deserialize, Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum OutcomeCode { ResolvedBuyerFavour, ResolvedSellerFavour, ResolvedWithPayout, CanceledByBuyer, ACCEPTED, DENIED, NONE, } #[derive(Deserialize, Debug, Serialize)] pub struct PaypalRefundWebhooks { pub id: String, pub amount: OrderAmount, pub seller_payable_breakdown: PaypalSellerPayableBreakdown, } #[derive(Deserialize, Debug, Serialize)] pub struct PaypalSellerPayableBreakdown { pub total_refunded_amount: OrderAmount, } #[derive(Deserialize, Debug, Serialize)] pub struct PaypalCardWebhooks { pub supplementary_data: PaypalSupplementaryData, pub amount: OrderAmount, pub invoice_id: Option<String>, } #[derive(Deserialize, Debug, Serialize)] pub struct PaypalRedirectsWebhooks { pub purchase_units: Vec<PurchaseUnitItem>, pub links: Vec<PaypalLinks>, pub id: String, pub intent: PaypalPaymentIntent, } #[derive(Deserialize, Debug, Serialize)] pub struct PaypalWebhooksPurchaseUnits { pub reference_id: String, pub amount: OrderAmount, } #[derive(Deserialize, Debug, Serialize)] pub struct PaypalSupplementaryData { pub related_ids: PaypalRelatedIds, } #[derive(Deserialize, Debug, Serialize)] pub struct PaypalRelatedIds { pub order_id: String, } #[derive(Deserialize, Debug, Serialize)] pub struct PaypalWebooksEventType { pub event_type: PaypalWebhookEventType, } pub(crate) fn get_payapl_webhooks_event( event: PaypalWebhookEventType, outcome: Option<OutcomeCode>, ) -> IncomingWebhookEvent { match event { PaypalWebhookEventType::PaymentCaptureCompleted | PaypalWebhookEventType::CheckoutOrderCompleted => { IncomingWebhookEvent::PaymentIntentSuccess } PaypalWebhookEventType::PaymentCapturePending | PaypalWebhookEventType::CheckoutOrderProcessed => { IncomingWebhookEvent::PaymentIntentProcessing } PaypalWebhookEventType::PaymentCaptureDeclined => { IncomingWebhookEvent::PaymentIntentFailure } PaypalWebhookEventType::PaymentCaptureRefunded => IncomingWebhookEvent::RefundSuccess, PaypalWebhookEventType::CustomerDisputeCreated => IncomingWebhookEvent::DisputeOpened, PaypalWebhookEventType::RiskDisputeCreated => IncomingWebhookEvent::DisputeAccepted, PaypalWebhookEventType::CustomerDisputeResolved => { if let Some(outcome_code) = outcome { IncomingWebhookEvent::from(outcome_code) } else { IncomingWebhookEvent::EventNotSupported } } PaypalWebhookEventType::PaymentAuthorizationCreated | PaypalWebhookEventType::PaymentAuthorizationVoided | PaypalWebhookEventType::CheckoutOrderApproved | PaypalWebhookEventType::CustomerDisputedUpdated | PaypalWebhookEventType::Unknown => IncomingWebhookEvent::EventNotSupported, #[cfg(feature = "payouts")] PaypalWebhookEventType::PayoutsBatchSuccess | PaypalWebhookEventType::PayoutsItemSuccess => IncomingWebhookEvent::PayoutSuccess, #[cfg(feature = "payouts")] PaypalWebhookEventType::PayoutsBatchProcessing | PaypalWebhookEventType::PayoutsItemHeld | PaypalWebhookEventType::PayoutsItemUnclaimed => IncomingWebhookEvent::PayoutProcessing, #[cfg(feature = "payouts")] PaypalWebhookEventType::PayoutsBatchDenied | PaypalWebhookEventType::PayoutsItemDenied | PaypalWebhookEventType::PayoutsItemBlocked | PaypalWebhookEventType::PayoutsItemCanceled => IncomingWebhookEvent::PayoutCancelled, #[cfg(feature = "payouts")] PaypalWebhookEventType::PayoutsItemFailed => IncomingWebhookEvent::PayoutFailure, #[cfg(feature = "payouts")] PaypalWebhookEventType::PayoutsItemRefunded | PaypalWebhookEventType::PayoutsItemReturned => IncomingWebhookEvent::PayoutReversed, } } impl From<OutcomeCode> for IncomingWebhookEvent { fn from(outcome_code: OutcomeCode) -> Self { match outcome_code { OutcomeCode::ResolvedBuyerFavour => Self::DisputeLost, OutcomeCode::ResolvedSellerFavour => Self::DisputeWon, OutcomeCode::CanceledByBuyer => Self::DisputeCancelled, OutcomeCode::ACCEPTED => Self::DisputeAccepted, OutcomeCode::DENIED => Self::DisputeCancelled, OutcomeCode::NONE => Self::DisputeCancelled, OutcomeCode::ResolvedWithPayout => Self::EventNotSupported, } } } impl From<DisputeLifeCycleStage> for enums::DisputeStage { fn from(dispute_life_cycle_stage: DisputeLifeCycleStage) -> Self { match dispute_life_cycle_stage { DisputeLifeCycleStage::Inquiry => Self::PreDispute, DisputeLifeCycleStage::Chargeback => Self::Dispute, DisputeLifeCycleStage::PreArbitration => Self::PreArbitration, DisputeLifeCycleStage::Arbitration => Self::PreArbitration, } } } #[derive(Deserialize, Serialize, Debug)] pub struct PaypalSourceVerificationRequest { pub transmission_id: String, pub transmission_time: String, pub cert_url: String, pub transmission_sig: String, pub auth_algo: String, pub webhook_id: String, pub webhook_event: serde_json::Value, } #[derive(Deserialize, Serialize, Debug)] pub struct PaypalSourceVerificationResponse { pub verification_status: PaypalSourceVerificationStatus, } #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaypalSourceVerificationStatus { Success, Failure, } impl TryFrom< ResponseRouterData< VerifyWebhookSource, PaypalSourceVerificationResponse, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >, > for VerifyWebhookSourceRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< VerifyWebhookSource, PaypalSourceVerificationResponse, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(VerifyWebhookSourceResponseData { verify_webhook_status: VerifyWebhookStatus::from(item.response.verification_status), }), ..item.data }) } } impl From<PaypalSourceVerificationStatus> for VerifyWebhookStatus { fn from(item: PaypalSourceVerificationStatus) -> Self { match item { PaypalSourceVerificationStatus::Success => Self::SourceVerified, PaypalSourceVerificationStatus::Failure => Self::SourceNotVerified, } } } impl TryFrom<(PaypalCardWebhooks, PaypalWebhookEventType)> for PaypalPaymentsSyncResponse { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (webhook_body, webhook_event): (PaypalCardWebhooks, PaypalWebhookEventType), ) -> Result<Self, Self::Error> { Ok(Self { id: webhook_body.supplementary_data.related_ids.order_id.clone(), status: PaypalPaymentStatus::try_from(webhook_event)?, amount: webhook_body.amount, supplementary_data: webhook_body.supplementary_data, invoice_id: webhook_body.invoice_id, }) } } impl TryFrom<(PaypalRedirectsWebhooks, PaypalWebhookEventType)> for PaypalOrdersResponse { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (webhook_body, webhook_event): (PaypalRedirectsWebhooks, PaypalWebhookEventType), ) -> Result<Self, Self::Error> { Ok(Self { id: webhook_body.id, intent: webhook_body.intent, status: PaypalOrderStatus::try_from(webhook_event)?, purchase_units: webhook_body.purchase_units, payment_source: None, }) } } impl TryFrom<(PaypalRefundWebhooks, PaypalWebhookEventType)> for RefundSyncResponse { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (webhook_body, webhook_event): (PaypalRefundWebhooks, PaypalWebhookEventType), ) -> Result<Self, Self::Error> { Ok(Self { id: webhook_body.id, status: RefundStatus::try_from(webhook_event) .attach_printable("Could not find suitable webhook event")?, }) } } impl TryFrom<PaypalWebhookEventType> for PaypalPaymentStatus { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(event: PaypalWebhookEventType) -> Result<Self, Self::Error> { match event { PaypalWebhookEventType::PaymentCaptureCompleted | PaypalWebhookEventType::CheckoutOrderCompleted => Ok(Self::Completed), PaypalWebhookEventType::PaymentAuthorizationVoided => Ok(Self::Voided), PaypalWebhookEventType::PaymentCaptureDeclined => Ok(Self::Declined), PaypalWebhookEventType::PaymentCapturePending | PaypalWebhookEventType::CheckoutOrderApproved | PaypalWebhookEventType::CheckoutOrderProcessed => Ok(Self::Pending), PaypalWebhookEventType::PaymentAuthorizationCreated => Ok(Self::Created), PaypalWebhookEventType::PaymentCaptureRefunded => Ok(Self::Refunded), PaypalWebhookEventType::CustomerDisputeCreated | PaypalWebhookEventType::CustomerDisputeResolved | PaypalWebhookEventType::CustomerDisputedUpdated | PaypalWebhookEventType::RiskDisputeCreated | PaypalWebhookEventType::Unknown => { Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) } #[cfg(feature = "payouts")] PaypalWebhookEventType::PayoutsBatchDenied | PaypalWebhookEventType::PayoutsBatchProcessing | PaypalWebhookEventType::PayoutsBatchSuccess | PaypalWebhookEventType::PayoutsItemBlocked | PaypalWebhookEventType::PayoutsItemCanceled | PaypalWebhookEventType::PayoutsItemDenied | PaypalWebhookEventType::PayoutsItemFailed | PaypalWebhookEventType::PayoutsItemHeld | PaypalWebhookEventType::PayoutsItemRefunded | PaypalWebhookEventType::PayoutsItemReturned | PaypalWebhookEventType::PayoutsItemSuccess | PaypalWebhookEventType::PayoutsItemUnclaimed => { Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) } } } } impl TryFrom<PaypalWebhookEventType> for RefundStatus { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(event: PaypalWebhookEventType) -> Result<Self, Self::Error> { match event { PaypalWebhookEventType::PaymentCaptureRefunded => Ok(Self::Completed), PaypalWebhookEventType::PaymentAuthorizationCreated | PaypalWebhookEventType::PaymentAuthorizationVoided | PaypalWebhookEventType::PaymentCaptureDeclined | PaypalWebhookEventType::PaymentCaptureCompleted | PaypalWebhookEventType::PaymentCapturePending | PaypalWebhookEventType::CheckoutOrderApproved | PaypalWebhookEventType::CheckoutOrderCompleted | PaypalWebhookEventType::CheckoutOrderProcessed | PaypalWebhookEventType::CustomerDisputeCreated | PaypalWebhookEventType::CustomerDisputeResolved | PaypalWebhookEventType::CustomerDisputedUpdated | PaypalWebhookEventType::RiskDisputeCreated | PaypalWebhookEventType::Unknown => { Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) } #[cfg(feature = "payouts")] PaypalWebhookEventType::PayoutsBatchDenied | PaypalWebhookEventType::PayoutsBatchProcessing | PaypalWebhookEventType::PayoutsBatchSuccess | PaypalWebhookEventType::PayoutsItemBlocked | PaypalWebhookEventType::PayoutsItemCanceled | PaypalWebhookEventType::PayoutsItemDenied | PaypalWebhookEventType::PayoutsItemFailed | PaypalWebhookEventType::PayoutsItemHeld | PaypalWebhookEventType::PayoutsItemRefunded | PaypalWebhookEventType::PayoutsItemReturned | PaypalWebhookEventType::PayoutsItemSuccess | PaypalWebhookEventType::PayoutsItemUnclaimed => { Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) } } } } #[cfg(feature = "payouts")] impl TryFrom<PaypalWebhookEventType> for PaypalFulfillStatus { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(event: PaypalWebhookEventType) -> Result<Self, Self::Error> { match event { PaypalWebhookEventType::PayoutsBatchSuccess | PaypalWebhookEventType::PayoutsItemSuccess => Ok(Self::Success), PaypalWebhookEventType::PayoutsBatchProcessing => Ok(Self::Processing), PaypalWebhookEventType::PayoutsItemHeld | PaypalWebhookEventType::PayoutsItemUnclaimed => Ok(Self::Pending), PaypalWebhookEventType::PayoutsItemBlocked | PaypalWebhookEventType::PayoutsItemCanceled => Ok(Self::Cancelled), PaypalWebhookEventType::PayoutsBatchDenied | PaypalWebhookEventType::PayoutsItemDenied => Ok(Self::Denied), PaypalWebhookEventType::PayoutsItemFailed => Ok(Self::Failed), PaypalWebhookEventType::PayoutsItemRefunded => Ok(Self::Refunded), PaypalWebhookEventType::PayoutsItemReturned => Ok(Self::Returned), PaypalWebhookEventType::PaymentCaptureRefunded | PaypalWebhookEventType::PaymentAuthorizationCreated | PaypalWebhookEventType::PaymentAuthorizationVoided | PaypalWebhookEventType::PaymentCaptureDeclined | PaypalWebhookEventType::PaymentCaptureCompleted | PaypalWebhookEventType::PaymentCapturePending | PaypalWebhookEventType::CheckoutOrderApproved | PaypalWebhookEventType::CheckoutOrderCompleted | PaypalWebhookEventType::CheckoutOrderProcessed | PaypalWebhookEventType::CustomerDisputeCreated | PaypalWebhookEventType::CustomerDisputeResolved | PaypalWebhookEventType::CustomerDisputedUpdated | PaypalWebhookEventType::RiskDisputeCreated | PaypalWebhookEventType::Unknown => { Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) } } } } impl TryFrom<PaypalWebhookEventType> for PaypalOrderStatus { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(event: PaypalWebhookEventType) -> Result<Self, Self::Error> { match event { PaypalWebhookEventType::PaymentCaptureCompleted | PaypalWebhookEventType::CheckoutOrderCompleted => Ok(Self::Completed), PaypalWebhookEventType::PaymentAuthorizationVoided => Ok(Self::Voided), PaypalWebhookEventType::PaymentCapturePending | PaypalWebhookEventType::CheckoutOrderProcessed => Ok(Self::Pending), PaypalWebhookEventType::PaymentAuthorizationCreated => Ok(Self::Created), PaypalWebhookEventType::CheckoutOrderApproved | PaypalWebhookEventType::PaymentCaptureDeclined | PaypalWebhookEventType::PaymentCaptureRefunded | PaypalWebhookEventType::CustomerDisputeCreated | PaypalWebhookEventType::CustomerDisputeResolved | PaypalWebhookEventType::CustomerDisputedUpdated | PaypalWebhookEventType::RiskDisputeCreated | PaypalWebhookEventType::Unknown => { Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) } #[cfg(feature = "payouts")] PaypalWebhookEventType::PayoutsBatchDenied | PaypalWebhookEventType::PayoutsBatchProcessing | PaypalWebhookEventType::PayoutsBatchSuccess | PaypalWebhookEventType::PayoutsItemBlocked | PaypalWebhookEventType::PayoutsItemCanceled | PaypalWebhookEventType::PayoutsItemDenied | PaypalWebhookEventType::PayoutsItemFailed | PaypalWebhookEventType::PayoutsItemHeld | PaypalWebhookEventType::PayoutsItemRefunded | PaypalWebhookEventType::PayoutsItemReturned | PaypalWebhookEventType::PayoutsItemSuccess | PaypalWebhookEventType::PayoutsItemUnclaimed => { Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) } } } } impl TryFrom<&VerifyWebhookSourceRequestData> for PaypalSourceVerificationRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(req: &VerifyWebhookSourceRequestData) -> Result<Self, Self::Error> { let req_body = serde_json::from_slice(&req.webhook_body) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(Self { transmission_id: get_headers( &req.webhook_headers, webhook_headers::PAYPAL_TRANSMISSION_ID, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?, transmission_time: get_headers( &req.webhook_headers, webhook_headers::PAYPAL_TRANSMISSION_TIME, )?, cert_url: get_headers(&req.webhook_headers, webhook_headers::PAYPAL_CERT_URL)?, transmission_sig: get_headers( &req.webhook_headers, webhook_headers::PAYPAL_TRANSMISSION_SIG, )?, auth_algo: get_headers(&req.webhook_headers, webhook_headers::PAYPAL_AUTH_ALGO)?, webhook_id: String::from_utf8(req.merchant_secret.secret.to_vec()) .change_context(errors::ConnectorError::WebhookVerificationSecretNotFound) .attach_printable("Could not convert secret to UTF-8")?, webhook_event: req_body, }) } } fn get_headers( header: &actix_web::http::header::HeaderMap, key: &'static str, ) -> CustomResult<String, errors::ConnectorError> { let header_value = header .get(key) .map(|value| value.to_str()) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: key })? .change_context(errors::ConnectorError::InvalidDataFormat { field_name: key })? .to_owned(); Ok(header_value) } impl From<OrderErrorDetails> for utils::ErrorCodeAndMessage { fn from(error: OrderErrorDetails) -> Self { Self { error_code: error.issue.to_string(), error_message: error.issue.to_string(), } } } impl From<ErrorDetails> for utils::ErrorCodeAndMessage { fn from(error: ErrorDetails) -> Self { Self { error_code: error.issue.to_string(), error_message: error.issue.to_string(), } } }
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
hyperswitch_connectors::src::connectors::paypal::transformers
28,484
true
// File: crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs // Module: hyperswitch_connectors::src::connectors::tokenex::transformers use common_utils::types::StringMinorUnit; use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ExternalVaultInsertFlow, ExternalVaultRetrieveFlow}, router_request_types::VaultRequestData, router_response_types::VaultResponseData, types::VaultRouterData, vault::PaymentMethodVaultingData, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::types::ResponseRouterData; pub struct TokenexRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for TokenexRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Default, Debug, Serialize, PartialEq)] pub struct TokenexInsertRequest { data: cards::CardNumber, //Currently only card number is tokenized. Data can be stringified and can be tokenized } impl<F> TryFrom<&VaultRouterData<F>> for TokenexInsertRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &VaultRouterData<F>) -> Result<Self, Self::Error> { match item.request.payment_method_vaulting_data.clone() { Some(PaymentMethodVaultingData::Card(req_card)) => Ok(Self { data: req_card.card_number.clone(), }), _ => Err(errors::ConnectorError::NotImplemented( "Payment method apart from card".to_string(), ) .into()), } } } pub struct TokenexAuthType { pub(super) api_key: Secret<String>, pub(super) tokenex_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for TokenexAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.to_owned(), tokenex_id: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct TokenexInsertResponse { token: Option<String>, first_six: Option<String>, last_four: Option<String>, success: bool, error: String, message: Option<String>, } impl TryFrom< ResponseRouterData< ExternalVaultInsertFlow, TokenexInsertResponse, VaultRequestData, VaultResponseData, >, > for RouterData<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< ExternalVaultInsertFlow, TokenexInsertResponse, VaultRequestData, VaultResponseData, >, ) -> Result<Self, Self::Error> { let resp = item.response; match resp.success && resp.error.is_empty() { true => { let token = resp .token .clone() .ok_or(errors::ConnectorError::ResponseDeserializationFailed) .attach_printable("Token is missing in tokenex response")?; Ok(Self { status: common_enums::AttemptStatus::Started, response: Ok(VaultResponseData::ExternalVaultInsertResponse { connector_vault_id: token.clone(), //fingerprint is not provided by tokenex, using token as fingerprint fingerprint_id: token.clone(), }), ..item.data }) } false => { let (code, message) = resp.error.split_once(':').unwrap_or(("", "")); let response = Err(ErrorResponse { code: code.to_string(), message: message.to_string(), reason: resp.message, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }); Ok(Self { response, ..item.data }) } } } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct TokenexRetrieveRequest { token: Secret<String>, //Currently only card number is tokenized. Data can be stringified and can be tokenized cache_cvv: bool, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct TokenexRetrieveResponse { value: Option<cards::CardNumber>, success: bool, error: String, message: Option<String>, } impl<F> TryFrom<&VaultRouterData<F>> for TokenexRetrieveRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &VaultRouterData<F>) -> Result<Self, Self::Error> { let connector_vault_id = item.request.connector_vault_id.as_ref().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "connector_vault_id", }, )?; Ok(Self { token: Secret::new(connector_vault_id.clone()), cache_cvv: false, //since cvv is not stored at tokenex }) } } impl TryFrom< ResponseRouterData< ExternalVaultRetrieveFlow, TokenexRetrieveResponse, VaultRequestData, VaultResponseData, >, > for RouterData<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< ExternalVaultRetrieveFlow, TokenexRetrieveResponse, VaultRequestData, VaultResponseData, >, ) -> Result<Self, Self::Error> { let resp = item.response; match resp.success && resp.error.is_empty() { true => { let data = resp .value .clone() .ok_or(errors::ConnectorError::ResponseDeserializationFailed) .attach_printable("Card number is missing in tokenex response")?; Ok(Self { status: common_enums::AttemptStatus::Started, response: Ok(VaultResponseData::ExternalVaultRetrieveResponse { vault_data: PaymentMethodVaultingData::CardNumber(data), }), ..item.data }) } false => { let (code, message) = resp.error.split_once(':').unwrap_or(("", "")); let response = Err(ErrorResponse { code: code.to_string(), message: message.to_string(), reason: resp.message, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }); Ok(Self { response, ..item.data }) } } } } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct TokenexErrorResponse { pub error: String, pub message: String, }
crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs
hyperswitch_connectors::src::connectors::tokenex::transformers
1,666
true
// File: crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs // Module: hyperswitch_connectors::src::connectors::mollie::transformers use cards::CardNumber; use common_enums::enums; use common_utils::{pii::Email, request::Method, types::StringMajorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankDebitData, BankRedirectData, PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, PaymentMethodToken, RouterData}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, utils::{ AddressDetailsData, BrowserInformationData, CardData as CardDataUtil, PaymentMethodTokenizationRequestData, PaymentsAuthorizeRequestData, RouterData as _, }, }; type Error = error_stack::Report<errors::ConnectorError>; #[derive(Debug, Serialize)] pub struct MollieRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for MollieRouterData<T> { fn from((amount, router_data): (StringMajorUnit, T)) -> Self { Self { amount, router_data, } } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MolliePaymentsRequest { amount: Amount, description: String, redirect_url: String, cancel_url: Option<String>, webhook_url: String, locale: Option<String>, #[serde(flatten)] payment_method_data: MolliePaymentMethodData, metadata: Option<MollieMetadata>, sequence_type: SequenceType, mandate_id: Option<Secret<String>>, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct Amount { currency: enums::Currency, value: StringMajorUnit, } #[derive(Debug, Serialize)] #[serde(tag = "method")] #[serde(rename_all = "lowercase")] pub enum MolliePaymentMethodData { Applepay(Box<ApplePayMethodData>), Eps, Giropay, Ideal(Box<IdealMethodData>), Paypal(Box<PaypalMethodData>), Sofort, Przelewy24(Box<Przelewy24MethodData>), Bancontact, CreditCard(Box<CreditCardMethodData>), DirectDebit(Box<DirectDebitMethodData>), } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayMethodData { apple_pay_payment_token: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct IdealMethodData { issuer: Option<Secret<String>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaypalMethodData { billing_address: Option<Address>, shipping_address: Option<Address>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Przelewy24MethodData { billing_email: Option<Email>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct DirectDebitMethodData { consumer_name: Option<Secret<String>>, consumer_account: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CreditCardMethodData { billing_address: Option<Address>, shipping_address: Option<Address>, card_token: Option<Secret<String>>, } #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SequenceType { #[default] Oneoff, First, Recurring, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Address { pub street_and_number: Secret<String>, pub postal_code: Secret<String>, pub city: String, pub region: Option<Secret<String>>, pub country: api_models::enums::CountryAlpha2, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MollieMetadata { pub order_id: String, } impl TryFrom<&MollieRouterData<&types::PaymentsAuthorizeRouterData>> for MolliePaymentsRequest { type Error = Error; fn try_from( item: &MollieRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let amount = Amount { currency: item.router_data.request.currency, value: item.amount.clone(), }; let description = item.router_data.get_description()?; let redirect_url = item.router_data.request.get_router_return_url()?; let payment_method_data = match item.router_data.request.capture_method.unwrap_or_default() { enums::CaptureMethod::Automatic | enums::CaptureMethod::SequentialAutomatic => { match &item.router_data.request.payment_method_data { PaymentMethodData::Card(_) => { let pm_token = item.router_data.get_payment_method_token()?; Ok(MolliePaymentMethodData::CreditCard(Box::new( CreditCardMethodData { billing_address: get_billing_details(item.router_data)?, shipping_address: get_shipping_details(item.router_data)?, card_token: Some(match pm_token { PaymentMethodToken::Token(token) => token, PaymentMethodToken::ApplePayDecrypt(_) => { Err(unimplemented_payment_method!( "Apple Pay", "Simplified", "Mollie" ))? } PaymentMethodToken::PazeDecrypt(_) => { Err(unimplemented_payment_method!("Paze", "Mollie"))? } PaymentMethodToken::GooglePayDecrypt(_) => { Err(unimplemented_payment_method!("Google Pay", "Mollie"))? } }), }, ))) } PaymentMethodData::BankRedirect(ref redirect_data) => { MolliePaymentMethodData::try_from((item.router_data, redirect_data)) } PaymentMethodData::Wallet(ref wallet_data) => { get_payment_method_for_wallet(item.router_data, wallet_data) } PaymentMethodData::BankDebit(ref directdebit_data) => { MolliePaymentMethodData::try_from((directdebit_data, item.router_data)) } _ => Err( errors::ConnectorError::NotImplemented("Payment Method".to_string()).into(), ), } } _ => Err(errors::ConnectorError::FlowNotSupported { flow: format!( "{} capture", item.router_data.request.capture_method.unwrap_or_default() ), connector: "Mollie".to_string(), } .into()), }?; Ok(Self { amount, description, redirect_url, cancel_url: None, /* webhook_url is a mandatory field. But we can't support webhook in our core hence keeping it as empty string */ webhook_url: "".to_string(), locale: None, payment_method_data, metadata: Some(MollieMetadata { order_id: item.router_data.connector_request_reference_id.clone(), }), sequence_type: SequenceType::Oneoff, mandate_id: None, }) } } impl TryFrom<(&types::PaymentsAuthorizeRouterData, &BankRedirectData)> for MolliePaymentMethodData { type Error = Error; fn try_from( (item, value): (&types::PaymentsAuthorizeRouterData, &BankRedirectData), ) -> Result<Self, Self::Error> { match value { BankRedirectData::Eps { .. } => Ok(Self::Eps), BankRedirectData::Giropay { .. } => Ok(Self::Giropay), BankRedirectData::Ideal { .. } => { Ok(Self::Ideal(Box::new(IdealMethodData { // To do if possible this should be from the payment request issuer: None, }))) } BankRedirectData::Sofort { .. } => Ok(Self::Sofort), BankRedirectData::Przelewy24 { .. } => { Ok(Self::Przelewy24(Box::new(Przelewy24MethodData { billing_email: item.get_optional_billing_email(), }))) } BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact), _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } impl TryFrom<(&BankDebitData, &types::PaymentsAuthorizeRouterData)> for MolliePaymentMethodData { type Error = Error; fn try_from( (bank_debit_data, item): (&BankDebitData, &types::PaymentsAuthorizeRouterData), ) -> Result<Self, Self::Error> { match bank_debit_data { BankDebitData::SepaBankDebit { iban, .. } => { Ok(Self::DirectDebit(Box::new(DirectDebitMethodData { consumer_name: item.get_optional_billing_full_name(), consumer_account: iban.clone(), }))) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MollieCardTokenRequest { card_holder: Secret<String>, card_number: CardNumber, card_cvv: Secret<String>, card_expiry_date: Secret<String>, locale: String, testmode: bool, profile_token: Secret<String>, } impl TryFrom<&types::TokenizationRouterData> for MollieCardTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => { let auth = MollieAuthType::try_from(&item.connector_auth_type)?; let card_holder = item .get_optional_billing_full_name() .unwrap_or(Secret::new("".to_string())); let card_number = ccard.card_number.clone(); let card_expiry_date = ccard.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?; let card_cvv = ccard.card_cvc; let locale = item.request.get_browser_info()?.get_language()?; let testmode = item.test_mode .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "test_mode", })?; let profile_token = auth .profile_token .ok_or(errors::ConnectorError::FailedToObtainAuthType)?; Ok(Self { card_holder, card_number, card_cvv, card_expiry_date, locale, testmode, profile_token, }) } _ => Err(errors::ConnectorError::NotImplemented( "Payment Method".to_string(), ))?, } } } fn get_payment_method_for_wallet( item: &types::PaymentsAuthorizeRouterData, wallet_data: &WalletData, ) -> Result<MolliePaymentMethodData, Error> { match wallet_data { WalletData::PaypalRedirect { .. } => Ok(MolliePaymentMethodData::Paypal(Box::new( PaypalMethodData { billing_address: get_billing_details(item)?, shipping_address: get_shipping_details(item)?, }, ))), WalletData::ApplePay(applepay_wallet_data) => { let apple_pay_encrypted_data = applepay_wallet_data .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", })?; Ok(MolliePaymentMethodData::Applepay(Box::new( ApplePayMethodData { apple_pay_payment_token: Secret::new(apple_pay_encrypted_data.to_owned()), }, ))) } _ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()), } } fn get_shipping_details( item: &types::PaymentsAuthorizeRouterData, ) -> Result<Option<Address>, Error> { let shipping_address = item .get_optional_shipping() .and_then(|shipping| shipping.address.as_ref()); get_address_details(shipping_address) } fn get_billing_details( item: &types::PaymentsAuthorizeRouterData, ) -> Result<Option<Address>, Error> { let billing_address = item .get_optional_billing() .and_then(|billing| billing.address.as_ref()); get_address_details(billing_address) } fn get_address_details( address: Option<&hyperswitch_domain_models::address::AddressDetails>, ) -> Result<Option<Address>, Error> { let address_details = match address { Some(address) => { let street_and_number = address.get_combined_address_line()?; let postal_code = address.get_zip()?.to_owned(); let city = address.get_city()?.to_owned(); let region = None; let country = address.get_country()?.to_owned(); Some(Address { street_and_number, postal_code, city, region, country, }) } None => None, }; Ok(address_details) } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct MolliePaymentsResponse { pub resource: String, pub id: String, pub amount: Amount, pub description: Option<String>, pub metadata: Option<MollieMetadata>, pub status: MolliePaymentStatus, pub is_cancelable: Option<bool>, pub sequence_type: SequenceType, pub redirect_url: Option<String>, pub webhook_url: Option<String>, #[serde(rename = "_links")] pub links: Links, } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum MolliePaymentStatus { Open, Canceled, #[default] Pending, Authorized, Expired, Failed, Paid, } impl From<MolliePaymentStatus> for enums::AttemptStatus { fn from(item: MolliePaymentStatus) -> Self { match item { MolliePaymentStatus::Paid => Self::Charged, MolliePaymentStatus::Failed => Self::Failure, MolliePaymentStatus::Pending => Self::Pending, MolliePaymentStatus::Open => Self::AuthenticationPending, MolliePaymentStatus::Canceled => Self::Voided, MolliePaymentStatus::Authorized => Self::Authorized, MolliePaymentStatus::Expired => Self::Failure, } } } #[derive(Debug, Serialize, Deserialize)] pub struct Link { href: Url, #[serde(rename = "type")] type_: String, } #[derive(Debug, Serialize, Deserialize)] pub struct Links { #[serde(rename = "self")] self_: Option<Link>, checkout: Option<Link>, dashboard: Option<Link>, documentation: Option<Link>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardDetails { pub card_number: Secret<String>, pub card_holder: Secret<String>, pub card_expiry_date: Secret<String>, pub card_cvv: Secret<String>, } pub struct MollieAuthType { pub(super) api_key: Secret<String>, pub(super) profile_token: Option<Secret<String>>, } impl TryFrom<&ConnectorAuthType> for MollieAuthType { type Error = Error; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), profile_token: None, }), ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.to_owned(), profile_token: Some(key1.to_owned()), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MollieCardTokenResponse { card_token: Secret<String>, } impl<F, T> TryFrom<ResponseRouterData<F, MollieCardTokenResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, MollieCardTokenResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::Pending, payment_method_token: Some(PaymentMethodToken::Token(item.response.card_token.clone())), response: Ok(PaymentsResponseData::TokenizationResponse { token: item.response.card_token.expose(), }), ..item.data }) } } impl<F, T> TryFrom<ResponseRouterData<F, MolliePaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = Error; fn try_from( item: ResponseRouterData<F, MolliePaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let url = item .response .links .checkout .map(|link| RedirectForm::from((link.href, Method::Get))); Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(url), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } // REFUND : #[derive(Default, Debug, Serialize)] pub struct MollieRefundRequest { amount: Amount, description: Option<String>, metadata: Option<MollieMetadata>, } impl<F> TryFrom<&MollieRouterData<&types::RefundsRouterData<F>>> for MollieRefundRequest { type Error = Error; fn try_from( item: &MollieRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { let amount = Amount { currency: item.router_data.request.currency, value: item.amount.clone(), }; Ok(Self { amount, description: item.router_data.request.reason.to_owned(), metadata: Some(MollieMetadata { order_id: item.router_data.request.refund_id.clone(), }), }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RefundResponse { resource: String, id: String, amount: Amount, settlement_id: Option<String>, settlement_amount: Option<Amount>, status: MollieRefundStatus, description: Option<String>, metadata: Option<MollieMetadata>, payment_id: String, #[serde(rename = "_links")] links: Links, } #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum MollieRefundStatus { Queued, #[default] Pending, Processing, Refunded, Failed, Canceled, } impl From<MollieRefundStatus> for enums::RefundStatus { fn from(item: MollieRefundStatus) -> Self { match item { MollieRefundStatus::Queued | MollieRefundStatus::Pending | MollieRefundStatus::Processing => Self::Pending, MollieRefundStatus::Refunded => Self::Success, MollieRefundStatus::Failed | MollieRefundStatus::Canceled => Self::Failure, } } } impl<T> TryFrom<RefundsResponseRouterData<T, RefundResponse>> for types::RefundsRouterData<T> { type Error = Error; fn try_from(item: RefundsResponseRouterData<T, RefundResponse>) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] pub struct MollieErrorResponse { pub status: u16, pub title: Option<String>, pub detail: String, pub field: Option<String>, }
crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
hyperswitch_connectors::src::connectors::mollie::transformers
4,526
true
// File: crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers.rs // Module: hyperswitch_connectors::src::connectors::adyenplatform::transformers use common_utils::types::MinorUnit; use error_stack::Report; use hyperswitch_domain_models::router_data::ConnectorAuthType; use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::Serialize; #[cfg(feature = "payouts")] pub mod payouts; #[cfg(feature = "payouts")] pub use payouts::*; // Error signature type Error = Report<ConnectorError>; // Auth Struct pub struct AdyenplatformAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for AdyenplatformAuthType { type Error = Error; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Serialize)] pub struct AdyenPlatformRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> TryFrom<(MinorUnit, T)> for AdyenPlatformRouterData<T> { type Error = Report<ConnectorError>; fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } }
crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers.rs
hyperswitch_connectors::src::connectors::adyenplatform::transformers
347
true
// File: crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs // Module: hyperswitch_connectors::src::connectors::adyenplatform::transformers::payouts use api_models::{payouts, webhooks}; use common_enums::enums; use common_utils::pii; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::types::{self, PayoutsRouterData}; use hyperswitch_interfaces::errors::ConnectorError; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use super::{AdyenPlatformRouterData, Error}; use crate::{ connectors::adyen::transformers as adyen, types::PayoutsResponseRouterData, utils::{ self, AddressDetailsData, CardData, PayoutFulfillRequestData, PayoutsData as _, RouterData as _, }, }; #[derive(Debug, Default, Serialize, Deserialize)] pub struct AdyenPlatformConnectorMetadataObject { source_balance_account: Option<Secret<String>>, } impl TryFrom<&Option<pii::SecretSerdeValue>> for AdyenPlatformConnectorMetadataObject { type Error = Error; fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) .change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?; Ok(metadata) } } #[serde_with::skip_serializing_none] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdyenTransferRequest { amount: adyen::Amount, balance_account_id: Secret<String>, category: AdyenPayoutMethod, counterparty: AdyenPayoutMethodDetails, priority: Option<AdyenPayoutPriority>, reference: String, reference_for_beneficiary: String, description: Option<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum AdyenPayoutMethod { Bank, Card, PlatformPayment, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum AdyenPayoutMethodDetails { BankAccount(AdyenBankAccountDetails), Card(AdyenCardDetails), } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenBankAccountDetails { account_holder: AdyenAccountHolder, account_identification: AdyenBankAccountIdentification, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenAccountHolder { address: Option<AdyenAddress>, first_name: Option<Secret<String>>, last_name: Option<Secret<String>>, full_name: Option<Secret<String>>, email: Option<pii::Email>, #[serde(rename = "reference")] customer_id: Option<String>, #[serde(rename = "type")] entity_type: Option<EntityType>, } #[serde_with::skip_serializing_none] #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenAddress { line1: Secret<String>, line2: Secret<String>, postal_code: Option<Secret<String>>, state_or_province: Option<Secret<String>>, city: String, country: enums::CountryAlpha2, } #[derive(Debug, Serialize, Deserialize)] pub struct AdyenBankAccountIdentification { #[serde(rename = "type")] bank_type: String, #[serde(flatten)] account_details: AdyenBankAccountIdentificationDetails, } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum AdyenBankAccountIdentificationDetails { Sepa(SepaDetails), } #[derive(Debug, Serialize, Deserialize)] pub struct SepaDetails { iban: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdyenCardDetails { card_holder: AdyenAccountHolder, card_identification: AdyenCardIdentification, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum AdyenCardIdentification { Card(AdyenRawCardIdentification), Stored(AdyenStoredCardIdentification), } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdyenRawCardIdentification { #[serde(rename = "number")] card_number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, issue_number: Option<String>, start_month: Option<String>, start_year: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdyenStoredCardIdentification { stored_payment_method_id: Secret<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum AdyenPayoutPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum EntityType { Individual, Organization, Unknown, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenTransferResponse { id: String, account_holder: AdyenPlatformAccountHolder, amount: adyen::Amount, balance_account: AdyenBalanceAccount, category: AdyenPayoutMethod, category_data: Option<AdyenCategoryData>, direction: AdyenTransactionDirection, reference: String, reference_for_beneficiary: String, status: AdyenTransferStatus, #[serde(rename = "type")] transaction_type: AdyenTransactionType, reason: String, } #[derive(Debug, Serialize, Deserialize)] pub struct AdyenPlatformAccountHolder { description: String, id: String, } #[derive(Debug, Serialize, Deserialize)] pub struct AdyenCategoryData { priority: AdyenPayoutPriority, #[serde(rename = "type")] category: AdyenPayoutMethod, } #[derive(Debug, Serialize, Deserialize)] pub struct AdyenBalanceAccount { description: String, id: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum AdyenTransactionDirection { Incoming, Outgoing, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum AdyenTransferStatus { Authorised, Refused, Error, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum AdyenTransactionType { BankTransfer, CardTransfer, InternalTransfer, Payment, Refund, } impl TryFrom<&hyperswitch_domain_models::address::AddressDetails> for AdyenAddress { type Error = Error; fn try_from( address: &hyperswitch_domain_models::address::AddressDetails, ) -> Result<Self, Self::Error> { let line1 = address .get_line1() .change_context(ConnectorError::MissingRequiredField { field_name: "billing.address.line1", })? .clone(); let line2 = address .get_line2() .change_context(ConnectorError::MissingRequiredField { field_name: "billing.address.line2", })? .clone(); Ok(Self { line1, line2, postal_code: address.get_optional_zip(), state_or_province: address.get_optional_state(), city: address.get_city()?.to_owned(), country: address.get_country()?.to_owned(), }) } } impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::CardPayout)> for AdyenAccountHolder { type Error = Error; fn try_from( (router_data, card): (&PayoutsRouterData<F>, &payouts::CardPayout), ) -> Result<Self, Self::Error> { let billing_address = router_data.get_optional_billing(); let address = billing_address .and_then(|billing| billing.address.as_ref().map(|addr| addr.try_into())) .transpose()? .ok_or(ConnectorError::MissingRequiredField { field_name: "address", })?; let (first_name, last_name) = if let Some(card_holder_name) = &card.card_holder_name { let exposed_name = card_holder_name.clone().expose(); let name_parts: Vec<&str> = exposed_name.split_whitespace().collect(); let first_name = name_parts .first() .map(|s| Secret::new(s.to_string())) .ok_or(ConnectorError::MissingRequiredField { field_name: "card_holder_name.first_name", })?; let last_name = if name_parts.len() > 1 { let remaining_names: Vec<&str> = name_parts.iter().skip(1).copied().collect(); Some(Secret::new(remaining_names.join(" "))) } else { return Err(ConnectorError::MissingRequiredField { field_name: "card_holder_name.last_name", } .into()); }; (Some(first_name), last_name) } else { return Err(ConnectorError::MissingRequiredField { field_name: "card_holder_name", } .into()); }; let customer_id_reference = match router_data.get_connector_customer_id() { Ok(connector_customer_id) => connector_customer_id, Err(_) => { let customer_id = router_data.get_customer_id()?; format!( "{}_{}", router_data.merchant_id.get_string_repr(), customer_id.get_string_repr() ) } }; Ok(Self { address: Some(address), first_name, last_name, full_name: None, email: router_data.get_optional_billing_email(), customer_id: Some(customer_id_reference), entity_type: Some(EntityType::from(router_data.request.entity_type)), }) } } impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::Bank)> for AdyenAccountHolder { type Error = Error; fn try_from( (router_data, _bank): (&PayoutsRouterData<F>, &payouts::Bank), ) -> Result<Self, Self::Error> { let billing_address = router_data.get_optional_billing(); let address = billing_address .and_then(|billing| billing.address.as_ref().map(|addr| addr.try_into())) .transpose()? .ok_or(ConnectorError::MissingRequiredField { field_name: "address", })?; let full_name = router_data.get_billing_full_name()?; let customer_id_reference = match router_data.get_connector_customer_id() { Ok(connector_customer_id) => connector_customer_id, Err(_) => { let customer_id = router_data.get_customer_id()?; format!( "{}_{}", router_data.merchant_id.get_string_repr(), customer_id.get_string_repr() ) } }; Ok(Self { address: Some(address), first_name: None, last_name: None, full_name: Some(full_name), email: router_data.get_optional_billing_email(), customer_id: Some(customer_id_reference), entity_type: Some(EntityType::from(router_data.request.entity_type)), }) } } #[derive(Debug)] pub struct StoredPaymentCounterparty<'a, F> { pub item: &'a AdyenPlatformRouterData<&'a PayoutsRouterData<F>>, pub stored_payment_method_id: String, } #[derive(Debug)] pub struct RawPaymentCounterparty<'a, F> { pub item: &'a AdyenPlatformRouterData<&'a PayoutsRouterData<F>>, pub raw_payout_method_data: payouts::PayoutMethodData, } impl<F> TryFrom<StoredPaymentCounterparty<'_, F>> for (AdyenPayoutMethodDetails, Option<AdyenPayoutPriority>) { type Error = Error; fn try_from(stored_payment: StoredPaymentCounterparty<'_, F>) -> Result<Self, Self::Error> { let request = &stored_payment.item.router_data.request; let payout_type = request.get_payout_type()?; match payout_type { enums::PayoutType::Card => { let billing_address = stored_payment.item.router_data.get_optional_billing(); let address = billing_address .and_then(|billing| billing.address.as_ref()) .ok_or(ConnectorError::MissingRequiredField { field_name: "address", })? .try_into()?; let customer_id_reference = match stored_payment.item.router_data.get_connector_customer_id() { Ok(connector_customer_id) => connector_customer_id, Err(_) => { let customer_id = stored_payment.item.router_data.get_customer_id()?; format!( "{}_{}", stored_payment .item .router_data .merchant_id .get_string_repr(), customer_id.get_string_repr() ) } }; let card_holder = AdyenAccountHolder { address: Some(address), first_name: stored_payment .item .router_data .get_optional_billing_first_name(), last_name: stored_payment .item .router_data .get_optional_billing_last_name(), full_name: stored_payment .item .router_data .get_optional_billing_full_name(), email: stored_payment.item.router_data.get_optional_billing_email(), customer_id: Some(customer_id_reference), entity_type: Some(EntityType::from(request.entity_type)), }; let card_identification = AdyenCardIdentification::Stored(AdyenStoredCardIdentification { stored_payment_method_id: Secret::new( stored_payment.stored_payment_method_id, ), }); let counterparty = AdyenPayoutMethodDetails::Card(AdyenCardDetails { card_holder, card_identification, }); Ok((counterparty, None)) } _ => Err(ConnectorError::NotSupported { message: "Stored payment method is only supported for card payouts".to_string(), connector: "Adyenplatform", } .into()), } } } impl<F> TryFrom<RawPaymentCounterparty<'_, F>> for (AdyenPayoutMethodDetails, Option<AdyenPayoutPriority>) { type Error = Error; fn try_from(raw_payment: RawPaymentCounterparty<'_, F>) -> Result<Self, Self::Error> { let request = &raw_payment.item.router_data.request; match raw_payment.raw_payout_method_data { payouts::PayoutMethodData::Wallet(_) | payouts::PayoutMethodData::BankRedirect(_) => { Err(ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyenplatform"), ))? } payouts::PayoutMethodData::Card(c) => { let card_holder: AdyenAccountHolder = (raw_payment.item.router_data, &c).try_into()?; let card_identification = AdyenCardIdentification::Card(AdyenRawCardIdentification { expiry_year: c.get_expiry_year_4_digit(), card_number: c.card_number, expiry_month: c.expiry_month, issue_number: None, start_month: None, start_year: None, }); let counterparty = AdyenPayoutMethodDetails::Card(AdyenCardDetails { card_holder, card_identification, }); Ok((counterparty, None)) } payouts::PayoutMethodData::Bank(bd) => { let account_holder: AdyenAccountHolder = (raw_payment.item.router_data, &bd).try_into()?; let bank_details = match bd { payouts::Bank::Sepa(b) => AdyenBankAccountIdentification { bank_type: "iban".to_string(), account_details: AdyenBankAccountIdentificationDetails::Sepa(SepaDetails { iban: b.iban, }), }, payouts::Bank::Ach(..) => Err(ConnectorError::NotSupported { message: "Bank transfer via ACH is not supported".to_string(), connector: "Adyenplatform", })?, payouts::Bank::Bacs(..) => Err(ConnectorError::NotSupported { message: "Bank transfer via Bacs is not supported".to_string(), connector: "Adyenplatform", })?, payouts::Bank::Pix(..) => Err(ConnectorError::NotSupported { message: "Bank transfer via Pix is not supported".to_string(), connector: "Adyenplatform", })?, }; let counterparty = AdyenPayoutMethodDetails::BankAccount(AdyenBankAccountDetails { account_holder, account_identification: bank_details, }); let priority = request .priority .ok_or(ConnectorError::MissingRequiredField { field_name: "priority", })?; Ok((counterparty, Some(AdyenPayoutPriority::from(priority)))) } } } } impl<F> TryFrom<&AdyenPlatformRouterData<&PayoutsRouterData<F>>> for AdyenTransferRequest { type Error = Error; fn try_from( item: &AdyenPlatformRouterData<&PayoutsRouterData<F>>, ) -> Result<Self, Self::Error> { let request = &item.router_data.request; let stored_payment_method_result = item.router_data.request.get_connector_transfer_method_id(); let raw_payout_method_result = item.router_data.get_payout_method_data(); let (counterparty, priority) = if let Ok(stored_payment_method_id) = stored_payment_method_result { StoredPaymentCounterparty { item, stored_payment_method_id, } .try_into()? } else if let Ok(raw_payout_method_data) = raw_payout_method_result { RawPaymentCounterparty { item, raw_payout_method_data, } .try_into()? } else { return Err(ConnectorError::MissingRequiredField { field_name: "payout_method_data or stored_payment_method_id", } .into()); }; let adyen_connector_metadata_object = AdyenPlatformConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?; let balance_account_id = adyen_connector_metadata_object .source_balance_account .ok_or(ConnectorError::InvalidConnectorConfig { config: "metadata.source_balance_account", })?; let payout_type = request.get_payout_type()?; Ok(Self { amount: adyen::Amount { value: item.amount, currency: request.destination_currency, }, balance_account_id, category: AdyenPayoutMethod::try_from(payout_type)?, counterparty, priority, reference: item.router_data.connector_request_reference_id.clone(), reference_for_beneficiary: item.router_data.connector_request_reference_id.clone(), description: item.router_data.description.clone(), }) } } impl<F> TryFrom<PayoutsResponseRouterData<F, AdyenTransferResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( item: PayoutsResponseRouterData<F, AdyenTransferResponse>, ) -> Result<Self, Self::Error> { let response: AdyenTransferResponse = item.response; let status = enums::PayoutStatus::from(response.status); if matches!(status, enums::PayoutStatus::Failed) { return Ok(Self { response: Err(hyperswitch_domain_models::router_data::ErrorResponse { code: response.status.to_string(), message: if !response.reason.is_empty() { response.reason } else { response.status.to_string() }, reason: None, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(response.id), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }); } Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(status), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } impl From<AdyenTransferStatus> for enums::PayoutStatus { fn from(adyen_status: AdyenTransferStatus) -> Self { match adyen_status { AdyenTransferStatus::Authorised => Self::Initiated, AdyenTransferStatus::Error | AdyenTransferStatus::Refused => Self::Failed, } } } impl From<enums::PayoutEntityType> for EntityType { fn from(entity: enums::PayoutEntityType) -> Self { match entity { enums::PayoutEntityType::Individual | enums::PayoutEntityType::Personal | enums::PayoutEntityType::NaturalPerson => Self::Individual, enums::PayoutEntityType::Company | enums::PayoutEntityType::Business => { Self::Organization } _ => Self::Unknown, } } } impl From<enums::PayoutSendPriority> for AdyenPayoutPriority { fn from(entity: enums::PayoutSendPriority) -> Self { match entity { enums::PayoutSendPriority::Instant => Self::Instant, enums::PayoutSendPriority::Fast => Self::Fast, enums::PayoutSendPriority::Regular => Self::Regular, enums::PayoutSendPriority::Wire => Self::Wire, enums::PayoutSendPriority::CrossBorder => Self::CrossBorder, enums::PayoutSendPriority::Internal => Self::Internal, } } } impl TryFrom<enums::PayoutType> for AdyenPayoutMethod { type Error = Error; fn try_from(payout_type: enums::PayoutType) -> Result<Self, Self::Error> { match payout_type { enums::PayoutType::Bank => Ok(Self::Bank), enums::PayoutType::Card => Ok(Self::Card), enums::PayoutType::Wallet | enums::PayoutType::BankRedirect => { Err(report!(ConnectorError::NotSupported { message: "Bakredirect or wallet payouts".to_string(), connector: "Adyenplatform", })) } } } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenplatformIncomingWebhook { pub data: AdyenplatformIncomingWebhookData, #[serde(rename = "type")] pub webhook_type: AdyenplatformWebhookEventType, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenplatformIncomingWebhookData { pub status: AdyenplatformWebhookStatus, pub reference: String, pub tracking: Option<AdyenplatformTrackingData>, pub category: Option<AdyenPayoutMethod>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenplatformTrackingData { status: TrackingStatus, estimated_arrival_time: Option<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum TrackingStatus { Accepted, Pending, Credited, } #[derive(Debug, Serialize, Deserialize)] pub enum AdyenplatformWebhookEventType { #[serde(rename = "balancePlatform.transfer.created")] PayoutCreated, #[serde(rename = "balancePlatform.transfer.updated")] PayoutUpdated, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum AdyenplatformWebhookStatus { Authorised, Booked, Pending, Failed, Returned, Received, } pub fn get_adyen_payout_webhook_event( event_type: AdyenplatformWebhookEventType, status: AdyenplatformWebhookStatus, tracking_data: Option<AdyenplatformTrackingData>, ) -> webhooks::IncomingWebhookEvent { match (event_type, status, tracking_data) { (AdyenplatformWebhookEventType::PayoutCreated, _, _) => { webhooks::IncomingWebhookEvent::PayoutCreated } (AdyenplatformWebhookEventType::PayoutUpdated, _, Some(tracking_data)) => { match tracking_data.status { TrackingStatus::Credited | TrackingStatus::Accepted => { webhooks::IncomingWebhookEvent::PayoutSuccess } TrackingStatus::Pending => webhooks::IncomingWebhookEvent::PayoutProcessing, } } (AdyenplatformWebhookEventType::PayoutUpdated, status, _) => match status { AdyenplatformWebhookStatus::Authorised | AdyenplatformWebhookStatus::Received => { webhooks::IncomingWebhookEvent::PayoutCreated } AdyenplatformWebhookStatus::Booked | AdyenplatformWebhookStatus::Pending => { webhooks::IncomingWebhookEvent::PayoutProcessing } AdyenplatformWebhookStatus::Failed => webhooks::IncomingWebhookEvent::PayoutFailure, AdyenplatformWebhookStatus::Returned => webhooks::IncomingWebhookEvent::PayoutReversed, }, } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenTransferErrorResponse { pub error_code: String, #[serde(rename = "type")] pub error_type: String, pub status: u16, pub title: String, pub detail: Option<String>, pub request_id: Option<String>, pub invalid_fields: Option<Vec<AdyenInvalidField>>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenInvalidField { pub name: Option<String>, pub value: Option<String>, pub message: Option<String>, }
crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs
hyperswitch_connectors::src::connectors::adyenplatform::transformers::payouts
5,589
true
// File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs // Module: hyperswitch_connectors::src::connectors::trustpay::transformers use std::collections::HashMap; use api_models::payments::SessionToken; use common_enums::enums; use common_utils::{ errors::CustomResult, pii::{self, Email}, request::Method, types::{FloatMajorUnit, StringMajorUnit}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ network_tokenization::NetworkTokenNumber, payment_method_data::{BankRedirectData, BankTransferData, Card, PaymentMethodData}, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_request_types::{BrowserInformation, PaymentsPreProcessingData, ResponseId}, router_response_types::{ PaymentsResponseData, PreprocessingResponseId, RedirectForm, RefundsResponseData, }, types::{ PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, RefreshTokenRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{consts, errors}; use masking::{ExposeInterface, PeekInterface, Secret}; use reqwest::Url; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, AddressDetailsData, BrowserInformationData, CardData, NetworkTokenData, PaymentsAuthorizeRequestData, PaymentsPreProcessingRequestData, RouterData as OtherRouterData, }, }; type Error = error_stack::Report<errors::ConnectorError>; #[derive(Debug, Serialize)] pub struct TrustpayRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> TryFrom<(StringMajorUnit, T)> for TrustpayRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } } pub struct TrustpayAuthType { pub(super) api_key: Secret<String>, pub(super) project_id: Secret<String>, pub(super) secret_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for TrustpayAuthType { type Error = Error; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } = auth_type { Ok(Self { api_key: api_key.to_owned(), project_id: key1.to_owned(), secret_key: api_secret.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } } } #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] pub enum TrustpayPaymentMethod { #[serde(rename = "EPS")] Eps, Giropay, IDeal, Sofort, Blik, } #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] pub enum TrustpayBankTransferPaymentMethod { SepaCreditTransfer, #[serde(rename = "Wire")] InstantBankTransfer, InstantBankTransferFI, InstantBankTransferPL, } #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct MerchantIdentification { pub project_id: Secret<String>, } #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct References { pub merchant_reference: String, } #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct Amount { pub amount: StringMajorUnit, pub currency: String, } #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct Reason { pub code: Option<String>, pub reject_reason: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct StatusReasonInformation { pub reason: Reason, } #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct DebtorInformation { pub name: Secret<String>, pub email: Email, } #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct BankPaymentInformation { pub amount: Amount, pub references: References, #[serde(skip_serializing_if = "Option::is_none")] pub debtor: Option<DebtorInformation>, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct BankPaymentInformationResponse { pub status: TrustpayBankRedirectPaymentStatus, pub status_reason_information: Option<StatusReasonInformation>, pub references: ReferencesResponse, pub amount: WebhookAmount, } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct CallbackURLs { pub success: String, pub cancel: String, pub error: String, } #[derive(Debug, Serialize, PartialEq)] pub struct PaymentRequestCards { pub amount: StringMajorUnit, pub currency: String, pub pan: cards::CardNumber, pub cvv: Secret<String>, #[serde(rename = "exp")] pub expiry_date: Secret<String>, pub cardholder: Secret<String>, pub reference: String, #[serde(rename = "redirectUrl")] pub redirect_url: String, #[serde(rename = "billing[city]")] pub billing_city: String, #[serde(rename = "billing[country]")] pub billing_country: api_models::enums::CountryAlpha2, #[serde(rename = "billing[street1]")] pub billing_street1: Secret<String>, #[serde(rename = "billing[postcode]")] pub billing_postcode: Secret<String>, #[serde(rename = "customer[email]")] pub customer_email: Email, #[serde(rename = "customer[ipAddress]")] pub customer_ip_address: Secret<String, pii::IpAddress>, #[serde(rename = "browser[acceptHeader]")] pub browser_accept_header: String, #[serde(rename = "browser[language]")] pub browser_language: String, #[serde(rename = "browser[screenHeight]")] pub browser_screen_height: String, #[serde(rename = "browser[screenWidth]")] pub browser_screen_width: String, #[serde(rename = "browser[timezone]")] pub browser_timezone: String, #[serde(rename = "browser[userAgent]")] pub browser_user_agent: String, #[serde(rename = "browser[javaEnabled]")] pub browser_java_enabled: String, #[serde(rename = "browser[javaScriptEnabled]")] pub browser_java_script_enabled: String, #[serde(rename = "browser[screenColorDepth]")] pub browser_screen_color_depth: String, #[serde(rename = "browser[challengeWindow]")] pub browser_challenge_window: String, #[serde(rename = "browser[paymentAction]")] pub payment_action: Option<String>, #[serde(rename = "browser[paymentType]")] pub payment_type: String, pub descriptor: Option<String>, } #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentRequestBankRedirect { pub payment_method: TrustpayPaymentMethod, pub merchant_identification: MerchantIdentification, pub payment_information: BankPaymentInformation, pub callback_urls: CallbackURLs, } #[derive(Debug, Serialize, PartialEq)] #[serde(untagged)] pub enum TrustpayPaymentsRequest { CardsPaymentRequest(Box<PaymentRequestCards>), BankRedirectPaymentRequest(Box<PaymentRequestBankRedirect>), BankTransferPaymentRequest(Box<PaymentRequestBankTransfer>), NetworkTokenPaymentRequest(Box<PaymentRequestNetworkToken>), } #[derive(Debug, Serialize, PartialEq)] pub struct PaymentRequestNetworkToken { pub amount: StringMajorUnit, pub currency: enums::Currency, pub pan: NetworkTokenNumber, #[serde(rename = "exp")] pub expiry_date: Secret<String>, #[serde(rename = "RedirectUrl")] pub redirect_url: String, #[serde(rename = "threeDSecureEnrollmentStatus")] pub enrollment_status: char, #[serde(rename = "threeDSecureEci")] pub eci: String, #[serde(rename = "threeDSecureAuthenticationStatus")] pub authentication_status: char, #[serde(rename = "threeDSecureVerificationId")] pub verification_id: Secret<String>, } #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentRequestBankTransfer { pub payment_method: TrustpayBankTransferPaymentMethod, pub merchant_identification: MerchantIdentification, pub payment_information: BankPaymentInformation, pub callback_urls: CallbackURLs, } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct TrustpayMandatoryParams { pub billing_city: String, pub billing_country: api_models::enums::CountryAlpha2, pub billing_street1: Secret<String>, pub billing_postcode: Secret<String>, pub billing_first_name: Secret<String>, } impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod { type Error = Error; fn try_from(value: &BankRedirectData) -> Result<Self, Self::Error> { match value { BankRedirectData::Giropay { .. } => Ok(Self::Giropay), BankRedirectData::Eps { .. } => Ok(Self::Eps), BankRedirectData::Ideal { .. } => Ok(Self::IDeal), BankRedirectData::Sofort { .. } => Ok(Self::Sofort), BankRedirectData::Blik { .. } => Ok(Self::Blik), BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::Trustly { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::LocalBankRedirect {} => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("trustpay"), ) .into()) } } } } impl TryFrom<&BankTransferData> for TrustpayBankTransferPaymentMethod { type Error = Error; fn try_from(value: &BankTransferData) -> Result<Self, Self::Error> { match value { BankTransferData::SepaBankTransfer { .. } => Ok(Self::SepaCreditTransfer), BankTransferData::InstantBankTransfer {} => Ok(Self::InstantBankTransfer), BankTransferData::InstantBankTransferFinland {} => Ok(Self::InstantBankTransferFI), BankTransferData::InstantBankTransferPoland {} => Ok(Self::InstantBankTransferPL), _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("trustpay"), ) .into()), } } } fn get_mandatory_fields( item: &PaymentsAuthorizeRouterData, ) -> Result<TrustpayMandatoryParams, Error> { let billing_address = item .get_billing()? .address .as_ref() .ok_or_else(utils::missing_field_err("billing.address"))?; Ok(TrustpayMandatoryParams { billing_city: billing_address.get_city()?.to_owned(), billing_country: billing_address.get_country()?.to_owned(), billing_street1: billing_address.get_line1()?.to_owned(), billing_postcode: billing_address.get_zip()?.to_owned(), billing_first_name: billing_address.get_first_name()?.to_owned(), }) } fn get_card_request_data( item: &PaymentsAuthorizeRouterData, browser_info: &BrowserInformation, params: TrustpayMandatoryParams, amount: StringMajorUnit, ccard: &Card, return_url: String, ) -> Result<TrustpayPaymentsRequest, Error> { let email = item.request.get_email()?; let customer_ip_address = browser_info.get_ip_address()?; let billing_last_name = item .get_billing()? .address .as_ref() .and_then(|address| address.last_name.clone()); Ok(TrustpayPaymentsRequest::CardsPaymentRequest(Box::new( PaymentRequestCards { amount, currency: item.request.currency.to_string(), pan: ccard.card_number.clone(), cvv: ccard.card_cvc.clone(), expiry_date: ccard.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?, cardholder: get_full_name(params.billing_first_name, billing_last_name), reference: item.connector_request_reference_id.clone(), redirect_url: return_url, billing_city: params.billing_city, billing_country: params.billing_country, billing_street1: params.billing_street1, billing_postcode: params.billing_postcode, customer_email: email, customer_ip_address, browser_accept_header: browser_info.get_accept_header()?, browser_language: browser_info.get_language()?, browser_screen_height: browser_info.get_screen_height()?.to_string(), browser_screen_width: browser_info.get_screen_width()?.to_string(), browser_timezone: browser_info.get_time_zone()?.to_string(), browser_user_agent: browser_info.get_user_agent()?, browser_java_enabled: browser_info.get_java_enabled()?.to_string(), browser_java_script_enabled: browser_info.get_java_script_enabled()?.to_string(), browser_screen_color_depth: browser_info.get_color_depth()?.to_string(), browser_challenge_window: "1".to_string(), payment_action: None, payment_type: "Plain".to_string(), descriptor: item.request.statement_descriptor.clone(), }, ))) } fn get_full_name( billing_first_name: Secret<String>, billing_last_name: Option<Secret<String>>, ) -> Secret<String> { match billing_last_name { Some(last_name) => format!("{} {}", billing_first_name.peek(), last_name.peek()).into(), None => billing_first_name, } } fn get_debtor_info( item: &PaymentsAuthorizeRouterData, pm: TrustpayPaymentMethod, params: TrustpayMandatoryParams, ) -> CustomResult<Option<DebtorInformation>, errors::ConnectorError> { let billing_last_name = item .get_billing()? .address .as_ref() .and_then(|address| address.last_name.clone()); Ok(match pm { TrustpayPaymentMethod::Blik => Some(DebtorInformation { name: get_full_name(params.billing_first_name, billing_last_name), email: item.request.get_email()?, }), TrustpayPaymentMethod::Eps | TrustpayPaymentMethod::Giropay | TrustpayPaymentMethod::IDeal | TrustpayPaymentMethod::Sofort => None, }) } fn get_bank_transfer_debtor_info( item: &PaymentsAuthorizeRouterData, pm: TrustpayBankTransferPaymentMethod, params: TrustpayMandatoryParams, ) -> CustomResult<Option<DebtorInformation>, errors::ConnectorError> { let billing_last_name = item .get_billing()? .address .as_ref() .and_then(|address| address.last_name.clone()); Ok(match pm { TrustpayBankTransferPaymentMethod::SepaCreditTransfer | TrustpayBankTransferPaymentMethod::InstantBankTransfer | TrustpayBankTransferPaymentMethod::InstantBankTransferFI | TrustpayBankTransferPaymentMethod::InstantBankTransferPL => Some(DebtorInformation { name: get_full_name(params.billing_first_name, billing_last_name), email: item.request.get_email()?, }), }) } fn get_bank_redirection_request_data( item: &PaymentsAuthorizeRouterData, bank_redirection_data: &BankRedirectData, params: TrustpayMandatoryParams, amount: StringMajorUnit, auth: TrustpayAuthType, ) -> Result<TrustpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> { let pm = TrustpayPaymentMethod::try_from(bank_redirection_data)?; let return_url = item.request.get_router_return_url()?; let payment_request = TrustpayPaymentsRequest::BankRedirectPaymentRequest(Box::new(PaymentRequestBankRedirect { payment_method: pm.clone(), merchant_identification: MerchantIdentification { project_id: auth.project_id, }, payment_information: BankPaymentInformation { amount: Amount { amount, currency: item.request.currency.to_string(), }, references: References { merchant_reference: item.connector_request_reference_id.clone(), }, debtor: get_debtor_info(item, pm, params)?, }, callback_urls: CallbackURLs { success: format!("{return_url}?status=SuccessOk"), cancel: return_url.clone(), error: return_url, }, })); Ok(payment_request) } fn get_bank_transfer_request_data( item: &PaymentsAuthorizeRouterData, bank_transfer_data: &BankTransferData, params: TrustpayMandatoryParams, amount: StringMajorUnit, auth: TrustpayAuthType, ) -> Result<TrustpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> { let pm = TrustpayBankTransferPaymentMethod::try_from(bank_transfer_data)?; let return_url = item.request.get_router_return_url()?; let payment_request = TrustpayPaymentsRequest::BankTransferPaymentRequest(Box::new(PaymentRequestBankTransfer { payment_method: pm.clone(), merchant_identification: MerchantIdentification { project_id: auth.project_id, }, payment_information: BankPaymentInformation { amount: Amount { amount, currency: item.request.currency.to_string(), }, references: References { merchant_reference: item.connector_request_reference_id.clone(), }, debtor: get_bank_transfer_debtor_info(item, pm, params)?, }, callback_urls: CallbackURLs { success: format!("{return_url}?status=SuccessOk"), cancel: return_url.clone(), error: return_url, }, })); Ok(payment_request) } impl TryFrom<&TrustpayRouterData<&PaymentsAuthorizeRouterData>> for TrustpayPaymentsRequest { type Error = Error; fn try_from( item: &TrustpayRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let browser_info = item .router_data .request .browser_info .clone() .unwrap_or_default(); let default_browser_info = BrowserInformation { color_depth: Some(browser_info.color_depth.unwrap_or(24)), java_enabled: Some(browser_info.java_enabled.unwrap_or(false)), java_script_enabled: Some(browser_info.java_enabled.unwrap_or(true)), language: Some(browser_info.language.unwrap_or("en-US".to_string())), screen_height: Some(browser_info.screen_height.unwrap_or(1080)), screen_width: Some(browser_info.screen_width.unwrap_or(1920)), time_zone: Some(browser_info.time_zone.unwrap_or(3600)), accept_header: Some(browser_info.accept_header.unwrap_or("*".to_string())), user_agent: browser_info.user_agent, ip_address: browser_info.ip_address, os_type: None, os_version: None, device_model: None, accept_language: Some(browser_info.accept_language.unwrap_or("en".to_string())), referer: None, }; let params = get_mandatory_fields(item.router_data)?; let amount = item.amount.to_owned(); let auth = TrustpayAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref ccard) => Ok(get_card_request_data( item.router_data, &default_browser_info, params, amount, ccard, item.router_data.request.get_router_return_url()?, )?), PaymentMethodData::BankRedirect(ref bank_redirection_data) => { get_bank_redirection_request_data( item.router_data, bank_redirection_data, params, amount, auth, ) } PaymentMethodData::BankTransfer(ref bank_transfer_data) => { get_bank_transfer_request_data( item.router_data, bank_transfer_data, params, amount, auth, ) } PaymentMethodData::NetworkToken(ref token_data) => { Ok(Self::NetworkTokenPaymentRequest(Box::new( PaymentRequestNetworkToken { amount: item.amount.to_owned(), currency: item.router_data.request.currency, pan: token_data.get_network_token(), expiry_date: token_data .get_token_expiry_month_year_2_digit_with_delimiter("/".to_owned())?, redirect_url: item.router_data.request.get_router_return_url()?, enrollment_status: 'Y', // Set to 'Y' as network provider not providing this value in response eci: token_data.eci.clone().ok_or_else(|| { errors::ConnectorError::MissingRequiredField { field_name: "eci" } })?, authentication_status: 'Y', // Set to 'Y' since presence of token_cryptogram is already validated verification_id: token_data.get_cryptogram().ok_or_else(|| { errors::ConnectorError::MissingRequiredField { field_name: "verification_id", } })?, }, ))) } PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("trustpay"), ) .into()) } } } } fn is_payment_failed(payment_status: &str) -> (bool, &'static str) { match payment_status { "100.100.600" => (true, "Empty CVV for VISA, MASTER not allowed"), "100.350.100" => (true, "Referenced session is rejected (no action possible)"), "100.380.401" => (true, "User authentication failed"), "100.380.501" => (true, "Risk management transaction timeout"), "100.390.103" => (true, "PARes validation failed - problem with signature"), "100.390.105" => ( true, "Transaction rejected because of technical error in 3DSecure system", ), "100.390.111" => ( true, "Communication error to VISA/Mastercard Directory Server", ), "100.390.112" => (true, "Technical error in 3D system"), "100.390.115" => (true, "Authentication failed due to invalid message format"), "100.390.118" => (true, "Authentication failed due to suspected fraud"), "100.400.304" => (true, "Invalid input data"), "100.550.312" => (true, "Amount is outside allowed ticket size boundaries"), "200.300.404" => (true, "Invalid or missing parameter"), "300.100.100" => ( true, "Transaction declined (additional customer authentication required)", ), "400.001.301" => (true, "Card not enrolled in 3DS"), "400.001.600" => (true, "Authentication error"), "400.001.601" => (true, "Transaction declined (auth. declined)"), "400.001.602" => (true, "Invalid transaction"), "400.001.603" => (true, "Invalid transaction"), "400.003.600" => (true, "No description available."), "700.400.200" => ( true, "Cannot refund (refund volume exceeded or tx reversed or invalid workflow)", ), "700.500.001" => (true, "Referenced session contains too many transactions"), "700.500.003" => (true, "Test accounts not allowed in production"), "800.100.100" => (true, "Transaction declined for unknown reason"), "800.100.151" => (true, "Transaction declined (invalid card)"), "800.100.152" => (true, "Transaction declined by authorization system"), "800.100.153" => (true, "Transaction declined (invalid CVV)"), "800.100.155" => (true, "Transaction declined (amount exceeds credit)"), "800.100.157" => (true, "Transaction declined (wrong expiry date)"), "800.100.158" => (true, "transaction declined (suspecting manipulation)"), "800.100.160" => (true, "transaction declined (card blocked)"), "800.100.162" => (true, "Transaction declined (limit exceeded)"), "800.100.163" => ( true, "Transaction declined (maximum transaction frequency exceeded)", ), "800.100.165" => (true, "Transaction declined (card lost)"), "800.100.168" => (true, "Transaction declined (restricted card)"), "800.100.170" => (true, "Transaction declined (transaction not permitted)"), "800.100.171" => (true, "transaction declined (pick up card)"), "800.100.172" => (true, "Transaction declined (account blocked)"), "800.100.190" => (true, "Transaction declined (invalid configuration data)"), "800.100.202" => (true, "Account Closed"), "800.100.203" => (true, "Insufficient Funds"), "800.120.100" => (true, "Rejected by throttling"), "800.300.102" => (true, "Country blacklisted"), "800.300.401" => (true, "Bin blacklisted"), "800.700.100" => ( true, "Transaction for the same session is currently being processed, please try again later", ), "900.100.100" => ( true, "Unexpected communication error with connector/acquirer", ), "900.100.300" => (true, "Timeout, uncertain result"), _ => (false, ""), } } fn is_payment_successful(payment_status: &str) -> CustomResult<bool, errors::ConnectorError> { match payment_status { "000.400.100" => Ok(true), _ => { let allowed_prefixes = [ "000.000.", "000.100.1", "000.3", "000.6", "000.400.01", "000.400.02", "000.400.04", "000.400.05", "000.400.06", "000.400.07", "000.400.08", "000.400.09", ]; let is_valid = allowed_prefixes .iter() .any(|&prefix| payment_status.starts_with(prefix)); Ok(is_valid) } } } fn get_pending_status_based_on_redirect_url(redirect_url: Option<Url>) -> enums::AttemptStatus { match redirect_url { Some(_url) => enums::AttemptStatus::AuthenticationPending, None => enums::AttemptStatus::Pending, } } fn get_transaction_status( payment_status: Option<String>, redirect_url: Option<Url>, ) -> CustomResult<(enums::AttemptStatus, Option<String>), errors::ConnectorError> { // We don't get payment_status only in case, when the user doesn't complete the authentication step. // If we receive status, then return the proper status based on the connector response if let Some(payment_status) = payment_status { let (is_failed, failure_message) = is_payment_failed(&payment_status); if is_failed { return Ok(( enums::AttemptStatus::Failure, Some(failure_message.to_string()), )); } if is_payment_successful(&payment_status)? { return Ok((enums::AttemptStatus::Charged, None)); } let pending_status = get_pending_status_based_on_redirect_url(redirect_url); Ok((pending_status, None)) } else { Ok((enums::AttemptStatus::AuthenticationPending, None)) } } #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] pub enum TrustpayBankRedirectPaymentStatus { Paid, Authorized, Rejected, Authorizing, Pending, } impl From<TrustpayBankRedirectPaymentStatus> for enums::AttemptStatus { fn from(item: TrustpayBankRedirectPaymentStatus) -> Self { match item { TrustpayBankRedirectPaymentStatus::Paid => Self::Charged, TrustpayBankRedirectPaymentStatus::Rejected => Self::AuthorizationFailed, TrustpayBankRedirectPaymentStatus::Authorized => Self::Authorized, TrustpayBankRedirectPaymentStatus::Authorizing => Self::Authorizing, TrustpayBankRedirectPaymentStatus::Pending => Self::Authorizing, } } } impl From<TrustpayBankRedirectPaymentStatus> for enums::RefundStatus { fn from(item: TrustpayBankRedirectPaymentStatus) -> Self { match item { TrustpayBankRedirectPaymentStatus::Paid => Self::Success, TrustpayBankRedirectPaymentStatus::Rejected => Self::Failure, _ => Self::Pending, } } } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentsResponseCards { pub status: i64, pub description: Option<String>, pub instance_id: String, pub payment_status: Option<String>, pub payment_description: Option<String>, pub redirect_url: Option<Url>, pub redirect_params: Option<HashMap<String, String>>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct PaymentsResponseBankRedirect { pub payment_request_id: i64, pub gateway_url: Url, pub payment_result_info: Option<ResultInfo>, pub payment_method_response: Option<TrustpayPaymentMethod>, pub merchant_identification_response: Option<MerchantIdentification>, pub payment_information_response: Option<BankPaymentInformationResponse>, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct ErrorResponseBankRedirect { #[serde(rename = "ResultInfo")] pub payment_result_info: ResultInfo, } #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct ReferencesResponse { pub payment_request_id: String, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct SyncResponseBankRedirect { pub payment_information: BankPaymentInformationResponse, } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(untagged)] pub enum TrustpayPaymentsResponse { CardsPayments(Box<PaymentsResponseCards>), BankRedirectPayments(Box<PaymentsResponseBankRedirect>), BankRedirectSync(Box<SyncResponseBankRedirect>), BankRedirectError(Box<ErrorResponseBankRedirect>), WebhookResponse(Box<WebhookPaymentInformation>), } impl<F, T> TryFrom<ResponseRouterData<F, TrustpayPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = Error; fn try_from( item: ResponseRouterData<F, TrustpayPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let (status, error, payment_response_data) = get_trustpay_response(item.response, item.http_code, item.data.status)?; Ok(Self { status, response: error.map_or_else(|| Ok(payment_response_data), Err), ..item.data }) } } fn handle_cards_response( response: PaymentsResponseCards, status_code: u16, ) -> CustomResult< ( enums::AttemptStatus, Option<ErrorResponse>, PaymentsResponseData, ), errors::ConnectorError, > { let (status, msg) = get_transaction_status( response.payment_status.to_owned(), response.redirect_url.to_owned(), )?; let form_fields = response.redirect_params.unwrap_or_default(); let redirection_data = response.redirect_url.map(|url| RedirectForm::Form { endpoint: url.to_string(), method: Method::Post, form_fields, }); let error = if msg.is_some() { Some(ErrorResponse { code: response .payment_status .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: msg .clone() .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: msg, status_code, attempt_status: None, connector_transaction_id: Some(response.instance_id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let payment_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response.instance_id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }; Ok((status, error, payment_response_data)) } fn handle_bank_redirects_response( response: PaymentsResponseBankRedirect, ) -> CustomResult< ( enums::AttemptStatus, Option<ErrorResponse>, PaymentsResponseData, ), errors::ConnectorError, > { let status = enums::AttemptStatus::AuthenticationPending; let error = None; let payment_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response.payment_request_id.to_string()), redirection_data: Box::new(Some(RedirectForm::from(( response.gateway_url, Method::Get, )))), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }; Ok((status, error, payment_response_data)) } fn handle_bank_redirects_error_response( response: ErrorResponseBankRedirect, status_code: u16, previous_attempt_status: enums::AttemptStatus, ) -> CustomResult< ( enums::AttemptStatus, Option<ErrorResponse>, PaymentsResponseData, ), errors::ConnectorError, > { let status = if matches!(response.payment_result_info.result_code, 1132014 | 1132005) { previous_attempt_status } else { enums::AttemptStatus::AuthorizationFailed }; let error = Some(ErrorResponse { code: response.payment_result_info.result_code.to_string(), // message vary for the same code, so relying on code alone as it is unique message: response.payment_result_info.result_code.to_string(), reason: response.payment_result_info.additional_info, status_code, attempt_status: Some(status), connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); let payment_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }; Ok((status, error, payment_response_data)) } fn handle_bank_redirects_sync_response( response: SyncResponseBankRedirect, status_code: u16, ) -> CustomResult< ( enums::AttemptStatus, Option<ErrorResponse>, PaymentsResponseData, ), errors::ConnectorError, > { let status = enums::AttemptStatus::from(response.payment_information.status); let error = if utils::is_payment_failure(status) { let reason_info = response .payment_information .status_reason_information .unwrap_or_default(); Some(ErrorResponse { code: reason_info .reason .code .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), // message vary for the same code, so relying on code alone as it is unique message: reason_info .reason .code .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: reason_info.reason.reject_reason, status_code, attempt_status: None, connector_transaction_id: Some( response .payment_information .references .payment_request_id .clone(), ), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let payment_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( response .payment_information .references .payment_request_id .clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }; Ok((status, error, payment_response_data)) } pub fn handle_webhook_response( payment_information: WebhookPaymentInformation, status_code: u16, ) -> CustomResult< ( enums::AttemptStatus, Option<ErrorResponse>, PaymentsResponseData, ), errors::ConnectorError, > { let status = enums::AttemptStatus::try_from(payment_information.status)?; let error = if utils::is_payment_failure(status) { let reason_info = payment_information .status_reason_information .unwrap_or_default(); Some(ErrorResponse { code: reason_info .reason .code .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), // message vary for the same code, so relying on code alone as it is unique message: reason_info .reason .code .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: reason_info.reason.reject_reason, status_code, attempt_status: None, connector_transaction_id: payment_information.references.payment_request_id.clone(), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let payment_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }; Ok((status, error, payment_response_data)) } pub fn get_trustpay_response( response: TrustpayPaymentsResponse, status_code: u16, previous_attempt_status: enums::AttemptStatus, ) -> CustomResult< ( enums::AttemptStatus, Option<ErrorResponse>, PaymentsResponseData, ), errors::ConnectorError, > { match response { TrustpayPaymentsResponse::CardsPayments(response) => { handle_cards_response(*response, status_code) } TrustpayPaymentsResponse::BankRedirectPayments(response) => { handle_bank_redirects_response(*response) } TrustpayPaymentsResponse::BankRedirectSync(response) => { handle_bank_redirects_sync_response(*response, status_code) } TrustpayPaymentsResponse::BankRedirectError(response) => { handle_bank_redirects_error_response(*response, status_code, previous_attempt_status) } TrustpayPaymentsResponse::WebhookResponse(response) => { handle_webhook_response(*response, status_code) } } } #[derive(Debug, Clone, Serialize, PartialEq)] pub struct TrustpayAuthUpdateRequest { pub grant_type: String, } impl TryFrom<&RefreshTokenRouterData> for TrustpayAuthUpdateRequest { type Error = Error; fn try_from(_item: &RefreshTokenRouterData) -> Result<Self, Self::Error> { Ok(Self { grant_type: "client_credentials".to_string(), }) } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct ResultInfo { pub result_code: i64, pub additional_info: Option<String>, pub correlation_id: Option<String>, } #[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq)] pub struct TrustpayAuthUpdateResponse { pub access_token: Option<Secret<String>>, pub token_type: Option<String>, pub expires_in: Option<i64>, #[serde(rename = "ResultInfo")] pub result_info: ResultInfo, } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "PascalCase")] pub struct TrustpayAccessTokenErrorResponse { pub result_info: ResultInfo, } impl<F, T> TryFrom<ResponseRouterData<F, TrustpayAuthUpdateResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = Error; fn try_from( item: ResponseRouterData<F, TrustpayAuthUpdateResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { match (item.response.access_token, item.response.expires_in) { (Some(access_token), Some(expires_in)) => Ok(Self { response: Ok(AccessToken { token: access_token, expires: expires_in, }), ..item.data }), _ => Ok(Self { response: Err(ErrorResponse { code: item.response.result_info.result_code.to_string(), // message vary for the same code, so relying on code alone as it is unique message: item.response.result_info.result_code.to_string(), reason: item.response.result_info.additional_info, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayCreateIntentRequest { pub amount: StringMajorUnit, pub currency: String, // If true, Apple Pay will be initialized pub init_apple_pay: Option<bool>, // If true, Google pay will be initialized pub init_google_pay: Option<bool>, pub reference: String, } impl TryFrom<&TrustpayRouterData<&PaymentsPreProcessingRouterData>> for TrustpayCreateIntentRequest { type Error = Error; fn try_from( item: &TrustpayRouterData<&PaymentsPreProcessingRouterData>, ) -> Result<Self, Self::Error> { let is_apple_pay = item .router_data .request .payment_method_type .as_ref() .map(|pmt| matches!(pmt, enums::PaymentMethodType::ApplePay)); let is_google_pay = item .router_data .request .payment_method_type .as_ref() .map(|pmt| matches!(pmt, enums::PaymentMethodType::GooglePay)); let currency = item.router_data.request.get_currency()?; let amount = item.amount.to_owned(); Ok(Self { amount, currency: currency.to_string(), init_apple_pay: is_apple_pay, init_google_pay: is_google_pay, reference: item.router_data.connector_request_reference_id.clone(), }) } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayCreateIntentResponse { // TrustPay's authorization secrets used by client pub secrets: SdkSecretInfo, // Data object to be used for Apple Pay or Google Pay #[serde(flatten)] pub init_result_data: InitResultData, // Unique operation/transaction identifier pub instance_id: String, } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub enum InitResultData { AppleInitResultData(TrustpayApplePayResponse), GoogleInitResultData(TrustpayGooglePayResponse), } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayTransactionInfo { pub country_code: api_models::enums::CountryAlpha2, pub currency_code: api_models::enums::Currency, pub total_price_status: String, pub total_price: StringMajorUnit, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayMerchantInfo { pub merchant_name: Secret<String>, pub merchant_id: Secret<String>, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayAllowedPaymentMethods { #[serde(rename = "type")] pub payment_method_type: String, pub parameters: GpayAllowedMethodsParameters, pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GpayTokenParameters { pub gateway: String, pub gateway_merchant_id: Secret<String>, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GpayTokenizationSpecification { #[serde(rename = "type")] pub token_specification_type: String, pub parameters: GpayTokenParameters, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GpayAllowedMethodsParameters { pub allowed_auth_methods: Vec<String>, pub allowed_card_networks: Vec<String>, pub assurance_details_required: Option<bool>, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayGooglePayResponse { pub merchant_info: GooglePayMerchantInfo, pub allowed_payment_methods: Vec<GooglePayAllowedPaymentMethods>, pub transaction_info: GooglePayTransactionInfo, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct SdkSecretInfo { pub display: Secret<String>, pub payment: Secret<String>, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayApplePayResponse { pub country_code: api_models::enums::CountryAlpha2, pub currency_code: api_models::enums::Currency, pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub total: ApplePayTotalInfo, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayTotalInfo { pub label: String, pub amount: StringMajorUnit, } impl<F> TryFrom< ResponseRouterData< F, TrustpayCreateIntentResponse, PaymentsPreProcessingData, PaymentsResponseData, >, > for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData> { type Error = Error; fn try_from( item: ResponseRouterData< F, TrustpayCreateIntentResponse, PaymentsPreProcessingData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let create_intent_response = item.response.init_result_data.to_owned(); let secrets = item.response.secrets.to_owned(); let instance_id = item.response.instance_id.to_owned(); let pmt = PaymentsPreProcessingData::get_payment_method_type(&item.data.request)?; match (pmt, create_intent_response) { ( enums::PaymentMethodType::ApplePay, InitResultData::AppleInitResultData(apple_pay_response), ) => get_apple_pay_session(instance_id, &secrets, apple_pay_response, item), ( enums::PaymentMethodType::GooglePay, InitResultData::GoogleInitResultData(google_pay_response), ) => get_google_pay_session(instance_id, &secrets, google_pay_response, item), _ => Err(report!(errors::ConnectorError::InvalidWallet)), } } } pub(crate) fn get_apple_pay_session<F, T>( instance_id: String, secrets: &SdkSecretInfo, apple_pay_init_result: TrustpayApplePayResponse, item: ResponseRouterData<F, TrustpayCreateIntentResponse, T, PaymentsResponseData>, ) -> Result<RouterData<F, T, PaymentsResponseData>, error_stack::Report<errors::ConnectorError>> { Ok(RouterData { response: Ok(PaymentsResponseData::PreProcessingResponse { connector_metadata: None, pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(instance_id), session_token: Some(SessionToken::ApplePay(Box::new( api_models::payments::ApplepaySessionTokenResponse { session_token_data: Some( api_models::payments::ApplePaySessionResponse::ThirdPartySdk( api_models::payments::ThirdPartySdkSessionResponse { secrets: secrets.to_owned().into(), }, ), ), payment_request_data: Some(api_models::payments::ApplePayPaymentRequest { country_code: apple_pay_init_result.country_code, currency_code: apple_pay_init_result.currency_code, supported_networks: Some(apple_pay_init_result.supported_networks.clone()), merchant_capabilities: Some( apple_pay_init_result.merchant_capabilities.clone(), ), total: apple_pay_init_result.total.into(), merchant_identifier: None, required_billing_contact_fields: None, required_shipping_contact_fields: None, recurring_payment_request: None, }), connector: "trustpay".to_string(), delayed_session_token: true, sdk_next_action: { api_models::payments::SdkNextAction { next_action: api_models::payments::NextActionCall::Sync, } }, connector_reference_id: None, connector_sdk_public_key: None, connector_merchant_id: None, }, ))), connector_response_reference_id: None, }), // We don't get status from TrustPay but status should be AuthenticationPending by default for session response status: enums::AttemptStatus::AuthenticationPending, ..item.data }) } pub(crate) fn get_google_pay_session<F, T>( instance_id: String, secrets: &SdkSecretInfo, google_pay_init_result: TrustpayGooglePayResponse, item: ResponseRouterData<F, TrustpayCreateIntentResponse, T, PaymentsResponseData>, ) -> Result<RouterData<F, T, PaymentsResponseData>, error_stack::Report<errors::ConnectorError>> { Ok(RouterData { response: Ok(PaymentsResponseData::PreProcessingResponse { connector_metadata: None, pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(instance_id), session_token: Some(SessionToken::GooglePay(Box::new( api_models::payments::GpaySessionTokenResponse::GooglePaySession( api_models::payments::GooglePaySessionResponse { connector: "trustpay".to_string(), delayed_session_token: true, sdk_next_action: { api_models::payments::SdkNextAction { next_action: api_models::payments::NextActionCall::Sync, } }, merchant_info: google_pay_init_result.merchant_info.into(), allowed_payment_methods: google_pay_init_result .allowed_payment_methods .into_iter() .map(Into::into) .collect(), transaction_info: google_pay_init_result.transaction_info.into(), secrets: Some((*secrets).clone().into()), shipping_address_required: false, email_required: false, shipping_address_parameters: api_models::payments::GpayShippingAddressParameters { phone_number_required: false, }, }, ), ))), connector_response_reference_id: None, }), // We don't get status from TrustPay but status should be AuthenticationPending by default for session response status: enums::AttemptStatus::AuthenticationPending, ..item.data }) } impl From<GooglePayTransactionInfo> for api_models::payments::GpayTransactionInfo { fn from(value: GooglePayTransactionInfo) -> Self { Self { country_code: value.country_code, currency_code: value.currency_code, total_price_status: value.total_price_status, total_price: value.total_price, } } } impl From<GooglePayMerchantInfo> for api_models::payments::GpayMerchantInfo { fn from(value: GooglePayMerchantInfo) -> Self { Self { merchant_id: Some(value.merchant_id.expose()), merchant_name: value.merchant_name.expose(), } } } impl From<GooglePayAllowedPaymentMethods> for api_models::payments::GpayAllowedPaymentMethods { fn from(value: GooglePayAllowedPaymentMethods) -> Self { Self { payment_method_type: value.payment_method_type, parameters: value.parameters.into(), tokenization_specification: value.tokenization_specification.into(), } } } impl From<GpayAllowedMethodsParameters> for api_models::payments::GpayAllowedMethodsParameters { fn from(value: GpayAllowedMethodsParameters) -> Self { Self { allowed_auth_methods: value.allowed_auth_methods, allowed_card_networks: value.allowed_card_networks, billing_address_required: None, billing_address_parameters: None, assurance_details_required: value.assurance_details_required, } } } impl From<GpayTokenizationSpecification> for api_models::payments::GpayTokenizationSpecification { fn from(value: GpayTokenizationSpecification) -> Self { Self { token_specification_type: value.token_specification_type, parameters: value.parameters.into(), } } } impl From<GpayTokenParameters> for api_models::payments::GpayTokenParameters { fn from(value: GpayTokenParameters) -> Self { Self { gateway: Some(value.gateway), gateway_merchant_id: Some(value.gateway_merchant_id.expose()), stripe_version: None, stripe_publishable_key: None, public_key: None, protocol_version: None, } } } impl From<SdkSecretInfo> for api_models::payments::SecretInfoToInitiateSdk { fn from(value: SdkSecretInfo) -> Self { Self { display: value.display, payment: Some(value.payment), } } } impl From<ApplePayTotalInfo> for api_models::payments::AmountInfo { fn from(value: ApplePayTotalInfo) -> Self { Self { label: value.label, amount: value.amount, total_type: None, } } } #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayRefundRequestCards { instance_id: String, amount: StringMajorUnit, currency: String, reference: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayRefundRequestBankRedirect { pub merchant_identification: MerchantIdentification, pub payment_information: BankPaymentInformation, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum TrustpayRefundRequest { CardsRefund(Box<TrustpayRefundRequestCards>), BankRedirectRefund(Box<TrustpayRefundRequestBankRedirect>), } impl<F> TryFrom<&TrustpayRouterData<&RefundsRouterData<F>>> for TrustpayRefundRequest { type Error = Error; fn try_from(item: &TrustpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let amount = item.amount.to_owned(); match item.router_data.payment_method { enums::PaymentMethod::BankRedirect => { let auth = TrustpayAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(Self::BankRedirectRefund(Box::new( TrustpayRefundRequestBankRedirect { merchant_identification: MerchantIdentification { project_id: auth.project_id, }, payment_information: BankPaymentInformation { amount: Amount { amount, currency: item.router_data.request.currency.to_string(), }, references: References { merchant_reference: item.router_data.request.refund_id.clone(), }, debtor: None, }, }, ))) } _ => Ok(Self::CardsRefund(Box::new(TrustpayRefundRequestCards { instance_id: item.router_data.request.connector_transaction_id.clone(), amount, currency: item.router_data.request.currency.to_string(), reference: item.router_data.request.refund_id.clone(), }))), } } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardsRefundResponse { pub status: i64, pub description: Option<String>, pub instance_id: String, pub payment_status: String, pub payment_description: Option<String>, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct BankRedirectRefundResponse { pub payment_request_id: i64, pub result_info: ResultInfo, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum RefundResponse { CardsRefund(Box<CardsRefundResponse>), WebhookRefund(Box<WebhookPaymentInformation>), BankRedirectRefund(Box<BankRedirectRefundResponse>), BankRedirectRefundSyncResponse(Box<SyncResponseBankRedirect>), BankRedirectError(Box<ErrorResponseBankRedirect>), } fn handle_cards_refund_response( response: CardsRefundResponse, status_code: u16, ) -> CustomResult<(Option<ErrorResponse>, RefundsResponseData), errors::ConnectorError> { let (refund_status, msg) = get_refund_status(&response.payment_status)?; let error = if msg.is_some() { Some(ErrorResponse { code: response.payment_status, message: msg .clone() .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: msg, status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let refund_response_data = RefundsResponseData { connector_refund_id: response.instance_id, refund_status, }; Ok((error, refund_response_data)) } fn handle_webhooks_refund_response( response: WebhookPaymentInformation, status_code: u16, ) -> CustomResult<(Option<ErrorResponse>, RefundsResponseData), errors::ConnectorError> { let refund_status = enums::RefundStatus::try_from(response.status)?; let error = if utils::is_refund_failure(refund_status) { let reason_info = response.status_reason_information.unwrap_or_default(); Some(ErrorResponse { code: reason_info .reason .code .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), // message vary for the same code, so relying on code alone as it is unique message: reason_info .reason .code .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: reason_info.reason.reject_reason, status_code, attempt_status: None, connector_transaction_id: response.references.payment_request_id.clone(), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let refund_response_data = RefundsResponseData { connector_refund_id: response .references .payment_request_id .ok_or(errors::ConnectorError::MissingConnectorRefundID)?, refund_status, }; Ok((error, refund_response_data)) } fn handle_bank_redirects_refund_response( response: BankRedirectRefundResponse, status_code: u16, ) -> (Option<ErrorResponse>, RefundsResponseData) { let (refund_status, msg) = get_refund_status_from_result_info(response.result_info.result_code); let error = if msg.is_some() { Some(ErrorResponse { code: response.result_info.result_code.to_string(), // message vary for the same code, so relying on code alone as it is unique message: response.result_info.result_code.to_string(), reason: msg.map(|message| message.to_string()), status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let refund_response_data = RefundsResponseData { connector_refund_id: response.payment_request_id.to_string(), refund_status, }; (error, refund_response_data) } fn handle_bank_redirects_refund_sync_response( response: SyncResponseBankRedirect, status_code: u16, ) -> (Option<ErrorResponse>, RefundsResponseData) { let refund_status = enums::RefundStatus::from(response.payment_information.status); let error = if utils::is_refund_failure(refund_status) { let reason_info = response .payment_information .status_reason_information .unwrap_or_default(); Some(ErrorResponse { code: reason_info .reason .code .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), // message vary for the same code, so relying on code alone as it is unique message: reason_info .reason .code .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: reason_info.reason.reject_reason, status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let refund_response_data = RefundsResponseData { connector_refund_id: response.payment_information.references.payment_request_id, refund_status, }; (error, refund_response_data) } fn handle_bank_redirects_refund_sync_error_response( response: ErrorResponseBankRedirect, status_code: u16, ) -> (Option<ErrorResponse>, RefundsResponseData) { let error = Some(ErrorResponse { code: response.payment_result_info.result_code.to_string(), // message vary for the same code, so relying on code alone as it is unique message: response.payment_result_info.result_code.to_string(), reason: response.payment_result_info.additional_info, status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); //unreachable case as we are sending error as Some() let refund_response_data = RefundsResponseData { connector_refund_id: "".to_string(), refund_status: enums::RefundStatus::Failure, }; (error, refund_response_data) } impl<F> TryFrom<RefundsResponseRouterData<F, RefundResponse>> for RefundsRouterData<F> { type Error = Error; fn try_from(item: RefundsResponseRouterData<F, RefundResponse>) -> Result<Self, Self::Error> { let (error, response) = match item.response { RefundResponse::CardsRefund(response) => { handle_cards_refund_response(*response, item.http_code)? } RefundResponse::WebhookRefund(response) => { handle_webhooks_refund_response(*response, item.http_code)? } RefundResponse::BankRedirectRefund(response) => { handle_bank_redirects_refund_response(*response, item.http_code) } RefundResponse::BankRedirectRefundSyncResponse(response) => { handle_bank_redirects_refund_sync_response(*response, item.http_code) } RefundResponse::BankRedirectError(response) => { handle_bank_redirects_refund_sync_error_response(*response, item.http_code) } }; Ok(Self { response: error.map_or_else(|| Ok(response), Err), ..item.data }) } } fn get_refund_status( payment_status: &str, ) -> CustomResult<(enums::RefundStatus, Option<String>), errors::ConnectorError> { let (is_failed, failure_message) = is_payment_failed(payment_status); if payment_status == "000.200.000" { Ok((enums::RefundStatus::Pending, None)) } else if is_failed { Ok(( enums::RefundStatus::Failure, Some(failure_message.to_string()), )) } else if is_payment_successful(payment_status)? { Ok((enums::RefundStatus::Success, None)) } else { Ok((enums::RefundStatus::Pending, None)) } } fn get_refund_status_from_result_info( result_code: i64, ) -> (enums::RefundStatus, Option<&'static str>) { match result_code { 1001000 => (enums::RefundStatus::Success, None), 1130001 => (enums::RefundStatus::Pending, Some("MapiPending")), 1130000 => (enums::RefundStatus::Pending, Some("MapiSuccess")), 1130004 => (enums::RefundStatus::Pending, Some("MapiProcessing")), 1130002 => (enums::RefundStatus::Pending, Some("MapiAnnounced")), 1130003 => (enums::RefundStatus::Pending, Some("MapiAuthorized")), 1130005 => (enums::RefundStatus::Pending, Some("MapiAuthorizedOnly")), 1112008 => (enums::RefundStatus::Failure, Some("InvalidPaymentState")), 1112009 => (enums::RefundStatus::Failure, Some("RefundRejected")), 1122006 => ( enums::RefundStatus::Failure, Some("AccountCurrencyNotAllowed"), ), 1132000 => (enums::RefundStatus::Failure, Some("InvalidMapiRequest")), 1132001 => (enums::RefundStatus::Failure, Some("UnknownAccount")), 1132002 => ( enums::RefundStatus::Failure, Some("MerchantAccountDisabled"), ), 1132003 => (enums::RefundStatus::Failure, Some("InvalidSign")), 1132004 => (enums::RefundStatus::Failure, Some("DisposableBalance")), 1132005 => (enums::RefundStatus::Failure, Some("TransactionNotFound")), 1132006 => (enums::RefundStatus::Failure, Some("UnsupportedTransaction")), 1132007 => (enums::RefundStatus::Failure, Some("GeneralMapiError")), 1132008 => ( enums::RefundStatus::Failure, Some("UnsupportedCurrencyConversion"), ), 1132009 => (enums::RefundStatus::Failure, Some("UnknownMandate")), 1132010 => (enums::RefundStatus::Failure, Some("CanceledMandate")), 1132011 => (enums::RefundStatus::Failure, Some("MissingCid")), 1132012 => (enums::RefundStatus::Failure, Some("MandateAlreadyPaid")), 1132013 => (enums::RefundStatus::Failure, Some("AccountIsTesting")), 1132014 => (enums::RefundStatus::Failure, Some("RequestThrottled")), 1133000 => (enums::RefundStatus::Failure, Some("InvalidAuthentication")), 1133001 => (enums::RefundStatus::Failure, Some("ServiceNotAllowed")), 1133002 => (enums::RefundStatus::Failure, Some("PaymentRequestNotFound")), 1133003 => (enums::RefundStatus::Failure, Some("UnexpectedGateway")), 1133004 => (enums::RefundStatus::Failure, Some("MissingExternalId")), 1152000 => (enums::RefundStatus::Failure, Some("RiskDecline")), _ => (enums::RefundStatus::Pending, None), } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct TrustpayRedirectResponse { pub status: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct Errors { pub code: i64, pub description: String, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct TrustpayErrorResponse { pub status: i64, pub description: Option<String>, pub errors: Option<Vec<Errors>>, pub instance_id: Option<String>, pub payment_description: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum CreditDebitIndicator { Crdt, Dbit, } #[derive(strum::Display, Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum WebhookStatus { Paid, Rejected, Refunded, Chargebacked, #[serde(other)] Unknown, } impl TryFrom<WebhookStatus> for enums::AttemptStatus { type Error = errors::ConnectorError; fn try_from(item: WebhookStatus) -> Result<Self, Self::Error> { match item { WebhookStatus::Paid => Ok(Self::Charged), WebhookStatus::Rejected => Ok(Self::AuthorizationFailed), _ => Err(errors::ConnectorError::WebhookEventTypeNotFound), } } } impl TryFrom<WebhookStatus> for enums::RefundStatus { type Error = errors::ConnectorError; fn try_from(item: WebhookStatus) -> Result<Self, Self::Error> { match item { WebhookStatus::Paid => Ok(Self::Success), WebhookStatus::Refunded => Ok(Self::Success), WebhookStatus::Rejected => Ok(Self::Failure), _ => Err(errors::ConnectorError::WebhookEventTypeNotFound), } } } #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct WebhookReferences { pub merchant_reference: Option<String>, pub payment_id: Option<String>, pub payment_request_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct WebhookAmount { pub amount: FloatMajorUnit, pub currency: enums::Currency, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct WebhookPaymentInformation { pub credit_debit_indicator: CreditDebitIndicator, pub references: WebhookReferences, pub status: WebhookStatus, pub amount: WebhookAmount, pub status_reason_information: Option<StatusReasonInformation>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct TrustpayWebhookResponse { pub payment_information: WebhookPaymentInformation, pub signature: String, } impl From<Errors> for utils::ErrorCodeAndMessage { fn from(error: Errors) -> Self { Self { error_code: error.code.to_string(), error_message: error.description, } } }
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
hyperswitch_connectors::src::connectors::trustpay::transformers
16,285
true
// File: crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs // Module: hyperswitch_connectors::src::connectors::xendit::transformers use std::collections::HashMap; use cards::CardNumber; use common_enums::{enums, Currency}; use common_utils::{pii, request::Method, types::FloatMajorUnit}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ PaymentsAuthorizeData, PaymentsCaptureData, PaymentsPreProcessingData, ResponseId, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors, }; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ get_unimplemented_payment_method_error_message, CardData, PaymentsAuthorizeRequestData, PaymentsSyncRequestData, RouterData as OtherRouterData, }, }; //TODO: Fill the struct with respective fields pub struct XenditRouterData<T> { pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } #[derive(Serialize, Deserialize, Debug)] pub enum PaymentMethodType { CARD, } #[derive(Serialize, Deserialize, Debug)] pub struct ChannelProperties { pub success_return_url: String, pub failure_return_url: String, pub skip_three_d_secure: bool, } #[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] pub enum PaymentMethod { Card(CardPaymentRequest), } #[derive(Serialize, Deserialize, Debug)] pub struct CardPaymentRequest { #[serde(rename = "type")] pub payment_type: PaymentMethodType, pub card: CardInfo, pub reusability: TransactionType, pub reference_id: Secret<String>, } #[derive(Serialize, Deserialize, Debug)] pub struct MandatePaymentRequest { pub amount: FloatMajorUnit, pub currency: Currency, pub capture_method: String, pub payment_method_id: Secret<String>, pub channel_properties: ChannelProperties, } #[derive(Serialize, Deserialize, Debug)] pub struct XenditRedirectionResponse { pub status: PaymentStatus, } #[derive(Serialize, Deserialize, Debug)] pub struct XenditPaymentsCaptureRequest { pub capture_amount: FloatMajorUnit, } #[derive(Serialize, Deserialize, Debug)] pub struct XenditPaymentsRequest { pub amount: FloatMajorUnit, pub currency: Currency, pub capture_method: String, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method: Option<PaymentMethod>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method_id: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub channel_properties: Option<ChannelProperties>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct XenditSplitRoute { #[serde(skip_serializing_if = "Option::is_none")] pub flat_amount: Option<FloatMajorUnit>, #[serde(skip_serializing_if = "Option::is_none")] pub percent_amount: Option<i64>, pub currency: Currency, pub destination_account_id: String, pub reference_id: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct XenditSplitRequest { pub name: String, pub description: String, pub routes: Vec<XenditSplitRoute>, } #[derive(Serialize, Deserialize, Debug)] pub struct XenditSplitRequestData { #[serde(flatten)] pub split_data: XenditSplitRequest, } #[derive(Serialize, Deserialize, Debug)] pub struct XenditSplitResponse { id: String, name: String, description: String, routes: Vec<XenditSplitRoute>, } #[derive(Serialize, Deserialize, Debug)] pub struct CardInfo { pub channel_properties: ChannelProperties, pub card_information: CardInformation, } #[derive(Serialize, Deserialize, Debug)] pub struct CardInformation { pub card_number: CardNumber, pub expiry_month: Secret<String>, pub expiry_year: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub cvv: Option<Secret<String>>, pub cardholder_name: Secret<String>, pub cardholder_email: pii::Email, pub cardholder_phone_number: Secret<String>, } pub mod auth_headers { pub const WITH_SPLIT_RULE: &str = "with-split-rule"; pub const FOR_USER_ID: &str = "for-user-id"; } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TransactionType { OneTimeUse, MultipleUse, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct XenditErrorResponse { pub error_code: String, pub message: String, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaymentStatus { Pending, RequiresAction, Failed, Succeeded, AwaitingCapture, Verified, } #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(untagged)] pub enum XenditResponse { Payment(XenditPaymentResponse), Webhook(XenditWebhookEvent), } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct XenditPaymentResponse { pub id: String, pub status: PaymentStatus, pub actions: Option<Vec<Action>>, pub payment_method: PaymentMethodInfo, pub failure_code: Option<String>, pub reference_id: Secret<String>, pub amount: FloatMajorUnit, pub currency: Currency, } fn map_payment_response_to_attempt_status( response: XenditPaymentResponse, is_auto_capture: bool, ) -> enums::AttemptStatus { match response.status { PaymentStatus::Failed => enums::AttemptStatus::Failure, PaymentStatus::Succeeded | PaymentStatus::Verified => { if is_auto_capture { enums::AttemptStatus::Charged } else { enums::AttemptStatus::Authorized } } PaymentStatus::Pending => enums::AttemptStatus::Pending, PaymentStatus::RequiresAction => enums::AttemptStatus::AuthenticationPending, PaymentStatus::AwaitingCapture => enums::AttemptStatus::Authorized, } } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct XenditCaptureResponse { pub id: String, pub status: PaymentStatus, pub actions: Option<Vec<Action>>, pub payment_method: PaymentMethodInfo, pub failure_code: Option<String>, pub reference_id: Secret<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum MethodType { Get, Post, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Action { pub method: MethodType, pub url: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentMethodInfo { pub id: Secret<String>, } impl TryFrom<XenditRouterData<&PaymentsAuthorizeRouterData>> for XenditPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: XenditRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(card_data) => Ok(Self { capture_method: match item.router_data.request.is_auto_capture()? { true => "AUTOMATIC".to_string(), false => "MANUAL".to_string(), }, currency: item.router_data.request.currency, amount: item.amount, payment_method: Some(PaymentMethod::Card(CardPaymentRequest { payment_type: PaymentMethodType::CARD, reference_id: Secret::new( item.router_data.connector_request_reference_id.clone(), ), card: CardInfo { channel_properties: ChannelProperties { success_return_url: item.router_data.request.get_router_return_url()?, failure_return_url: item.router_data.request.get_router_return_url()?, skip_three_d_secure: !item.router_data.is_three_ds(), }, card_information: CardInformation { card_number: card_data.card_number.clone(), expiry_month: card_data.card_exp_month.clone(), expiry_year: card_data.get_expiry_year_4_digit(), cvv: if card_data.card_cvc.clone().expose().is_empty() { None } else { Some(card_data.card_cvc.clone()) }, cardholder_name: card_data .get_cardholder_name() .or(item.router_data.get_billing_full_name())?, cardholder_email: item .router_data .get_billing_email() .or(item.router_data.request.get_email())?, cardholder_phone_number: item.router_data.get_billing_phone_number()?, }, }, reusability: match item.router_data.request.is_mandate_payment() { true => TransactionType::MultipleUse, false => TransactionType::OneTimeUse, }, })), payment_method_id: None, channel_properties: None, }), PaymentMethodData::MandatePayment => Ok(Self { channel_properties: Some(ChannelProperties { success_return_url: item.router_data.request.get_router_return_url()?, failure_return_url: item.router_data.request.get_router_return_url()?, skip_three_d_secure: true, }), capture_method: match item.router_data.request.is_auto_capture()? { true => "AUTOMATIC".to_string(), false => "MANUAL".to_string(), }, currency: item.router_data.request.currency, amount: item.amount, payment_method_id: Some(Secret::new( item.router_data.request.get_connector_mandate_id()?, )), payment_method: None, }), _ => Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("xendit"), ) .into()), } } } impl TryFrom<XenditRouterData<&PaymentsCaptureRouterData>> for XenditPaymentsCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: XenditRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { Ok(Self { capture_amount: item.amount, }) } } impl<F> TryFrom< ResponseRouterData<F, XenditPaymentResponse, PaymentsAuthorizeData, PaymentsResponseData>, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, XenditPaymentResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = map_payment_response_to_attempt_status( item.response.clone(), item.data.request.is_auto_capture()?, ); let response = if status == enums::AttemptStatus::Failure { Err(ErrorResponse { code: item .response .failure_code .clone() .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: item .response .failure_code .clone() .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: Some( item.response .failure_code .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), ), attempt_status: None, connector_transaction_id: Some(item.response.id.clone()), status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { let charges = match item.data.request.split_payments.as_ref() { Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::MultipleSplits(_), )) => item .data .response .as_ref() .ok() .and_then(|response| match response { PaymentsResponseData::TransactionResponse { charges, .. } => { charges.clone() } _ => None, }), Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::SingleSplit(ref split_data), )) => { let charges = common_types::domain::XenditSplitSubMerchantData { for_user_id: split_data.for_user_id.clone(), }; Some( common_types::payments::ConnectorChargeResponseData::XenditSplitPayment( common_types::payments::XenditChargeResponseData::SingleSplit(charges), ), ) } _ => None, }; Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: match item.response.actions { Some(actions) if !actions.is_empty() => { actions.first().map_or(Box::new(None), |single_action| { Box::new(Some(RedirectForm::Form { endpoint: single_action.url.clone(), method: match single_action.method { MethodType::Get => Method::Get, MethodType::Post => Method::Post, }, form_fields: HashMap::new(), })) }) } _ => Box::new(None), }, mandate_reference: match item.data.request.is_mandate_payment() { true => Box::new(Some(MandateReference { connector_mandate_id: Some(item.response.payment_method.id.expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, })), false => Box::new(None), }, connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( item.response.reference_id.peek().to_string(), ), incremental_authorization_allowed: None, charges, }) }; Ok(Self { status, response, ..item.data }) } } impl<F> TryFrom<ResponseRouterData<F, XenditCaptureResponse, PaymentsCaptureData, PaymentsResponseData>> for RouterData<F, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, XenditCaptureResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = match item.response.status { PaymentStatus::Failed => enums::AttemptStatus::Failure, PaymentStatus::Succeeded | PaymentStatus::Verified => enums::AttemptStatus::Charged, PaymentStatus::Pending => enums::AttemptStatus::Pending, PaymentStatus::RequiresAction => enums::AttemptStatus::AuthenticationPending, PaymentStatus::AwaitingCapture => enums::AttemptStatus::Authorized, }; let response = if status == enums::AttemptStatus::Failure { Err(ErrorResponse { code: item .response .failure_code .clone() .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: item .response .failure_code .clone() .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: Some( item.response .failure_code .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), ), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( item.response.reference_id.peek().to_string(), ), incremental_authorization_allowed: None, charges: None, }) }; Ok(Self { status, response, ..item.data }) } } impl<F> TryFrom< ResponseRouterData<F, XenditSplitResponse, PaymentsPreProcessingData, PaymentsResponseData>, > for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, XenditSplitResponse, PaymentsPreProcessingData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let for_user_id = match item.data.request.split_payments { Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::MultipleSplits(ref split_data), )) => split_data.for_user_id.clone(), _ => None, }; let routes: Vec<common_types::payments::XenditSplitRoute> = item .response .routes .iter() .map(|route| { let required_conversion_type = common_utils::types::FloatMajorUnitForConnector; route .flat_amount .map(|amount| { common_utils::types::AmountConvertor::convert_back( &required_conversion_type, amount, item.data.request.currency.unwrap_or(Currency::USD), ) .map_err(|_| { errors::ConnectorError::RequestEncodingFailedWithReason( "Failed to convert the amount into a major unit".to_owned(), ) }) }) .transpose() .map(|flat_amount| common_types::payments::XenditSplitRoute { flat_amount, percent_amount: route.percent_amount, currency: route.currency, destination_account_id: route.destination_account_id.clone(), reference_id: route.reference_id.clone(), }) }) .collect::<Result<Vec<_>, _>>()?; let charges = common_types::payments::XenditMultipleSplitResponse { split_rule_id: item.response.id, for_user_id, name: item.response.name, description: item.response.description, routes, }; let response = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: Some( common_types::payments::ConnectorChargeResponseData::XenditSplitPayment( common_types::payments::XenditChargeResponseData::MultipleSplits(charges), ), ), }; Ok(Self { response: Ok(response), ..item.data }) } } impl TryFrom<PaymentsSyncResponseRouterData<XenditResponse>> for PaymentsSyncRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: PaymentsSyncResponseRouterData<XenditResponse>) -> Result<Self, Self::Error> { match item.response { XenditResponse::Payment(payment_response) => { let status = map_payment_response_to_attempt_status( payment_response.clone(), item.data.request.is_auto_capture()?, ); let response = if status == enums::AttemptStatus::Failure { Err(ErrorResponse { code: payment_response .failure_code .clone() .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: payment_response .failure_code .clone() .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: Some( payment_response .failure_code .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), ), attempt_status: None, connector_transaction_id: Some(payment_response.id.clone()), status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) }; Ok(Self { status, response, ..item.data }) } XenditResponse::Webhook(webhook_event) => { let status = match webhook_event.event { XenditEventType::PaymentSucceeded | XenditEventType::CaptureSucceeded => { enums::AttemptStatus::Charged } XenditEventType::PaymentAwaitingCapture => enums::AttemptStatus::Authorized, XenditEventType::PaymentFailed | XenditEventType::CaptureFailed => { enums::AttemptStatus::Failure } }; Ok(Self { status, ..item.data }) } } } } impl<T> From<(FloatMajorUnit, T)> for XenditRouterData<T> { fn from((amount, item): (FloatMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } pub struct XenditAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for XenditAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } impl TryFrom<&PaymentsPreProcessingRouterData> for XenditSplitRequestData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> { if let Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::MultipleSplits(ref split_data), )) = item.request.split_payments.clone() { let routes: Vec<XenditSplitRoute> = split_data .routes .iter() .map(|route| { let required_conversion_type = common_utils::types::FloatMajorUnitForConnector; route .flat_amount .map(|amount| { common_utils::types::AmountConvertor::convert( &required_conversion_type, amount, item.request.currency.unwrap_or(Currency::USD), ) .map_err(|_| { errors::ConnectorError::RequestEncodingFailedWithReason( "Failed to convert the amount into a major unit".to_owned(), ) }) }) .transpose() .map(|flat_amount| XenditSplitRoute { flat_amount, percent_amount: route.percent_amount, currency: route.currency, destination_account_id: route.destination_account_id.clone(), reference_id: route.reference_id.clone(), }) }) .collect::<Result<Vec<_>, _>>()?; let split_data = XenditSplitRequest { name: split_data.name.clone(), description: split_data.description.clone(), routes, }; Ok(Self { split_data }) } else { Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Xendit"), ) .into()) } } } //TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct XenditRefundRequest { pub amount: FloatMajorUnit, pub payment_request_id: String, pub reason: String, } impl<F> TryFrom<&XenditRouterData<&RefundsRouterData<F>>> for XenditRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &XenditRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), payment_request_id: item.router_data.request.connector_transaction_id.clone(), reason: "REQUESTED_BY_CUSTOMER".to_string(), }) } } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RefundStatus { RequiresAction, Succeeded, Failed, Pending, Cancelled, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed | RefundStatus::Cancelled => Self::Failure, RefundStatus::Pending | RefundStatus::RequiresAction => Self::Pending, } } } //TODO: Fill the struct with respective fields #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { pub id: String, pub status: RefundStatus, pub amount: FloatMajorUnit, pub currency: String, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize)] pub struct XenditMetadata { pub for_user_id: String, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct XenditWebhookEvent { pub event: XenditEventType, pub data: EventDetails, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct EventDetails { pub id: String, pub payment_request_id: Option<String>, pub amount: FloatMajorUnit, pub currency: String, } #[derive(Debug, Serialize, Deserialize, Clone)] pub enum XenditEventType { #[serde(rename = "payment.succeeded")] PaymentSucceeded, #[serde(rename = "payment.awaiting_capture")] PaymentAwaitingCapture, #[serde(rename = "payment.failed")] PaymentFailed, #[serde(rename = "capture.succeeded")] CaptureSucceeded, #[serde(rename = "capture.failed")] CaptureFailed, }
crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
hyperswitch_connectors::src::connectors::xendit::transformers
6,036
true
// File: crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs // Module: hyperswitch_connectors::src::connectors::authipay::transformers use cards; use common_enums::enums; use common_utils::types::FloatMajorUnit; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils, }; // Type definition for router data with amount pub struct AuthipayRouterData<T> { pub amount: FloatMajorUnit, // Amount in major units (e.g., dollars instead of cents) pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for AuthipayRouterData<T> { fn from((amount, item): (FloatMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } // Basic request/response structs used across multiple operations #[derive(Default, Debug, Serialize, Deserialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Amount { total: FloatMajorUnit, currency: String, #[serde(skip_serializing_if = "Option::is_none")] components: Option<AmountComponents>, } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AmountComponents { subtotal: FloatMajorUnit, } #[derive(Default, Debug, Serialize, Deserialize, Clone, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct ExpiryDate { month: Secret<String>, year: Secret<String>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Card { number: cards::CardNumber, security_code: Secret<String>, expiry_date: ExpiryDate, } #[derive(Default, Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentMethod { payment_card: Card, } #[derive(Default, Debug, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SplitShipment { total_count: i32, final_shipment: bool, } #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthipayPaymentsRequest { request_type: &'static str, transaction_amount: Amount, payment_method: PaymentMethod, // split_shipment: Option<SplitShipment>, // incremental_flag: Option<bool>, } impl TryFrom<&AuthipayRouterData<&PaymentsAuthorizeRouterData>> for AuthipayPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &AuthipayRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { // Check if 3DS is being requested - Authipay doesn't support 3DS if matches!( item.router_data.auth_type, enums::AuthenticationType::ThreeDs ) { return Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("authipay"), ) .into()); } match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let expiry_date = ExpiryDate { month: req_card.card_exp_month.clone(), year: req_card.card_exp_year.clone(), }; let card = Card { number: req_card.card_number.clone(), security_code: req_card.card_cvc.clone(), expiry_date, }; let payment_method = PaymentMethod { payment_card: card }; let transaction_amount = Amount { total: item.amount, currency: item.router_data.request.currency.to_string(), components: None, }; // Determine request type based on capture method let request_type = match item.router_data.request.capture_method { Some(enums::CaptureMethod::Manual) => "PaymentCardPreAuthTransaction", Some(enums::CaptureMethod::Automatic) => "PaymentCardSaleTransaction", Some(enums::CaptureMethod::SequentialAutomatic) => "PaymentCardSaleTransaction", Some(enums::CaptureMethod::ManualMultiple) | Some(enums::CaptureMethod::Scheduled) => { return Err(errors::ConnectorError::NotSupported { message: "Capture method not supported by Authipay".to_string(), connector: "Authipay", } .into()); } None => "PaymentCardSaleTransaction", // Default when not specified }; let request = Self { request_type, transaction_amount, payment_method, }; Ok(request) } _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("authipay"), ) .into()), } } } //TODO: Fill the struct with respective fields // Auth Struct pub struct AuthipayAuthType { pub(super) api_key: Secret<String>, pub(super) api_secret: Secret<String>, } impl TryFrom<&ConnectorAuthType> for AuthipayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, api_secret, .. } => Ok(Self { api_key: api_key.to_owned(), api_secret: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // Transaction Status enum (like Fiserv's FiservPaymentStatus) #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum AuthipayTransactionStatus { Authorized, Captured, Voided, Declined, Failed, #[default] Processing, } impl From<AuthipayTransactionStatus> for enums::AttemptStatus { fn from(item: AuthipayTransactionStatus) -> Self { match item { AuthipayTransactionStatus::Captured => Self::Charged, AuthipayTransactionStatus::Declined | AuthipayTransactionStatus::Failed => { Self::Failure } AuthipayTransactionStatus::Processing => Self::Pending, AuthipayTransactionStatus::Authorized => Self::Authorized, AuthipayTransactionStatus::Voided => Self::Voided, } } } // Transaction Processing Details (like Fiserv's TransactionProcessingDetails) #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthipayTransactionProcessingDetails { pub order_id: String, pub transaction_id: String, } // Gateway Response (like Fiserv's GatewayResponse) #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthipayGatewayResponse { pub transaction_state: AuthipayTransactionStatus, pub transaction_processing_details: AuthipayTransactionProcessingDetails, } // Payment Receipt (like Fiserv's PaymentReceipt) #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthipayPaymentReceipt { pub approved_amount: Amount, pub processor_response_details: Option<Processor>, } // Main Response (like Fiserv's FiservPaymentsResponse) - but flat for JSON deserialization #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthipayPaymentsResponse { #[serde(rename = "type")] response_type: Option<String>, client_request_id: String, api_trace_id: String, ipg_transaction_id: String, order_id: String, transaction_type: String, payment_token: Option<PaymentToken>, transaction_origin: Option<String>, payment_method_details: Option<PaymentMethodDetails>, country: Option<String>, terminal_id: Option<String>, merchant_id: Option<String>, transaction_time: i64, approved_amount: Amount, transaction_amount: Amount, // For payment transactions (SALE) transaction_status: Option<String>, // For refund transactions (RETURN) transaction_result: Option<String>, transaction_state: Option<String>, approval_code: String, scheme_transaction_id: Option<String>, processor: Processor, } impl AuthipayPaymentsResponse { /// Get gateway response (like Fiserv's gateway_response) pub fn gateway_response(&self) -> AuthipayGatewayResponse { AuthipayGatewayResponse { transaction_state: self.get_transaction_status(), transaction_processing_details: AuthipayTransactionProcessingDetails { order_id: self.order_id.clone(), transaction_id: self.ipg_transaction_id.clone(), }, } } /// Get payment receipt (like Fiserv's payment_receipt) pub fn payment_receipt(&self) -> AuthipayPaymentReceipt { AuthipayPaymentReceipt { approved_amount: self.approved_amount.clone(), processor_response_details: Some(self.processor.clone()), } } /// Determine the transaction status based on transaction type and various status fields (like Fiserv) fn get_transaction_status(&self) -> AuthipayTransactionStatus { match self.transaction_type.as_str() { "RETURN" => { // Refund transaction - use transaction_result match self.transaction_result.as_deref() { Some("APPROVED") => AuthipayTransactionStatus::Captured, Some("DECLINED") | Some("FAILED") => AuthipayTransactionStatus::Failed, _ => AuthipayTransactionStatus::Processing, } } "VOID" => { // Void transaction - use transaction_result, fallback to transaction_state match self.transaction_result.as_deref() { Some("APPROVED") => AuthipayTransactionStatus::Voided, Some("DECLINED") | Some("FAILED") => AuthipayTransactionStatus::Failed, Some("PENDING") | Some("PROCESSING") => AuthipayTransactionStatus::Processing, _ => { // Fallback to transaction_state for void operations match self.transaction_state.as_deref() { Some("VOIDED") => AuthipayTransactionStatus::Voided, Some("FAILED") | Some("DECLINED") => AuthipayTransactionStatus::Failed, _ => AuthipayTransactionStatus::Voided, // Default assumption for void requests } } } } _ => { // Payment transaction - prioritize transaction_state over transaction_status match self.transaction_state.as_deref() { Some("AUTHORIZED") => AuthipayTransactionStatus::Authorized, Some("CAPTURED") => AuthipayTransactionStatus::Captured, Some("VOIDED") => AuthipayTransactionStatus::Voided, Some("DECLINED") | Some("FAILED") => AuthipayTransactionStatus::Failed, _ => { // Fallback to transaction_status with transaction_type context match ( self.transaction_type.as_str(), self.transaction_status.as_deref(), ) { // For PREAUTH transactions, "APPROVED" means authorized and awaiting capture ("PREAUTH", Some("APPROVED")) => AuthipayTransactionStatus::Authorized, // For POSTAUTH transactions, "APPROVED" means successfully captured ("POSTAUTH", Some("APPROVED")) => AuthipayTransactionStatus::Captured, // For SALE transactions, "APPROVED" means completed payment ("SALE", Some("APPROVED")) => AuthipayTransactionStatus::Captured, // For VOID transactions, "APPROVED" means successfully voided ("VOID", Some("APPROVED")) => AuthipayTransactionStatus::Voided, // Generic status mappings for other cases (_, Some("APPROVED")) => AuthipayTransactionStatus::Captured, (_, Some("AUTHORIZED")) => AuthipayTransactionStatus::Authorized, (_, Some("DECLINED") | Some("FAILED")) => { AuthipayTransactionStatus::Failed } _ => AuthipayTransactionStatus::Processing, } } } } } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentToken { reusable: Option<bool>, decline_duplicates: Option<bool>, brand: Option<String>, #[serde(rename = "type")] token_type: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentMethodDetails { payment_card: Option<PaymentCardDetails>, payment_method_type: Option<String>, payment_method_brand: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentCardDetails { expiry_date: ExpiryDate, bin: String, last4: String, brand: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Processor { reference_number: Option<String>, authorization_code: Option<String>, response_code: String, response_message: String, avs_response: Option<AvsResponse>, security_code_response: Option<String>, tax_refund_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AvsResponse { street_match: Option<String>, postal_code_match: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, AuthipayPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AuthipayPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { // Get gateway response (like Fiserv pattern) let gateway_resp = item.response.gateway_response(); // Store order_id in connector_metadata for void operations (like Fiserv) let mut metadata = std::collections::HashMap::new(); metadata.insert( "order_id".to_string(), serde_json::Value::String(gateway_resp.transaction_processing_details.order_id.clone()), ); let connector_metadata = Some(serde_json::Value::Object(serde_json::Map::from_iter( metadata, ))); Ok(Self { status: enums::AttemptStatus::from(gateway_resp.transaction_state.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( gateway_resp .transaction_processing_details .transaction_id .clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some( gateway_resp.transaction_processing_details.order_id.clone(), ), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } // Type definition for CaptureRequest #[derive(Debug, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthipayCaptureRequest { request_type: &'static str, transaction_amount: Amount, } impl TryFrom<&AuthipayRouterData<&PaymentsCaptureRouterData>> for AuthipayCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &AuthipayRouterData<&PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { request_type: "PostAuthTransaction", transaction_amount: Amount { total: item.amount, currency: item.router_data.request.currency.to_string(), components: None, }, }) } } // Type definition for VoidRequest #[derive(Debug, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthipayVoidRequest { request_type: &'static str, } impl TryFrom<&AuthipayRouterData<&PaymentsCancelRouterData>> for AuthipayVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( _item: &AuthipayRouterData<&PaymentsCancelRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { request_type: "VoidTransaction", }) } } // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthipayRefundRequest { request_type: &'static str, transaction_amount: Amount, } impl<F> TryFrom<&AuthipayRouterData<&RefundsRouterData<F>>> for AuthipayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &AuthipayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { request_type: "ReturnTransaction", transaction_amount: Amount { total: item.amount.to_owned(), currency: item.router_data.request.currency.to_string(), components: None, }, }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } // Reusing the payments response structure for refunds // because Authipay uses the same endpoint and response format pub type RefundResponse = AuthipayPaymentsResponse; impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = if item.response.transaction_type == "RETURN" { match item.response.transaction_result.as_deref() { Some("APPROVED") => RefundStatus::Succeeded, Some("DECLINED") | Some("FAILED") => RefundStatus::Failed, _ => RefundStatus::Processing, } } else { RefundStatus::Processing }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.ipg_transaction_id.to_string(), refund_status: enums::RefundStatus::from(refund_status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = if item.response.transaction_type == "RETURN" { match item.response.transaction_result.as_deref() { Some("APPROVED") => RefundStatus::Succeeded, Some("DECLINED") | Some("FAILED") => RefundStatus::Failed, _ => RefundStatus::Processing, } } else { RefundStatus::Processing }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.ipg_transaction_id.to_string(), refund_status: enums::RefundStatus::from(refund_status), }), ..item.data }) } } // Error Response structs #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ErrorDetailItem { pub field: String, pub message: String, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ErrorDetails { pub code: Option<String>, pub message: String, pub details: Option<Vec<ErrorDetailItem>>, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthipayErrorResponse { pub client_request_id: Option<String>, pub api_trace_id: Option<String>, pub response_type: Option<String>, #[serde(rename = "type")] pub response_object_type: Option<String>, pub error: ErrorDetails, pub decline_reason_code: Option<String>, } impl From<&AuthipayErrorResponse> for ErrorResponse { fn from(item: &AuthipayErrorResponse) -> Self { Self { status_code: 500, // Default to Internal Server Error, will be overridden by actual HTTP status code: item.error.code.clone().unwrap_or_default(), message: item.error.message.clone(), reason: None, attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, } } }
crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs
hyperswitch_connectors::src::connectors::authipay::transformers
4,611
true
// File: crates/hyperswitch_connectors/src/connectors/juspaythreedsserver/transformers.rs // Module: hyperswitch_connectors::src::connectors::juspaythreedsserver::transformers use common_enums::enums; use common_utils::types::StringMinorUnit; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::PaymentsAuthorizeRequestData, }; //TODO: Fill the struct with respective fields pub struct JuspaythreedsserverRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for JuspaythreedsserverRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { //Todo : use utils to convert the amount to the type of amount that a connector accepts Self { amount, router_data: item, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] pub struct JuspaythreedsserverPaymentsRequest { amount: StringMinorUnit, card: JuspaythreedsserverCard, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct JuspaythreedsserverCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } impl TryFrom<&JuspaythreedsserverRouterData<&PaymentsAuthorizeRouterData>> for JuspaythreedsserverPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &JuspaythreedsserverRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let card = JuspaythreedsserverCard { number: req_card.card_number, expiry_month: req_card.card_exp_month, expiry_year: req_card.card_exp_year, cvc: req_card.card_cvc, complete: item.router_data.request.is_auto_capture()?, }; Ok(Self { amount: item.amount.clone(), card, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } //TODO: Fill the struct with respective fields // Auth Struct pub struct JuspaythreedsserverAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for JuspaythreedsserverAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse //TODO: Append the remaining status flags #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum JuspaythreedsserverPaymentStatus { Succeeded, Failed, #[default] Processing, } impl From<JuspaythreedsserverPaymentStatus> for common_enums::AttemptStatus { fn from(item: JuspaythreedsserverPaymentStatus) -> Self { match item { JuspaythreedsserverPaymentStatus::Succeeded => Self::Charged, JuspaythreedsserverPaymentStatus::Failed => Self::Failure, JuspaythreedsserverPaymentStatus::Processing => Self::Authorizing, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct JuspaythreedsserverPaymentsResponse { status: JuspaythreedsserverPaymentStatus, id: String, } impl<F, T> TryFrom<ResponseRouterData<F, JuspaythreedsserverPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, JuspaythreedsserverPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } //TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct JuspaythreedsserverRefundRequest { pub amount: StringMinorUnit, } impl<F> TryFrom<&JuspaythreedsserverRouterData<&RefundsRouterData<F>>> for JuspaythreedsserverRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &JuspaythreedsserverRouterData<&RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct JuspaythreedsserverErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, }
crates/hyperswitch_connectors/src/connectors/juspaythreedsserver/transformers.rs
hyperswitch_connectors::src::connectors::juspaythreedsserver::transformers
1,851
true
// File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs // Module: hyperswitch_connectors::src::connectors::barclaycard::transformers use base64::Engine; use common_enums::enums; use common_types::payments::ApplePayPredecryptData; use common_utils::{ consts, date_time, ext_traits::ValueExt, pii, types::{SemanticVersion, StringMajorUnit}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{ApplePayWalletData, GooglePayWalletData, PaymentMethodData, WalletData}, router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, ErrorResponse, PaymentMethodToken, RouterData, }, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ authentication::MessageExtensionAttribute, CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSyncData, ResponseId, }, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::{ constants, types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, utils::{ self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, PaymentsSyncRequestData, RouterData as OtherRouterData, }, }; pub struct BarclaycardAuthType { pub(super) api_key: Secret<String>, pub(super) merchant_account: Secret<String>, pub(super) api_secret: Secret<String>, } impl TryFrom<&ConnectorAuthType> for BarclaycardAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } = auth_type { Ok(Self { api_key: api_key.to_owned(), merchant_account: key1.to_owned(), api_secret: api_secret.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } pub struct BarclaycardRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> TryFrom<(StringMajorUnit, T)> for BarclaycardRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardPaymentsRequest { processing_information: ProcessingInformation, payment_information: PaymentInformation, order_information: OrderInformationWithBill, client_reference_information: ClientReferenceInformation, #[serde(skip_serializing_if = "Option::is_none")] consumer_authentication_information: Option<BarclaycardConsumerAuthInformation>, #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProcessingInformation { commerce_indicator: String, capture: Option<bool>, payment_solution: Option<String>, cavv_algorithm: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantDefinedInformation { key: u8, value: String, } #[derive(Debug, Serialize)] pub enum BarclaycardParesStatus { #[serde(rename = "Y")] AuthenticationSuccessful, #[serde(rename = "A")] AuthenticationAttempted, #[serde(rename = "N")] AuthenticationFailed, #[serde(rename = "U")] AuthenticationNotCompleted, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardConsumerAuthInformation { ucaf_collection_indicator: Option<String>, cavv: Option<Secret<String>>, ucaf_authentication_data: Option<Secret<String>>, xid: Option<String>, directory_server_transaction_id: Option<Secret<String>>, specification_version: Option<SemanticVersion>, /// This field specifies the 3ds version pa_specification_version: Option<SemanticVersion>, /// Verification response enrollment status. /// /// This field is supported only on Asia, Middle East, and Africa Gateway. /// /// For external authentication, this field will always be "Y" veres_enrolled: Option<String>, /// Raw electronic commerce indicator (ECI) eci_raw: Option<String>, /// This field is supported only on Asia, Middle East, and Africa Gateway /// Also needed for Credit Mutuel-CIC in France and Mastercard Identity Check transactions /// This field is only applicable for Mastercard and Visa Transactions pares_status: Option<BarclaycardParesStatus>, //This field is used to send the authentication date in yyyyMMDDHHMMSS format authentication_date: Option<String>, /// This field indicates the 3D Secure transaction flow. It is only supported for secure transactions in France. /// The possible values are - CH (Challenge), FD (Frictionless with delegation), FR (Frictionless) effective_authentication_type: Option<EffectiveAuthenticationType>, /// This field indicates the authentication type or challenge presented to the cardholder at checkout. challenge_code: Option<String>, /// This field indicates the reason for payer authentication response status. It is only supported for secure transactions in France. pares_status_reason: Option<String>, /// This field indicates the reason why strong authentication was cancelled. It is only supported for secure transactions in France. challenge_cancel_code: Option<String>, /// This field indicates the score calculated by the 3D Securing platform. It is only supported for secure transactions in France. network_score: Option<u32>, /// This is the transaction ID generated by the access control server. This field is supported only for secure transactions in France. acs_transaction_id: Option<String>, } #[derive(Debug, Serialize)] pub enum EffectiveAuthenticationType { CH, FR, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardPaymentInformation { card: Card, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayPaymentInformation { fluid_data: FluidData, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCard { number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, cryptogram: Option<Secret<String>>, transaction_type: TransactionType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayTokenizedCard { transaction_type: TransactionType, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayTokenPaymentInformation { fluid_data: FluidData, tokenized_card: ApplePayTokenizedCard, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayPaymentInformation { tokenized_card: TokenizedCard, } pub const FLUID_DATA_DESCRIPTOR: &str = "RklEPUNPTU1PTi5BUFBMRS5JTkFQUC5QQVlNRU5U"; #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaymentInformation { Cards(Box<CardPaymentInformation>), GooglePay(Box<GooglePayPaymentInformation>), ApplePay(Box<ApplePayPaymentInformation>), ApplePayToken(Box<ApplePayTokenPaymentInformation>), } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Card { number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, security_code: Secret<String>, #[serde(rename = "type")] card_type: Option<String>, type_selection_indicator: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct FluidData { value: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] descriptor: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformationWithBill { amount_details: Amount, bill_to: Option<BillTo>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Amount { total_amount: StringMajorUnit, currency: api_models::enums::Currency, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BillTo { first_name: Secret<String>, last_name: Secret<String>, address1: Secret<String>, locality: String, administrative_area: Secret<String>, postal_code: Secret<String>, country: enums::CountryAlpha2, email: pii::Email, } fn truncate_string(state: &Secret<String>, max_len: usize) -> Secret<String> { let exposed = state.clone().expose(); let truncated = exposed.get(..max_len).unwrap_or(&exposed); Secret::new(truncated.to_string()) } fn build_bill_to( address_details: &hyperswitch_domain_models::address::AddressDetails, email: pii::Email, ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { let administrative_area = address_details .to_state_code_as_optional() .unwrap_or_else(|_| { address_details .get_state() .ok() .map(|state| truncate_string(state, 20)) }) .ok_or_else(|| errors::ConnectorError::MissingRequiredField { field_name: "billing_address.state", })?; Ok(BillTo { first_name: address_details.get_first_name()?.clone(), last_name: address_details.get_last_name()?.clone(), address1: address_details.get_line1()?.clone(), locality: address_details.get_city()?.clone(), administrative_area, postal_code: address_details.get_zip()?.clone(), country: address_details.get_country()?.to_owned(), email, }) } fn get_barclaycard_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> { match card_network { common_enums::CardNetwork::Visa => Some("001"), common_enums::CardNetwork::Mastercard => Some("002"), common_enums::CardNetwork::AmericanExpress => Some("003"), common_enums::CardNetwork::JCB => Some("007"), common_enums::CardNetwork::DinersClub => Some("005"), common_enums::CardNetwork::Discover => Some("004"), common_enums::CardNetwork::CartesBancaires => Some("006"), common_enums::CardNetwork::UnionPay => Some("062"), //"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024" common_enums::CardNetwork::Maestro => Some("042"), common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay | common_enums::CardNetwork::Star | common_enums::CardNetwork::Accel | common_enums::CardNetwork::Pulse | common_enums::CardNetwork::Nyce => None, } } #[derive(Debug, Serialize)] pub enum PaymentSolution { GooglePay, ApplePay, } #[derive(Debug, Serialize)] pub enum TransactionType { #[serde(rename = "1")] InApp, } impl From<PaymentSolution> for String { fn from(solution: PaymentSolution) -> Self { let payment_solution = match solution { PaymentSolution::GooglePay => "012", PaymentSolution::ApplePay => "001", }; payment_solution.to_string() } } impl From<( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, Option<BillTo>, )> for OrderInformationWithBill { fn from( (item, bill_to): ( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, Option<BillTo>, ), ) -> Self { Self { amount_details: Amount { total_amount: item.amount.clone(), currency: item.router_data.request.currency, }, bill_to, } } } impl TryFrom<( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, Option<PaymentSolution>, Option<String>, )> for ProcessingInformation { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, solution, network): ( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, Option<PaymentSolution>, Option<String>, ), ) -> Result<Self, Self::Error> { let commerce_indicator = solution .as_ref() .map(|pm_solution| match pm_solution { PaymentSolution::ApplePay => network .as_ref() .map(|card_network| match card_network.to_lowercase().as_str() { "amex" => "internet", "discover" => "internet", "mastercard" => "spa", "visa" => "internet", _ => "internet", }) .unwrap_or("internet"), PaymentSolution::GooglePay => "internet", }) .unwrap_or("internet") .to_string(); let cavv_algorithm = Some("2".to_string()); Ok(Self { capture: Some(matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None )), payment_solution: solution.map(String::from), commerce_indicator, cavv_algorithm, }) } } impl TryFrom<( &BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>, Option<PaymentSolution>, Option<String>, )> for ProcessingInformation { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, solution, network): ( &BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>, Option<PaymentSolution>, Option<String>, ), ) -> Result<Self, Self::Error> { let commerce_indicator = get_commerce_indicator(network); let cavv_algorithm = Some("2".to_string()); Ok(Self { capture: Some(matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None )), payment_solution: solution.map(String::from), commerce_indicator, cavv_algorithm, }) } } impl From<&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>> for ClientReferenceInformation { fn from(item: &BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>) -> Self { Self { code: Some(item.router_data.connector_request_reference_id.clone()), } } } impl From<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation { fn from(item: &BarclaycardRouterData<&PaymentsAuthorizeRouterData>) -> Self { Self { code: Some(item.router_data.connector_request_reference_id.clone()), } } } impl From<( &BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>, BillTo, )> for OrderInformationWithBill { fn from( (item, bill_to): ( &BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>, BillTo, ), ) -> Self { Self { amount_details: Amount { total_amount: item.amount.clone(), currency: item.router_data.request.currency, }, bill_to: Some(bill_to), } } } impl From<BarclaycardAuthEnrollmentStatus> for enums::AttemptStatus { fn from(item: BarclaycardAuthEnrollmentStatus) -> Self { match item { BarclaycardAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending, BarclaycardAuthEnrollmentStatus::AuthenticationSuccessful => { Self::AuthenticationSuccessful } BarclaycardAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed, } } } impl From<common_enums::DecoupledAuthenticationType> for EffectiveAuthenticationType { fn from(auth_type: common_enums::DecoupledAuthenticationType) -> Self { match auth_type { common_enums::DecoupledAuthenticationType::Challenge => Self::CH, common_enums::DecoupledAuthenticationType::Frictionless => Self::FR, } } } fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> { let hashmap: std::collections::BTreeMap<String, Value> = serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new()); let mut vector = Vec::new(); let mut iter = 1; for (key, value) in hashmap { vector.push(MerchantDefinedInformation { key: iter, value: format!("{key}={value}"), }); iter += 1; } vector } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientReferenceInformation { code: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ClientProcessorInformation { avs: Option<Avs>, card_verification: Option<CardVerification>, processor: Option<ProcessorResponse>, network_transaction_id: Option<Secret<String>>, approval_code: Option<String>, merchant_advice: Option<MerchantAdvice>, response_code: Option<String>, ach_verification: Option<AchVerification>, system_trace_audit_number: Option<String>, event_status: Option<String>, retrieval_reference_number: Option<String>, consumer_authentication_response: Option<ConsumerAuthenticationResponse>, response_details: Option<String>, transaction_id: Option<Secret<String>>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantAdvice { code: Option<String>, code_raw: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ConsumerAuthenticationResponse { code: Option<String>, code_raw: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AchVerification { result_code_raw: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProcessorResponse { name: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardVerification { result_code: Option<String>, result_code_raw: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientRiskInformation { rules: Option<Vec<ClientRiskInformationRules>>, profile: Option<Profile>, score: Option<Score>, info_codes: Option<InfoCodes>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct InfoCodes { address: Option<Vec<String>>, identity_change: Option<Vec<String>>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Score { factor_codes: Option<Vec<String>>, result: Option<RiskResult>, model_used: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum RiskResult { StringVariant(String), IntVariant(u64), } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Profile { early_decision: Option<String>, name: Option<String>, decision: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct ClientRiskInformationRules { name: Option<Secret<String>>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Avs { code: Option<String>, code_raw: Option<String>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardConsumerAuthValidateResponse { ucaf_collection_indicator: Option<String>, cavv: Option<Secret<String>>, ucaf_authentication_data: Option<Secret<String>>, xid: Option<String>, specification_version: Option<SemanticVersion>, directory_server_transaction_id: Option<Secret<String>>, indicator: Option<String>, } #[derive(Debug, Deserialize, Serialize)] pub struct BarclaycardThreeDSMetadata { three_ds_data: BarclaycardConsumerAuthValidateResponse, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardConsumerAuthInformationEnrollmentResponse { access_token: Option<Secret<String>>, step_up_url: Option<String>, //Added to segregate the three_ds_data in a separate struct #[serde(flatten)] validate_response: BarclaycardConsumerAuthValidateResponse, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BarclaycardAuthEnrollmentStatus { PendingAuthentication, AuthenticationSuccessful, AuthenticationFailed, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientAuthCheckInfoResponse { id: String, client_reference_information: ClientReferenceInformation, consumer_authentication_information: BarclaycardConsumerAuthInformationEnrollmentResponse, status: BarclaycardAuthEnrollmentStatus, error_information: Option<BarclaycardErrorInformation>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardConsumerAuthInformationValidateRequest { authentication_transaction_id: String, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum BarclaycardPreProcessingResponse { ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), ErrorInformation(Box<BarclaycardErrorInformationResponse>), } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardAuthSetupRequest { payment_information: PaymentInformation, client_reference_information: ClientReferenceInformation, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardAuthValidateRequest { payment_information: PaymentInformation, client_reference_information: ClientReferenceInformation, consumer_authentication_information: BarclaycardConsumerAuthInformationValidateRequest, order_information: OrderInformation, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardAuthEnrollmentRequest { payment_information: PaymentInformation, client_reference_information: ClientReferenceInformation, consumer_authentication_information: BarclaycardConsumerAuthInformationRequest, order_information: OrderInformationWithBill, } #[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct BarclaycardRedirectionAuthResponse { pub transaction_id: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardConsumerAuthInformationRequest { return_url: String, reference_id: String, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum BarclaycardPreProcessingRequest { AuthEnrollment(Box<BarclaycardAuthEnrollmentRequest>), AuthValidate(Box<BarclaycardAuthValidateRequest>), } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardConsumerAuthInformationResponse { access_token: String, device_data_collection_url: String, reference_id: String, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientAuthSetupInfoResponse { id: String, client_reference_information: ClientReferenceInformation, consumer_authentication_information: BarclaycardConsumerAuthInformationResponse, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum BarclaycardAuthSetupResponse { ClientAuthSetupInfo(Box<ClientAuthSetupInfoResponse>), ErrorInformation(Box<BarclaycardErrorInformationResponse>), } impl TryFrom<&BarclaycardRouterData<&PaymentsPreProcessingRouterData>> for BarclaycardPreProcessingRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BarclaycardRouterData<&PaymentsPreProcessingRouterData>, ) -> Result<Self, Self::Error> { let client_reference_information = ClientReferenceInformation { code: Some(item.router_data.connector_request_reference_id.clone()), }; let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "payment_method_data", }, )?; let payment_information = match payment_method_data { PaymentMethodData::Card(ccard) => { let card_type = match ccard .card_network .clone() .and_then(get_barclaycard_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; Ok(PaymentInformation::Cards(Box::new( CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: ccard.card_cvc, card_type, type_selection_indicator: Some("1".to_owned()), }, }, ))) } PaymentMethodData::Wallet(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Barclaycard"), )) } }?; let redirect_response = item.router_data.request.redirect_response.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "redirect_response", }, )?; let amount_details = Amount { total_amount: item.amount.clone(), currency: item.router_data.request.currency.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "currency", }, )?, }; match redirect_response.params { Some(param) if !param.clone().peek().is_empty() => { let reference_id = param .clone() .peek() .split_once('=') .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.params.reference_id", })? .1 .to_string(); let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?; let order_information = OrderInformationWithBill { amount_details, bill_to: Some(bill_to), }; Ok(Self::AuthEnrollment(Box::new( BarclaycardAuthEnrollmentRequest { payment_information, client_reference_information, consumer_authentication_information: BarclaycardConsumerAuthInformationRequest { return_url: item .router_data .request .get_complete_authorize_url()?, reference_id, }, order_information, }, ))) } Some(_) | None => { let redirect_payload: BarclaycardRedirectionAuthResponse = redirect_response .payload .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.payload", })? .peek() .clone() .parse_value("BarclaycardRedirectionAuthResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let order_information = OrderInformation { amount_details }; Ok(Self::AuthValidate(Box::new( BarclaycardAuthValidateRequest { payment_information, client_reference_information, consumer_authentication_information: BarclaycardConsumerAuthInformationValidateRequest { authentication_transaction_id: redirect_payload.transaction_id, }, order_information, }, ))) } } } } impl<F> TryFrom< ResponseRouterData< F, BarclaycardPreProcessingResponse, PaymentsPreProcessingData, PaymentsResponseData, >, > for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BarclaycardPreProcessingResponse, PaymentsPreProcessingData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response { BarclaycardPreProcessingResponse::ClientAuthCheckInfo(info_response) => { let status = enums::AttemptStatus::from(info_response.status); let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { let response = Err(get_error_response( &info_response.error_information, &None, &risk_info, Some(status), item.http_code, info_response.id.clone(), )); Ok(Self { status, response, ..item.data }) } else { let connector_response_reference_id = Some( info_response .client_reference_information .code .unwrap_or(info_response.id.clone()), ); let redirection_data = match ( info_response .consumer_authentication_information .access_token, info_response .consumer_authentication_information .step_up_url, ) { (Some(token), Some(step_up_url)) => { Some(RedirectForm::BarclaycardConsumerAuth { access_token: token.expose(), step_up_url, }) } _ => None, }; let three_ds_data = serde_json::to_value( info_response .consumer_authentication_information .validate_response, ) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!({ "three_ds_data": three_ds_data })), network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } BarclaycardPreProcessingResponse::ErrorInformation(error_response) => { let detailed_error_info = error_response .error_information .details .to_owned() .map(|details| { details .iter() .map(|details| format!("{} : {}", details.field, details.reason)) .collect::<Vec<_>>() .join(", ") }); let reason = get_error_reason( error_response.error_information.message, detailed_error_info, None, ); let error_message = error_response.error_information.reason.to_owned(); let response = Err(ErrorResponse { code: error_message .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: error_message .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); Ok(Self { response, status: enums::AttemptStatus::AuthenticationFailed, ..item.data }) } } } } fn extract_score_id(message_extensions: &[MessageExtensionAttribute]) -> Option<u32> { message_extensions.iter().find_map(|attr| { attr.id .ends_with("CB-SCORE") .then(|| { attr.id .split('_') .next() .and_then(|p| p.strip_prefix('A')) .and_then(|s| { s.parse::<u32>().map(Some).unwrap_or_else(|err| { router_env::logger::error!( "Failed to parse score_id from '{}': {}", s, err ); None }) }) .or_else(|| { router_env::logger::error!("Unexpected prefix format in id: {}", attr.id); None }) }) .flatten() }) } impl TryFrom<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for BarclaycardAuthSetupRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => { let card_type = match ccard .card_network .clone() .and_then(get_barclaycard_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; let payment_information = PaymentInformation::Cards(Box::new(CardPaymentInformation { card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: ccard.card_cvc, card_type, type_selection_indicator: Some("1".to_owned()), }, })); let client_reference_information = ClientReferenceInformation::from(item); Ok(Self { payment_information, client_reference_information, }) } PaymentMethodData::Wallet(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Barclaycard"), ) .into()) } } } } impl TryFrom<( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, hyperswitch_domain_models::payment_method_data::Card, )> for BarclaycardPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, ccard): ( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, hyperswitch_domain_models::payment_method_data::Card, ), ) -> Result<Self, Self::Error> { let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = PaymentInformation::try_from(&ccard)?; let processing_information = ProcessingInformation::try_from((item, None, None))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); let pares_status = Some(BarclaycardParesStatus::AuthenticationSuccessful); let consumer_authentication_information = item .router_data .request .authentication_data .as_ref() .map(|authn_data| { let (ucaf_authentication_data, cavv, ucaf_collection_indicator) = if ccard.card_network == Some(common_enums::CardNetwork::Mastercard) { (Some(authn_data.cavv.clone()), None, Some("2".to_string())) } else { (None, Some(authn_data.cavv.clone()), None) }; let authentication_date = date_time::format_date( authn_data.created_at, date_time::DateFormat::YYYYMMDDHHmmss, ) .ok(); let effective_authentication_type = authn_data.authentication_type.map(Into::into); let network_score: Option<u32> = if ccard.card_network == Some(common_enums::CardNetwork::CartesBancaires) { match authn_data.message_extension.as_ref() { Some(secret) => { let exposed_value = secret.clone().expose(); match serde_json::from_value::<Vec<MessageExtensionAttribute>>( exposed_value, ) { Ok(exts) => extract_score_id(&exts), Err(err) => { router_env::logger::error!( "Failed to deserialize message_extension: {:?}", err ); None } } } None => None, } } else { None }; BarclaycardConsumerAuthInformation { pares_status, ucaf_collection_indicator, cavv, ucaf_authentication_data, xid: None, directory_server_transaction_id: authn_data .ds_trans_id .clone() .map(Secret::new), specification_version: authn_data.message_version.clone(), pa_specification_version: authn_data.message_version.clone(), veres_enrolled: Some("Y".to_string()), eci_raw: authn_data.eci.clone(), authentication_date, effective_authentication_type, challenge_code: authn_data.challenge_code.clone(), pares_status_reason: authn_data.challenge_code_reason.clone(), challenge_cancel_code: authn_data.challenge_cancel.clone(), network_score, acs_transaction_id: authn_data.acs_trans_id.clone(), } }); Ok(Self { processing_information, payment_information, order_information, client_reference_information, merchant_defined_information, consumer_authentication_information, }) } } impl TryFrom<( &BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>, hyperswitch_domain_models::payment_method_data::Card, )> for BarclaycardPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, ccard): ( &BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>, hyperswitch_domain_models::payment_method_data::Card, ), ) -> Result<Self, Self::Error> { let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?; let order_information = OrderInformationWithBill::from((item, bill_to)); let payment_information = PaymentInformation::try_from(&ccard)?; let processing_information = ProcessingInformation::try_from((item, None, None))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); let pares_status = Some(BarclaycardParesStatus::AuthenticationSuccessful); let three_ds_info: BarclaycardThreeDSMetadata = item .router_data .request .connector_meta .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "connector_meta", })? .parse_value("BarclaycardThreeDSMetadata") .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata", })?; let consumer_authentication_information = Some(BarclaycardConsumerAuthInformation { pares_status, ucaf_collection_indicator: three_ds_info.three_ds_data.ucaf_collection_indicator, cavv: three_ds_info.three_ds_data.cavv, ucaf_authentication_data: three_ds_info.three_ds_data.ucaf_authentication_data, xid: three_ds_info.three_ds_data.xid, directory_server_transaction_id: three_ds_info .three_ds_data .directory_server_transaction_id, specification_version: three_ds_info.three_ds_data.specification_version.clone(), pa_specification_version: three_ds_info.three_ds_data.specification_version.clone(), veres_enrolled: None, eci_raw: None, authentication_date: None, effective_authentication_type: None, challenge_code: None, pares_status_reason: None, challenge_cancel_code: None, network_score: None, acs_transaction_id: None, }); Ok(Self { processing_information, payment_information, order_information, client_reference_information, merchant_defined_information, consumer_authentication_information, }) } } impl TryFrom<( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, GooglePayWalletData, )> for BarclaycardPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, google_pay_data): ( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, GooglePayWalletData, ), ) -> Result<Self, Self::Error> { let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = PaymentInformation::try_from(&google_pay_data)?; let processing_information = ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { processing_information, payment_information, order_information, client_reference_information, merchant_defined_information, consumer_authentication_information: None, }) } } impl TryFrom<( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, Box<ApplePayPredecryptData>, ApplePayWalletData, )> for BarclaycardPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, apple_pay_data, apple_pay_wallet_data): ( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, Box<ApplePayPredecryptData>, ApplePayWalletData, ), ) -> Result<Self, Self::Error> { let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = ProcessingInformation::try_from((item, Some(PaymentSolution::ApplePay), None))?; let client_reference_information = ClientReferenceInformation::from(item); let expiration_month = apple_pay_data.get_expiry_month().change_context( errors::ConnectorError::InvalidDataFormat { field_name: "expiration_month", }, )?; let expiration_year = apple_pay_data.get_four_digit_expiry_year(); let payment_information = PaymentInformation::ApplePay(Box::new(ApplePayPaymentInformation { tokenized_card: TokenizedCard { number: apple_pay_data.application_primary_account_number, cryptogram: Some(apple_pay_data.payment_data.online_payment_cryptogram), transaction_type: TransactionType::InApp, expiration_year, expiration_month, }, })); let merchant_defined_information = item .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); let ucaf_collection_indicator = match apple_pay_wallet_data .payment_method .network .to_lowercase() .as_str() { "mastercard" => Some("2".to_string()), _ => None, }; Ok(Self { processing_information, payment_information, order_information, client_reference_information, consumer_authentication_information: Some(BarclaycardConsumerAuthInformation { ucaf_collection_indicator, cavv: None, ucaf_authentication_data: None, xid: None, directory_server_transaction_id: None, specification_version: None, pa_specification_version: None, veres_enrolled: None, eci_raw: None, pares_status: None, authentication_date: None, effective_authentication_type: None, challenge_code: None, pares_status_reason: None, challenge_cancel_code: None, network_score: None, acs_transaction_id: None, }), merchant_defined_information, }) } } impl TryFrom<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for BarclaycardPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::GooglePay(google_pay_data) => Self::try_from((item, google_pay_data)), WalletData::ApplePay(apple_pay_data) => { match item.router_data.payment_method_token.clone() { Some(payment_method_token) => match payment_method_token { PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { Self::try_from((item, decrypt_data, apple_pay_data)) } PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!( "Apple Pay", "Manual", "Cybersource" ))?, PaymentMethodToken::PazeDecrypt(_) => { Err(unimplemented_payment_method!("Paze", "Cybersource"))? } PaymentMethodToken::GooglePayDecrypt(_) => { Err(unimplemented_payment_method!("Google Pay", "Cybersource"))? } }, None => { let transaction_type = TransactionType::InApp; let email = item .router_data .get_billing_email() .or(item.router_data.request.get_email())?; let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = ProcessingInformation::try_from(( item, Some(PaymentSolution::ApplePay), Some(apple_pay_data.payment_method.network.clone()), ))?; let client_reference_information = ClientReferenceInformation::from(item); let apple_pay_encrypted_data = apple_pay_data .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", })?; let payment_information = PaymentInformation::ApplePayToken(Box::new( ApplePayTokenPaymentInformation { fluid_data: FluidData { value: Secret::from(apple_pay_encrypted_data.clone()), descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()), }, tokenized_card: ApplePayTokenizedCard { transaction_type }, }, )); let merchant_defined_information = item.router_data.request.metadata.clone().map(|metadata| { convert_metadata_to_merchant_defined_info(metadata) }); let ucaf_collection_indicator = match apple_pay_data .payment_method .network .to_lowercase() .as_str() { "mastercard" => Some("2".to_string()), _ => None, }; Ok(Self { processing_information, payment_information, order_information, client_reference_information, merchant_defined_information, consumer_authentication_information: Some( BarclaycardConsumerAuthInformation { ucaf_collection_indicator, cavv: None, ucaf_authentication_data: None, xid: None, directory_server_transaction_id: None, specification_version: None, pa_specification_version: None, veres_enrolled: None, eci_raw: None, pares_status: None, authentication_date: None, effective_authentication_type: None, challenge_code: None, pares_status_reason: None, challenge_cancel_code: None, network_score: None, acs_transaction_id: None, }, ), }) } } } WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPayRedirect(_) | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::RevolutPay(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::AmazonPay(_) | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Barclaycard"), ) .into()), }, PaymentMethodData::MandatePayment | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Barclaycard"), ) .into()) } } } } impl<F> TryFrom< ResponseRouterData< F, BarclaycardAuthSetupResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BarclaycardAuthSetupResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response { BarclaycardAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(Some(RedirectForm::BarclaycardAuthSetup { access_token: info_response .consumer_authentication_information .access_token, ddc_url: info_response .consumer_authentication_information .device_data_collection_url, reference_id: info_response .consumer_authentication_information .reference_id, })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( info_response .client_reference_information .code .unwrap_or(info_response.id.clone()), ), incremental_authorization_allowed: None, charges: None, }), ..item.data }), BarclaycardAuthSetupResponse::ErrorInformation(error_response) => { let detailed_error_info = error_response .error_information .details .to_owned() .map(|details| { details .iter() .map(|details| format!("{} : {}", details.field, details.reason)) .collect::<Vec<_>>() .join(", ") }); let reason = get_error_reason( error_response.error_information.message, detailed_error_info, None, ); let error_message = error_response.error_information.reason; Ok(Self { response: Err(ErrorResponse { code: error_message .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: error_message.unwrap_or( hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string(), ), reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), status: enums::AttemptStatus::AuthenticationFailed, ..item.data }) } } } } impl TryFrom<&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>> for BarclaycardPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "payment_method_data", }, )?; match payment_method_data { PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), PaymentMethodData::Wallet(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Barclaycard"), ) .into()) } } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BarclaycardPaymentStatus { Authorized, Succeeded, Failed, Voided, Reversed, Pending, Declined, Rejected, Challenge, AuthorizedPendingReview, AuthorizedRiskDeclined, Transmitted, InvalidRequest, ServerError, PendingAuthentication, PendingReview, Accepted, Cancelled, StatusNotReceived, //PartialAuthorized, not being consumed yet. } fn map_barclaycard_attempt_status( (status, auto_capture): (BarclaycardPaymentStatus, bool), ) -> enums::AttemptStatus { match status { BarclaycardPaymentStatus::Authorized | BarclaycardPaymentStatus::AuthorizedPendingReview => { if auto_capture { // Because Barclaycard will return Payment Status as Authorized even in AutoCapture Payment enums::AttemptStatus::Charged } else { enums::AttemptStatus::Authorized } } BarclaycardPaymentStatus::Pending => { if auto_capture { enums::AttemptStatus::Charged } else { enums::AttemptStatus::Pending } } BarclaycardPaymentStatus::Succeeded | BarclaycardPaymentStatus::Transmitted => { enums::AttemptStatus::Charged } BarclaycardPaymentStatus::Voided | BarclaycardPaymentStatus::Reversed | BarclaycardPaymentStatus::Cancelled => enums::AttemptStatus::Voided, BarclaycardPaymentStatus::Failed | BarclaycardPaymentStatus::Declined | BarclaycardPaymentStatus::AuthorizedRiskDeclined | BarclaycardPaymentStatus::InvalidRequest | BarclaycardPaymentStatus::Rejected | BarclaycardPaymentStatus::ServerError => enums::AttemptStatus::Failure, BarclaycardPaymentStatus::PendingAuthentication => { enums::AttemptStatus::AuthenticationPending } BarclaycardPaymentStatus::PendingReview | BarclaycardPaymentStatus::StatusNotReceived | BarclaycardPaymentStatus::Challenge | BarclaycardPaymentStatus::Accepted => enums::AttemptStatus::Pending, } } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum BarclaycardPaymentsResponse { ClientReferenceInformation(Box<BarclaycardClientReferenceResponse>), ErrorInformation(Box<BarclaycardErrorInformationResponse>), } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardClientReferenceResponse { id: String, status: Option<BarclaycardPaymentStatus>, client_reference_information: ClientReferenceInformation, processor_information: Option<ClientProcessorInformation>, processing_information: Option<ProcessingInformationResponse>, payment_information: Option<PaymentInformationResponse>, payment_insights_information: Option<PaymentInsightsInformation>, risk_information: Option<ClientRiskInformation>, error_information: Option<BarclaycardErrorInformation>, issuer_information: Option<IssuerInformation>, sender_information: Option<SenderInformation>, payment_account_information: Option<PaymentAccountInformation>, reconciliation_id: Option<String>, consumer_authentication_information: Option<ConsumerAuthenticationInformation>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ConsumerAuthenticationInformation { eci_raw: Option<String>, eci: Option<String>, acs_transaction_id: Option<String>, cavv: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct SenderInformation { payment_information: Option<PaymentInformationResponse>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentInsightsInformation { response_insights: Option<ResponseInsights>, rule_results: Option<RuleResults>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ResponseInsights { category_code: Option<String>, category: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RuleResults { id: Option<String>, decision: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentInformationResponse { tokenized_card: Option<CardResponseObject>, customer: Option<CustomerResponseObject>, card: Option<CardResponseObject>, scheme: Option<String>, bin: Option<String>, account_type: Option<String>, issuer: Option<String>, bin_country: Option<enums::CountryAlpha2>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CustomerResponseObject { customer_id: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentAccountInformation { card: Option<PaymentAccountCardInformation>, features: Option<PaymentAccountFeatureInformation>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentAccountFeatureInformation { health_card: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentAccountCardInformation { #[serde(rename = "type")] card_type: Option<String>, hashed_number: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProcessingInformationResponse { payment_solution: Option<String>, commerce_indicator: Option<String>, commerce_indicator_label: Option<String>, ecommerce_indicator: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct IssuerInformation { country: Option<enums::CountryAlpha2>, discretionary_data: Option<String>, country_specific_discretionary_data: Option<String>, response_code: Option<String>, pin_request_indicator: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardResponseObject { suffix: Option<String>, prefix: Option<String>, expiration_month: Option<Secret<String>>, expiration_year: Option<Secret<String>>, #[serde(rename = "type")] card_type: Option<String>, } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardErrorInformationResponse { id: String, error_information: BarclaycardErrorInformation, } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct BarclaycardErrorInformation { reason: Option<String>, message: Option<String>, details: Option<Vec<Details>>, } fn map_error_response<F, T>( error_response: &BarclaycardErrorInformationResponse, item: ResponseRouterData<F, BarclaycardPaymentsResponse, T, PaymentsResponseData>, transaction_status: Option<enums::AttemptStatus>, ) -> RouterData<F, T, PaymentsResponseData> { let detailed_error_info = error_response .error_information .details .as_ref() .map(|details| { details .iter() .map(|details| format!("{} : {}", details.field, details.reason)) .collect::<Vec<_>>() .join(", ") }); let reason = get_error_reason( error_response.error_information.message.clone(), detailed_error_info, None, ); let response = Err(ErrorResponse { code: error_response .error_information .reason .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: error_response .error_information .reason .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); match transaction_status { Some(status) => RouterData { response, status, ..item.data }, None => RouterData { response, ..item.data }, } } fn get_error_response_if_failure( (info_response, status, http_code): ( &BarclaycardClientReferenceResponse, enums::AttemptStatus, u16, ), ) -> Option<ErrorResponse> { if utils::is_payment_failure(status) { Some(get_error_response( &info_response.error_information, &info_response.processor_information, &info_response.risk_information, Some(status), http_code, info_response.id.clone(), )) } else { None } } fn get_payment_response( (info_response, status, http_code): ( &BarclaycardClientReferenceResponse, enums::AttemptStatus, u16, ), ) -> Result<PaymentsResponseData, Box<ErrorResponse>> { let error_response = get_error_response_if_failure((info_response, status, http_code)); match error_response { Some(error) => Err(Box::new(error)), None => Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( info_response .client_reference_information .code .clone() .unwrap_or(info_response.id.clone()), ), incremental_authorization_allowed: None, charges: None, }), } } impl<F> TryFrom< ResponseRouterData< F, BarclaycardPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BarclaycardPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response { BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => { let status = map_barclaycard_attempt_status(( info_response .status .clone() .unwrap_or(BarclaycardPaymentStatus::StatusNotReceived), item.data.request.is_auto_capture()?, )); let response = get_payment_response((&info_response, status, item.http_code)) .map_err(|err| *err); let connector_response = match item.data.payment_method { common_enums::PaymentMethod::Card => info_response .processor_information .as_ref() .and_then(|processor_information| { info_response .consumer_authentication_information .as_ref() .map(|consumer_auth_information| { convert_to_additional_payment_method_connector_response( processor_information, consumer_auth_information, ) }) }) .map(ConnectorResponseData::with_additional_payment_method_data), common_enums::PaymentMethod::CardRedirect | common_enums::PaymentMethod::PayLater | common_enums::PaymentMethod::Wallet | common_enums::PaymentMethod::BankRedirect | common_enums::PaymentMethod::BankTransfer | common_enums::PaymentMethod::Crypto | common_enums::PaymentMethod::BankDebit | common_enums::PaymentMethod::Reward | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::MobilePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher | common_enums::PaymentMethod::OpenBanking | common_enums::PaymentMethod::GiftCard => None, }; Ok(Self { status, response, connector_response, ..item.data }) } BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => { Ok(map_error_response( &error_response.clone(), item, Some(enums::AttemptStatus::Failure), )) } } } } fn convert_to_additional_payment_method_connector_response( processor_information: &ClientProcessorInformation, consumer_authentication_information: &ConsumerAuthenticationInformation, ) -> AdditionalPaymentMethodConnectorResponse { let payment_checks = Some(serde_json::json!({ "avs_response": processor_information.avs, "card_verification": processor_information.card_verification, "approval_code": processor_information.approval_code, "consumer_authentication_response": processor_information.consumer_authentication_response, "cavv": consumer_authentication_information.cavv, "eci": consumer_authentication_information.eci, "eci_raw": consumer_authentication_information.eci_raw, })); let authentication_data = Some(serde_json::json!({ "retrieval_reference_number": processor_information.retrieval_reference_number, "acs_transaction_id": consumer_authentication_information.acs_transaction_id, "system_trace_audit_number": processor_information.system_trace_audit_number, })); AdditionalPaymentMethodConnectorResponse::Card { authentication_data, payment_checks, card_network: None, domestic_network: None, } } impl<F> TryFrom< ResponseRouterData< F, BarclaycardPaymentsResponse, PaymentsCaptureData, PaymentsResponseData, >, > for RouterData<F, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BarclaycardPaymentsResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response { BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => { let status = map_barclaycard_attempt_status(( info_response .status .clone() .unwrap_or(BarclaycardPaymentStatus::StatusNotReceived), true, )); let response = get_payment_response((&info_response, status, item.http_code)) .map_err(|err| *err); Ok(Self { status, response, ..item.data }) } BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => { Ok(map_error_response(&error_response.clone(), item, None)) } } } } impl<F> TryFrom< ResponseRouterData< F, BarclaycardPaymentsResponse, PaymentsCancelData, PaymentsResponseData, >, > for RouterData<F, PaymentsCancelData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BarclaycardPaymentsResponse, PaymentsCancelData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response { BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => { let status = map_barclaycard_attempt_status(( info_response .status .clone() .unwrap_or(BarclaycardPaymentStatus::StatusNotReceived), false, )); let response = get_payment_response((&info_response, status, item.http_code)) .map_err(|err| *err); Ok(Self { status, response, ..item.data }) } BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => { Ok(map_error_response(&error_response.clone(), item, None)) } } } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardTransactionResponse { id: String, application_information: ApplicationInformation, client_reference_information: Option<ClientReferenceInformation>, processor_information: Option<ClientProcessorInformation>, processing_information: Option<ProcessingInformationResponse>, payment_information: Option<PaymentInformationResponse>, payment_insights_information: Option<PaymentInsightsInformation>, error_information: Option<BarclaycardErrorInformation>, fraud_marking_information: Option<FraudMarkingInformation>, risk_information: Option<ClientRiskInformation>, reconciliation_id: Option<String>, consumer_authentication_information: Option<ConsumerAuthenticationInformation>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct FraudMarkingInformation { reason: Option<String>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplicationInformation { status: Option<BarclaycardPaymentStatus>, } impl<F> TryFrom< ResponseRouterData< F, BarclaycardTransactionResponse, PaymentsSyncData, PaymentsResponseData, >, > for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BarclaycardTransactionResponse, PaymentsSyncData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response.application_information.status { Some(app_status) => { let status = map_barclaycard_attempt_status(( app_status, item.data.request.is_auto_capture()?, )); let connector_response = match item.data.payment_method { common_enums::PaymentMethod::Card => item .response .processor_information .as_ref() .and_then(|processor_information| { item.response .consumer_authentication_information .as_ref() .map(|consumer_auth_information| { convert_to_additional_payment_method_connector_response( processor_information, consumer_auth_information, ) }) }) .map(ConnectorResponseData::with_additional_payment_method_data), common_enums::PaymentMethod::CardRedirect | common_enums::PaymentMethod::PayLater | common_enums::PaymentMethod::Wallet | common_enums::PaymentMethod::BankRedirect | common_enums::PaymentMethod::BankTransfer | common_enums::PaymentMethod::Crypto | common_enums::PaymentMethod::BankDebit | common_enums::PaymentMethod::Reward | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::MobilePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher | common_enums::PaymentMethod::OpenBanking | common_enums::PaymentMethod::GiftCard => None, }; let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { Ok(Self { response: Err(get_error_response( &item.response.error_information, &item.response.processor_information, &risk_info, Some(status), item.http_code, item.response.id.clone(), )), status: enums::AttemptStatus::Failure, connector_response, ..item.data }) } else { Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item .response .client_reference_information .map(|cref| cref.code) .unwrap_or(Some(item.response.id)), incremental_authorization_allowed: None, charges: None, }), connector_response, ..item.data }) } } None => Ok(Self { status: item.data.status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, charges: None, }), ..item.data }), } } } impl<F> TryFrom< ResponseRouterData< F, BarclaycardPaymentsResponse, CompleteAuthorizeData, PaymentsResponseData, >, > for RouterData<F, CompleteAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BarclaycardPaymentsResponse, CompleteAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response { BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => { let status = map_barclaycard_attempt_status(( info_response .status .clone() .unwrap_or(BarclaycardPaymentStatus::StatusNotReceived), item.data.request.is_auto_capture()?, )); let response = get_payment_response((&info_response, status, item.http_code)) .map_err(|err| *err); let connector_response = info_response .processor_information .as_ref() .map(AdditionalPaymentMethodConnectorResponse::from) .map(ConnectorResponseData::with_additional_payment_method_data); Ok(Self { status, response, connector_response, ..item.data }) } BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => { Ok(map_error_response(&error_response.clone(), item, None)) } } } } impl From<&ClientProcessorInformation> for AdditionalPaymentMethodConnectorResponse { fn from(processor_information: &ClientProcessorInformation) -> Self { let payment_checks = Some( serde_json::json!({"avs_response": processor_information.avs, "card_verification": processor_information.card_verification}), ); Self::Card { authentication_data: None, payment_checks, card_network: None, domestic_network: None, } } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformation { amount_details: Amount, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardCaptureRequest { order_information: OrderInformation, client_reference_information: ClientReferenceInformation, #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } impl TryFrom<&BarclaycardRouterData<&PaymentsCaptureRouterData>> for BarclaycardCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( value: &BarclaycardRouterData<&PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { let merchant_defined_information = value .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { order_information: OrderInformation { amount_details: Amount { total_amount: value.amount.to_owned(), currency: value.router_data.request.currency, }, }, client_reference_information: ClientReferenceInformation { code: Some(value.router_data.connector_request_reference_id.clone()), }, merchant_defined_information, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardVoidRequest { client_reference_information: ClientReferenceInformation, reversal_information: ReversalInformation, #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, // The connector documentation does not mention the merchantDefinedInformation field for Void requests. But this has been still added because it works! } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ReversalInformation { amount_details: Amount, reason: String, } impl TryFrom<&BarclaycardRouterData<&PaymentsCancelRouterData>> for BarclaycardVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( value: &BarclaycardRouterData<&PaymentsCancelRouterData>, ) -> Result<Self, Self::Error> { let merchant_defined_information = value .router_data .request .metadata .clone() .map(convert_metadata_to_merchant_defined_info); Ok(Self { client_reference_information: ClientReferenceInformation { code: Some(value.router_data.connector_request_reference_id.clone()), }, reversal_information: ReversalInformation { amount_details: Amount { total_amount: value.amount.to_owned(), currency: value.router_data.request.currency.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "Currency", }, )?, }, reason: value .router_data .request .cancellation_reason .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "Cancellation Reason", })?, }, merchant_defined_information, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardRefundRequest { order_information: OrderInformation, client_reference_information: ClientReferenceInformation, } impl<F> TryFrom<&BarclaycardRouterData<&RefundsRouterData<F>>> for BarclaycardRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &BarclaycardRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { order_information: OrderInformation { amount_details: Amount { total_amount: item.amount.clone(), currency: item.router_data.request.currency, }, }, client_reference_information: ClientReferenceInformation { code: Some(item.router_data.request.refund_id.clone()), }, }) } } impl From<BarclaycardRefundResponse> for enums::RefundStatus { fn from(item: BarclaycardRefundResponse) -> Self { let error_reason = item .error_information .and_then(|error_info| error_info.reason); match item.status { BarclaycardRefundStatus::Succeeded | BarclaycardRefundStatus::Transmitted => { Self::Success } BarclaycardRefundStatus::Cancelled | BarclaycardRefundStatus::Failed | BarclaycardRefundStatus::Voided => Self::Failure, BarclaycardRefundStatus::Pending => Self::Pending, BarclaycardRefundStatus::TwoZeroOne => { if error_reason == Some("PROCESSOR_DECLINED".to_string()) { Self::Failure } else { Self::Pending } } } } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardRefundResponse { id: String, status: BarclaycardRefundStatus, error_information: Option<BarclaycardErrorInformation>, } impl TryFrom<RefundsResponseRouterData<Execute, BarclaycardRefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, BarclaycardRefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.clone()); let response = if utils::is_refund_failure(refund_status) { Err(get_error_response( &item.response.error_information, &None, &None, None, item.http_code, item.response.id, )) } else { Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }) }; Ok(Self { response, ..item.data }) } } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BarclaycardRefundStatus { Succeeded, Transmitted, Failed, Pending, Voided, Cancelled, #[serde(rename = "201")] TwoZeroOne, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RsyncApplicationInformation { status: Option<BarclaycardRefundStatus>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardRsyncResponse { id: String, application_information: Option<RsyncApplicationInformation>, error_information: Option<BarclaycardErrorInformation>, } impl TryFrom<RefundsResponseRouterData<RSync, BarclaycardRsyncResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, BarclaycardRsyncResponse>, ) -> Result<Self, Self::Error> { let response = match item .response .application_information .and_then(|application_information| application_information.status) { Some(status) => { let error_reason = item .response .error_information .clone() .and_then(|error_info| error_info.reason); let refund_status = match status { BarclaycardRefundStatus::Succeeded | BarclaycardRefundStatus::Transmitted => { enums::RefundStatus::Success } BarclaycardRefundStatus::Cancelled | BarclaycardRefundStatus::Failed | BarclaycardRefundStatus::Voided => enums::RefundStatus::Failure, BarclaycardRefundStatus::Pending => enums::RefundStatus::Pending, BarclaycardRefundStatus::TwoZeroOne => { if error_reason == Some("PROCESSOR_DECLINED".to_string()) { enums::RefundStatus::Failure } else { enums::RefundStatus::Pending } } }; if utils::is_refund_failure(refund_status) { if status == BarclaycardRefundStatus::Voided { Err(get_error_response( &Some(BarclaycardErrorInformation { message: Some(constants::REFUND_VOIDED.to_string()), reason: Some(constants::REFUND_VOIDED.to_string()), details: None, }), &None, &None, None, item.http_code, item.response.id.clone(), )) } else { Err(get_error_response( &item.response.error_information, &None, &None, None, item.http_code, item.response.id.clone(), )) } } else { Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }) } } None => Ok(RefundsResponseData { connector_refund_id: item.response.id.clone(), refund_status: match item.data.response { Ok(response) => response.refund_status, Err(_) => common_enums::RefundStatus::Pending, }, }), }; Ok(Self { response, ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardStandardErrorResponse { pub error_information: Option<ErrorInformation>, pub status: Option<String>, pub message: Option<String>, pub reason: Option<String>, pub details: Option<Vec<Details>>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BarclaycardServerErrorResponse { pub status: Option<String>, pub message: Option<String>, pub reason: Option<Reason>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum Reason { SystemError, ServerTimeout, ServiceTimeout, } #[derive(Debug, Deserialize, Serialize)] pub struct BarclaycardAuthenticationErrorResponse { pub response: AuthenticationErrorInformation, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum BarclaycardErrorResponse { AuthenticationError(BarclaycardAuthenticationErrorResponse), StandardError(BarclaycardStandardErrorResponse), } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct Details { pub field: String, pub reason: String, } #[derive(Debug, Default, Deserialize, Serialize)] pub struct ErrorInformation { pub message: String, pub reason: String, pub details: Option<Vec<Details>>, } #[derive(Debug, Default, Deserialize, Serialize)] pub struct AuthenticationErrorInformation { pub rmsg: String, } fn get_error_response( error_data: &Option<BarclaycardErrorInformation>, processor_information: &Option<ClientProcessorInformation>, risk_information: &Option<ClientRiskInformation>, attempt_status: Option<enums::AttemptStatus>, status_code: u16, transaction_id: String, ) -> ErrorResponse { let avs_message = risk_information .clone() .map(|client_risk_information| { client_risk_information.rules.map(|rules| { rules .iter() .map(|risk_info| { risk_info.name.clone().map_or("".to_string(), |name| { format!(" , {}", name.clone().expose()) }) }) .collect::<Vec<String>>() .join("") }) }) .unwrap_or(Some("".to_string())); let detailed_error_info = error_data.to_owned().and_then(|error_info| { error_info.details.map(|error_details| { error_details .iter() .map(|details| format!("{} : {}", details.field, details.reason)) .collect::<Vec<_>>() .join(", ") }) }); let network_decline_code = processor_information .as_ref() .and_then(|info| info.response_code.clone()); let network_advice_code = processor_information.as_ref().and_then(|info| { info.merchant_advice .as_ref() .and_then(|merchant_advice| merchant_advice.code_raw.clone()) }); let reason = get_error_reason( error_data .clone() .and_then(|error_details| error_details.message), detailed_error_info, avs_message, ); let error_message = error_data .clone() .and_then(|error_details| error_details.reason); ErrorResponse { code: error_message .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), message: error_message .clone() .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), reason, status_code, attempt_status, connector_transaction_id: Some(transaction_id.clone()), network_advice_code, network_decline_code, network_error_message: None, connector_metadata: None, } } impl TryFrom<&hyperswitch_domain_models::payment_method_data::Card> for PaymentInformation { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( ccard: &hyperswitch_domain_models::payment_method_data::Card, ) -> Result<Self, Self::Error> { let card_type = match ccard .card_network .clone() .and_then(get_barclaycard_card_type) { Some(card_network) => Some(card_network.to_string()), None => ccard.get_card_issuer().ok().map(String::from), }; Ok(Self::Cards(Box::new(CardPaymentInformation { card: Card { number: ccard.card_number.clone(), expiration_month: ccard.card_exp_month.clone(), expiration_year: ccard.card_exp_year.clone(), security_code: ccard.card_cvc.clone(), card_type, type_selection_indicator: Some("1".to_owned()), }, }))) } } impl TryFrom<&GooglePayWalletData> for PaymentInformation { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(google_pay_data: &GooglePayWalletData) -> Result<Self, Self::Error> { Ok(Self::GooglePay(Box::new(GooglePayPaymentInformation { fluid_data: FluidData { value: Secret::from( consts::BASE64_ENGINE.encode( google_pay_data .tokenization_data .get_encrypted_google_pay_token() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "gpay wallet_token", })? .clone(), ), ), descriptor: None, }, }))) } } fn get_commerce_indicator(network: Option<String>) -> String { match network { Some(card_network) => match card_network.to_lowercase().as_str() { "amex" => "aesk", "discover" => "dipb", "mastercard" => "spa", "visa" => "internet", _ => "internet", }, None => "internet", } .to_string() } pub fn get_error_reason( error_info: Option<String>, detailed_error_info: Option<String>, avs_error_info: Option<String>, ) -> Option<String> { match (error_info, detailed_error_info, avs_error_info) { (Some(message), Some(details), Some(avs_message)) => Some(format!( "{message}, detailed_error_information: {details}, avs_message: {avs_message}", )), (Some(message), Some(details), None) => { Some(format!("{message}, detailed_error_information: {details}")) } (Some(message), None, Some(avs_message)) => { Some(format!("{message}, avs_message: {avs_message}")) } (None, Some(details), Some(avs_message)) => { Some(format!("{details}, avs_message: {avs_message}")) } (Some(message), None, None) => Some(message), (None, Some(details), None) => Some(details), (None, None, Some(avs_message)) => Some(avs_message), (None, None, None) => None, } }
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
hyperswitch_connectors::src::connectors::barclaycard::transformers
20,783
true
// File: crates/hyperswitch_connectors/src/connectors/santander/transformers.rs // Module: hyperswitch_connectors::src::connectors::santander::transformers use std::collections::HashMap; use api_models::payments::{QrCodeInformation, VoucherNextStepData}; use common_enums::{enums, AttemptStatus}; use common_utils::{ errors::CustomResult, ext_traits::{ByteSliceExt, Encode}, id_type, request::Method, types::{AmountConvertor, FloatMajorUnit, StringMajorUnit, StringMajorUnitForConnector}, }; use crc::{Algorithm, Crc}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankTransferData, PaymentMethodData, VoucherData}, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors, }; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; use time::OffsetDateTime; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{self as connector_utils, QrImage, RouterData as _}, }; const CRC_16_CCITT_FALSE: Algorithm<u16> = Algorithm { width: 16, poly: 0x1021, init: 0xFFFF, refin: false, refout: false, xorout: 0x0000, check: 0x29B1, residue: 0x0000, }; type Error = error_stack::Report<errors::ConnectorError>; pub struct SantanderRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for SantanderRouterData<T> { fn from((amount, item): (StringMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SantanderMetadataObject { pub pix_key: Secret<String>, pub expiration_time: i32, pub cpf: Secret<String>, pub merchant_city: String, pub merchant_name: String, pub workspace_id: String, pub covenant_code: String, // max_size : 9 } impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for SantanderMetadataObject { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( meta_data: &Option<common_utils::pii::SecretSerdeValue>, ) -> Result<Self, Self::Error> { let metadata = connector_utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata", })?; Ok(metadata) } } pub fn format_emv_field(id: &str, value: &str) -> String { format!("{id}{:02}{value}", value.len()) } pub fn generate_emv_string( payload_url: &str, merchant_name: &str, merchant_city: &str, amount: Option<&str>, txid: Option<&str>, ) -> String { let mut emv = String::new(); // 00: Payload Format Indicator emv += &format_emv_field("00", "01"); // 01: Point of Initiation Method (dynamic) emv += &format_emv_field("01", "12"); // 26: Merchant Account Info let gui = format_emv_field("00", "br.gov.bcb.pix"); let url = format_emv_field("25", payload_url); let merchant_account_info = format_emv_field("26", &(gui + &url)); emv += &merchant_account_info; // 52: Merchant Category Code (0000) emv += &format_emv_field("52", "0000"); // 53: Currency Code (986 for BRL) emv += &format_emv_field("53", "986"); // 54: Amount (optional) if let Some(amount) = amount { emv += &format_emv_field("54", amount); } // 58: Country Code (BR) emv += &format_emv_field("58", "BR"); // 59: Merchant Name emv += &format_emv_field("59", merchant_name); // 60: Merchant City emv += &format_emv_field("60", merchant_city); // 62: Additional Data Field Template (optional TXID) if let Some(txid) = txid { let reference = format_emv_field("05", txid); emv += &format_emv_field("62", &reference); } // Placeholder for CRC (we need to calculate this last) emv += "6304"; // Compute CRC16-CCITT (False) checksum let crc = Crc::<u16>::new(&CRC_16_CCITT_FALSE); let checksum = crc.checksum(emv.as_bytes()); emv += &format!("{checksum:04X}"); emv } #[derive(Debug, Serialize, Deserialize)] pub struct SantanderAuthUpdateResponse { #[serde(rename = "camelCase")] pub refresh_url: String, pub token_type: String, pub client_id: String, pub access_token: Secret<String>, pub scopes: String, pub expires_in: i64, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct SantanderCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SantanderPSyncBoletoRequest { payer_document_number: Secret<i64>, } pub struct SantanderAuthType { pub(super) _api_key: Secret<String>, pub(super) _key1: Secret<String>, } impl TryFrom<&ConnectorAuthType> for SantanderAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { _api_key: api_key.to_owned(), _key1: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } impl<F, T> TryFrom<ResponseRouterData<F, SantanderAuthUpdateResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, SantanderAuthUpdateResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(AccessToken { token: item.response.access_token, expires: item.response.expires_in, }), ..item.data }) } } impl TryFrom<&SantanderRouterData<&PaymentsAuthorizeRouterData>> for SantanderPaymentRequest { type Error = Error; fn try_from( value: &SantanderRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { if value.router_data.request.capture_method != Some(enums::CaptureMethod::Automatic) { return Err(errors::ConnectorError::FlowNotSupported { flow: format!("{:?}", value.router_data.request.capture_method), connector: "Santander".to_string(), } .into()); } match value.router_data.request.payment_method_data.clone() { PaymentMethodData::BankTransfer(ref bank_transfer_data) => { Self::try_from((value, bank_transfer_data.as_ref())) } PaymentMethodData::Voucher(ref voucher_data) => Self::try_from((value, voucher_data)), _ => Err(errors::ConnectorError::NotImplemented( crate::utils::get_unimplemented_payment_method_error_message("Santander"), ))?, } } } impl TryFrom<&SantanderRouterData<&PaymentsSyncRouterData>> for SantanderPSyncBoletoRequest { type Error = Error; fn try_from(value: &SantanderRouterData<&PaymentsSyncRouterData>) -> Result<Self, Self::Error> { let payer_document_number: i64 = value .router_data .connector_request_reference_id .parse() .map_err(|_| errors::ConnectorError::ParsingFailed)?; Ok(Self { payer_document_number: Secret::new(payer_document_number), }) } } impl TryFrom<( &SantanderRouterData<&PaymentsAuthorizeRouterData>, &VoucherData, )> for SantanderPaymentRequest { type Error = Error; fn try_from( value: ( &SantanderRouterData<&PaymentsAuthorizeRouterData>, &VoucherData, ), ) -> Result<Self, Self::Error> { let santander_mca_metadata = SantanderMetadataObject::try_from(&value.0.router_data.connector_meta_data)?; let voucher_data = match &value.0.router_data.request.payment_method_data { PaymentMethodData::Voucher(VoucherData::Boleto(boleto_data)) => boleto_data, _ => { return Err(errors::ConnectorError::NotImplemented( crate::utils::get_unimplemented_payment_method_error_message("Santander"), ) .into()); } }; let nsu_code = if value .0 .router_data .is_payment_id_from_merchant .unwrap_or(false) && value.0.router_data.payment_id.len() > 20 { return Err(errors::ConnectorError::MaxFieldLengthViolated { connector: "Santander".to_string(), field_name: "payment_id".to_string(), max_length: 20, received_length: value.0.router_data.payment_id.len(), } .into()); } else { value.0.router_data.payment_id.clone() }; Ok(Self::Boleto(Box::new(SantanderBoletoPaymentRequest { environment: Environment::from(router_env::env::which()), nsu_code, nsu_date: OffsetDateTime::now_utc() .date() .format(&time::macros::format_description!("[year]-[month]-[day]")) .change_context(errors::ConnectorError::DateFormattingFailed)?, covenant_code: santander_mca_metadata.covenant_code.clone(), bank_number: voucher_data.bank_number.clone().ok_or_else(|| { errors::ConnectorError::MissingRequiredField { field_name: "document_type", } })?, // size: 13 client_number: Some(value.0.router_data.get_customer_id()?), due_date: voucher_data.due_date.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "due_date", }, )?, issue_date: OffsetDateTime::now_utc() .date() .format(&time::macros::format_description!("[year]-[month]-[day]")) .change_context(errors::ConnectorError::DateFormattingFailed)?, currency: Some(value.0.router_data.request.currency), nominal_value: value.0.amount.to_owned(), participant_code: value .0 .router_data .request .merchant_order_reference_id .clone(), payer: Payer { name: value.0.router_data.get_billing_full_name()?, document_type: voucher_data.document_type.ok_or_else(|| { errors::ConnectorError::MissingRequiredField { field_name: "document_type", } })?, document_number: voucher_data.social_security_number.clone(), address: Secret::new( [ value.0.router_data.get_billing_line1()?, value.0.router_data.get_billing_line2()?, ] .map(|s| s.expose()) .join(" "), ), neighborhood: value.0.router_data.get_billing_line1()?, city: value.0.router_data.get_billing_city()?, state: value.0.router_data.get_billing_state()?, zipcode: value.0.router_data.get_billing_zip()?, }, beneficiary: None, document_kind: BoletoDocumentKind::BillProposal, // to change discount: Some(Discount { discount_type: DiscountType::Free, discount_one: None, discount_two: None, discount_three: None, }), fine_percentage: voucher_data.fine_percentage.clone(), fine_quantity_days: voucher_data.fine_quantity_days.clone(), interest_percentage: voucher_data.interest_percentage.clone(), deduction_value: None, protest_type: None, protest_quantity_days: None, write_off_quantity_days: voucher_data.write_off_quantity_days.clone(), payment_type: PaymentType::Registration, parcels_quantity: None, value_type: None, min_value_or_percentage: None, max_value_or_percentage: None, iof_percentage: None, sharing: None, key: None, tx_id: None, messages: voucher_data.messages.clone(), }))) } } impl TryFrom<( &SantanderRouterData<&PaymentsAuthorizeRouterData>, &BankTransferData, )> for SantanderPaymentRequest { type Error = Error; fn try_from( value: ( &SantanderRouterData<&PaymentsAuthorizeRouterData>, &BankTransferData, ), ) -> Result<Self, Self::Error> { let santander_mca_metadata = SantanderMetadataObject::try_from(&value.0.router_data.connector_meta_data)?; let debtor = Some(SantanderDebtor { cpf: santander_mca_metadata.cpf.clone(), name: value.0.router_data.get_billing_full_name()?, }); Ok(Self::PixQR(Box::new(SantanderPixQRPaymentRequest { calender: SantanderCalendar { creation: OffsetDateTime::now_utc() .date() .format(&time::macros::format_description!("[year]-[month]-[day]")) .change_context(errors::ConnectorError::DateFormattingFailed)?, expiration: santander_mca_metadata.expiration_time, }, debtor, value: SantanderValue { original: value.0.amount.to_owned(), }, key: santander_mca_metadata.pix_key.clone(), request_payer: value.0.router_data.request.statement_descriptor.clone(), additional_info: None, }))) } } #[derive(Debug, Serialize)] pub enum SantanderPaymentRequest { PixQR(Box<SantanderPixQRPaymentRequest>), Boleto(Box<SantanderBoletoPaymentRequest>), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Discount { #[serde(rename = "type")] pub discount_type: DiscountType, pub discount_one: Option<DiscountObject>, pub discount_two: Option<DiscountObject>, pub discount_three: Option<DiscountObject>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SantanderBoletoPaymentRequest { pub environment: Environment, pub nsu_code: String, pub nsu_date: String, pub covenant_code: String, pub bank_number: Secret<String>, pub client_number: Option<id_type::CustomerId>, pub due_date: String, pub issue_date: String, pub currency: Option<enums::Currency>, pub nominal_value: StringMajorUnit, pub participant_code: Option<String>, pub payer: Payer, pub beneficiary: Option<Beneficiary>, pub document_kind: BoletoDocumentKind, pub discount: Option<Discount>, pub fine_percentage: Option<String>, pub fine_quantity_days: Option<String>, pub interest_percentage: Option<String>, pub deduction_value: Option<FloatMajorUnit>, pub protest_type: Option<ProtestType>, pub protest_quantity_days: Option<i64>, pub write_off_quantity_days: Option<String>, pub payment_type: PaymentType, pub parcels_quantity: Option<i64>, pub value_type: Option<String>, pub min_value_or_percentage: Option<f64>, pub max_value_or_percentage: Option<f64>, pub iof_percentage: Option<f64>, pub sharing: Option<Sharing>, pub key: Option<Key>, pub tx_id: Option<String>, pub messages: Option<Vec<String>>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Payer { pub name: Secret<String>, pub document_type: enums::DocumentKind, pub document_number: Option<Secret<String>>, pub address: Secret<String>, pub neighborhood: Secret<String>, pub city: String, pub state: Secret<String>, pub zipcode: Secret<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Beneficiary { pub name: Option<Secret<String>>, pub document_type: Option<enums::DocumentKind>, pub document_number: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum Environment { #[serde(rename = "Teste")] Sandbox, #[serde(rename = "Producao")] Production, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum SantanderDocumentKind { Cpf, Cnpj, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BoletoDocumentKind { #[serde(rename = "DUPLICATA_MERCANTIL")] DuplicateMercantil, #[serde(rename = "DUPLICATA_SERVICO")] DuplicateService, #[serde(rename = "NOTA_PROMISSORIA")] PromissoryNote, #[serde(rename = "NOTA_PROMISSORIA_RURAL")] RuralPromissoryNote, #[serde(rename = "RECIBO")] Receipt, #[serde(rename = "APOLICE_SEGURO")] InsurancePolicy, #[serde(rename = "BOLETO_CARTAO_CREDITO")] BillCreditCard, #[serde(rename = "BOLETO_PROPOSTA")] BillProposal, #[serde(rename = "BOLETO_DEPOSITO_APORTE")] BoletoDepositoAponte, #[serde(rename = "CHEQUE")] Check, #[serde(rename = "NOTA_PROMISSORIA_DIRETA")] DirectPromissoryNote, #[serde(rename = "OUTROS")] Others, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum DiscountType { #[serde(rename = "ISENTO")] Free, #[serde(rename = "VALOR_DATA_FIXA")] FixedDateValue, #[serde(rename = "VALOR_DIA_CORRIDO")] ValueDayConductor, #[serde(rename = "VALOR_DIA_UTIL")] ValueWorthDay, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub struct DiscountObject { pub value: f64, pub limit_date: String, // YYYY-MM-DD } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum ProtestType { #[serde(rename = "SEM_PROTESTO")] WithoutProtest, #[serde(rename = "DIAS_CORRIDOS")] DaysConducted, #[serde(rename = "DIAS_UTEIS")] WorkingDays, #[serde(rename = "CADASTRO_CONVENIO")] RegistrationAgreement, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum PaymentType { #[serde(rename = "REGISTRO")] Registration, #[serde(rename = "DIVERGENTE")] Divergent, #[serde(rename = "PARCIAL")] Partial, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Sharing { pub code: String, pub value: f64, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Key { #[serde(rename = "type")] pub key_type: Option<String>, pub dict_key: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SantanderPixQRCodeRequest { #[serde(rename = "calendario")] pub calender: SantanderCalendar, #[serde(rename = "devedor")] pub debtor: SantanderDebtor, #[serde(rename = "valor")] pub value: SantanderValue, #[serde(rename = "chave")] pub key: Secret<String>, #[serde(rename = "solicitacaoPagador")] pub request_payer: Option<String>, #[serde(rename = "infoAdicionais")] pub additional_info: Option<Vec<SantanderAdditionalInfo>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SantanderPixQRPaymentRequest { #[serde(rename = "calendario")] pub calender: SantanderCalendar, #[serde(rename = "devedor")] pub debtor: Option<SantanderDebtor>, #[serde(rename = "valor")] pub value: SantanderValue, #[serde(rename = "chave")] pub key: Secret<String>, #[serde(rename = "solicitacaoPagador")] pub request_payer: Option<String>, #[serde(rename = "infoAdicionais")] pub additional_info: Option<Vec<SantanderAdditionalInfo>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SantanderDebtor { pub cpf: Secret<String>, #[serde(rename = "nome")] pub name: Secret<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SantanderValue { pub original: StringMajorUnit, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SantanderAdditionalInfo { #[serde(rename = "nome")] pub name: String, #[serde(rename = "valor")] pub value: String, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SantanderPaymentStatus { Active, Completed, RemovedByReceivingUser, RemovedByPSP, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SantanderVoidStatus { RemovedByReceivingUser, } impl From<SantanderPaymentStatus> for AttemptStatus { fn from(item: SantanderPaymentStatus) -> Self { match item { SantanderPaymentStatus::Active => Self::Authorizing, SantanderPaymentStatus::Completed => Self::Charged, SantanderPaymentStatus::RemovedByReceivingUser => Self::Voided, SantanderPaymentStatus::RemovedByPSP => Self::Failure, } } } impl From<router_env::env::Env> for Environment { fn from(item: router_env::env::Env) -> Self { match item { router_env::env::Env::Sandbox | router_env::env::Env::Development => Self::Sandbox, router_env::env::Env::Production => Self::Production, } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum SantanderPaymentsResponse { PixQRCode(Box<SantanderPixQRCodePaymentsResponse>), Boleto(Box<SantanderBoletoPaymentsResponse>), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SantanderBoletoPaymentsResponse { pub environment: Environment, pub nsu_code: String, pub nsu_date: String, pub covenant_code: String, pub bank_number: String, pub client_number: Option<id_type::CustomerId>, pub due_date: String, pub issue_date: String, pub participant_code: Option<String>, pub nominal_value: StringMajorUnit, pub payer: Payer, pub beneficiary: Option<Beneficiary>, pub document_kind: BoletoDocumentKind, pub discount: Option<Discount>, pub fine_percentage: Option<String>, pub fine_quantity_days: Option<String>, pub interest_percentage: Option<String>, pub deduction_value: Option<FloatMajorUnit>, pub protest_type: Option<ProtestType>, pub protest_quantity_days: Option<i64>, pub write_off_quantity_days: Option<String>, pub payment_type: PaymentType, pub parcels_quantity: Option<i64>, pub value_type: Option<String>, pub min_value_or_percentage: Option<f64>, pub max_value_or_percentage: Option<f64>, pub iof_percentage: Option<f64>, pub sharing: Option<Sharing>, pub key: Option<Key>, pub tx_id: Option<String>, pub messages: Option<Vec<String>>, pub barcode: Option<String>, pub digitable_line: Option<Secret<String>>, pub entry_date: Option<String>, pub qr_code_pix: Option<String>, pub qr_code_url: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SantanderPixQRCodePaymentsResponse { pub status: SantanderPaymentStatus, #[serde(rename = "calendario")] pub calendar: SantanderCalendar, #[serde(rename = "txid")] pub transaction_id: String, #[serde(rename = "revisao")] pub revision: i32, #[serde(rename = "devedor")] pub debtor: Option<SantanderDebtor>, pub location: Option<String>, #[serde(rename = "valor")] pub value: SantanderValue, #[serde(rename = "chave")] pub key: Secret<String>, #[serde(rename = "solicitacaoPagador")] pub request_payer: Option<String>, #[serde(rename = "infoAdicionais")] pub additional_info: Option<Vec<SantanderAdditionalInfo>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SantanderPixVoidResponse { #[serde(rename = "calendario")] pub calendar: SantanderCalendar, #[serde(rename = "txid")] pub transaction_id: String, #[serde(rename = "revisao")] pub revision: i32, #[serde(rename = "devedor")] pub debtor: Option<SantanderDebtor>, pub location: Option<String>, pub status: SantanderPaymentStatus, #[serde(rename = "valor")] pub value: SantanderValue, #[serde(rename = "chave")] pub key: Secret<String>, #[serde(rename = "solicitacaoPagador")] pub request_payer: Option<String>, #[serde(rename = "infoAdicionais")] pub additional_info: Option<Vec<SantanderAdditionalInfo>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct SantanderCalendar { #[serde(rename = "calendario")] pub creation: String, #[serde(rename = "expiracao")] pub expiration: i32, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum SantanderPaymentsSyncResponse { PixQRCode(Box<SantanderPixPSyncResponse>), Boleto(Box<SantanderBoletoPSyncResponse>), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SantanderBoletoPSyncResponse { pub link: Option<Url>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SantanderPixPSyncResponse { #[serde(flatten)] pub base: SantanderPixQRCodePaymentsResponse, pub pix: Vec<SantanderPix>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SantanderPix { pub end_to_end_id: Secret<String>, #[serde(rename = "txid")] pub transaction_id: Secret<String>, #[serde(rename = "valor")] pub value: String, #[serde(rename = "horario")] pub time: String, #[serde(rename = "infoPagador")] pub info_payer: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SantanderPaymentsCancelRequest { pub status: Option<SantanderVoidStatus>, } impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, SantanderPaymentsSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let response = item.response.clone(); match response { SantanderPaymentsSyncResponse::PixQRCode(pix_data) => { let attempt_status = AttemptStatus::from(pix_data.base.status.clone()); match attempt_status { AttemptStatus::Failure => { let response = Err(get_error_response( Box::new(pix_data.base), item.http_code, attempt_status, )); Ok(Self { response, ..item.data }) } _ => { let connector_metadata = pix_data.pix.first().map(|pix| { serde_json::json!({ "end_to_end_id": pix.end_to_end_id.clone().expose() }) }); Ok(Self { status: AttemptStatus::from(pix_data.base.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( pix_data.base.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } } SantanderPaymentsSyncResponse::Boleto(boleto_data) => { let redirection_data = boleto_data.link.clone().map(|url| RedirectForm::Form { endpoint: url.to_string(), method: Method::Get, form_fields: HashMap::new(), }); Ok(Self { status: AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } } } pub fn get_error_response( pix_data: Box<SantanderPixQRCodePaymentsResponse>, status_code: u16, attempt_status: AttemptStatus, ) -> ErrorResponse { ErrorResponse { code: NO_ERROR_CODE.to_string(), message: NO_ERROR_MESSAGE.to_string(), reason: None, status_code, attempt_status: Some(attempt_status), connector_transaction_id: Some(pix_data.transaction_id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, } } impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let response = item.response.clone(); match response { SantanderPaymentsResponse::PixQRCode(pix_data) => { let attempt_status = AttemptStatus::from(pix_data.status.clone()); match attempt_status { AttemptStatus::Failure => { let response = Err(get_error_response( Box::new(*pix_data), item.http_code, attempt_status, )); Ok(Self { response, ..item.data }) } _ => Ok(Self { status: AttemptStatus::from(pix_data.status.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( pix_data.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: get_qr_code_data(&item, &pix_data)?, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), } } SantanderPaymentsResponse::Boleto(boleto_data) => { let voucher_data = VoucherNextStepData { expires_at: None, digitable_line: boleto_data.digitable_line.clone(), reference: boleto_data.barcode.ok_or( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "barcode", }, )?, entry_date: boleto_data.entry_date, download_url: None, instructions_url: None, }; let connector_metadata = Some(voucher_data.encode_to_value()) .transpose() .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let resource_id = match boleto_data.tx_id { Some(tx_id) => ResponseId::ConnectorTransactionId(tx_id), None => ResponseId::NoResponseId, }; let connector_response_reference_id = Some( boleto_data .digitable_line .as_ref() .map(|s| s.peek().to_owned()) .clone() .or_else(|| { boleto_data.beneficiary.as_ref().map(|beneficiary| { format!( "{}.{:?}", boleto_data.bank_number, beneficiary.document_number.clone() ) }) }) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "beneficiary.document_number", })?, ); Ok(Self { status: AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } } } impl<F, T> TryFrom<ResponseRouterData<F, SantanderPixVoidResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, SantanderPixVoidResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let response = item.response.clone(); Ok(Self { status: AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response.transaction_id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: *Box::new(None), network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl TryFrom<&PaymentsCancelRouterData> for SantanderPaymentsCancelRequest { type Error = Error; fn try_from(_item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { Ok(Self { status: Some(SantanderVoidStatus::RemovedByReceivingUser), }) } } fn get_qr_code_data<F, T>( item: &ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsResponseData>, pix_data: &SantanderPixQRCodePaymentsResponse, ) -> CustomResult<Option<Value>, errors::ConnectorError> { let santander_mca_metadata = SantanderMetadataObject::try_from(&item.data.connector_meta_data)?; let response = pix_data.clone(); let expiration_time = response.calendar.expiration; let expiration_i64 = i64::from(expiration_time); let rfc3339_expiry = (OffsetDateTime::now_utc() + time::Duration::seconds(expiration_i64)) .format(&time::format_description::well_known::Rfc3339) .map_err(|_| errors::ConnectorError::ResponseHandlingFailed)?; let qr_expiration_duration = OffsetDateTime::parse( rfc3339_expiry.as_str(), &time::format_description::well_known::Rfc3339, ) .map_err(|_| errors::ConnectorError::ResponseHandlingFailed)? .unix_timestamp() * 1000; let merchant_city = santander_mca_metadata.merchant_city.as_str(); let merchant_name = santander_mca_metadata.merchant_name.as_str(); let payload_url = if let Some(location) = response.location { location } else { return Err(errors::ConnectorError::ResponseHandlingFailed)?; }; let amount_i64 = StringMajorUnitForConnector .convert_back(response.value.original, enums::Currency::BRL) .change_context(errors::ConnectorError::ResponseHandlingFailed)? .get_amount_as_i64(); let amount_string = amount_i64.to_string(); let amount = amount_string.as_str(); let dynamic_pix_code = generate_emv_string( payload_url.as_str(), merchant_name, merchant_city, Some(amount), Some(response.transaction_id.as_str()), ); let image_data = QrImage::new_from_data(dynamic_pix_code.clone()) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let image_data_url = Url::parse(image_data.data.clone().as_str()) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let qr_code_info = QrCodeInformation::QrDataUrl { image_data_url, display_to_timestamp: Some(qr_expiration_duration), }; Some(qr_code_info.encode_to_value()) .transpose() .change_context(errors::ConnectorError::ResponseHandlingFailed) } #[derive(Default, Debug, Serialize)] pub struct SantanderRefundRequest { #[serde(rename = "valor")] pub value: StringMajorUnit, } impl<F> TryFrom<&SantanderRouterData<&RefundsRouterData<F>>> for SantanderRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &SantanderRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { value: item.amount.to_owned(), }) } } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SantanderRefundStatus { InProcessing, Returned, NotDone, } impl From<SantanderRefundStatus> for enums::RefundStatus { fn from(item: SantanderRefundStatus) -> Self { match item { SantanderRefundStatus::Returned => Self::Success, SantanderRefundStatus::NotDone => Self::Failure, SantanderRefundStatus::InProcessing => Self::Pending, } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SantanderRefundResponse { pub id: Secret<String>, pub rtr_id: Secret<String>, #[serde(rename = "valor")] pub value: StringMajorUnit, #[serde(rename = "horario")] pub time: SantanderTime, pub status: SantanderRefundStatus, #[serde(rename = "motivo")] pub reason: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SantanderTime { #[serde(rename = "solicitacao")] pub request: Option<String>, #[serde(rename = "liquidacao")] pub liquidation: Option<String>, } impl<F> TryFrom<RefundsResponseRouterData<F, SantanderRefundResponse>> for RefundsRouterData<F> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<F, SantanderRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.rtr_id.clone().expose(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize)] pub enum SantanderErrorResponse { PixQrCode(SantanderPixQRCodeErrorResponse), Boleto(SantanderBoletoErrorResponse), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SantanderBoletoErrorResponse { #[serde(rename = "_errorCode")] pub error_code: i64, #[serde(rename = "_message")] pub error_message: String, #[serde(rename = "_details")] pub issuer_error_message: String, #[serde(rename = "_timestamp")] pub timestamp: String, #[serde(rename = "_traceId")] pub trace_id: String, #[serde(rename = "_errors")] pub errors: Option<Vec<ErrorObject>>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ErrorObject { #[serde(rename = "_code")] pub code: Option<i64>, #[serde(rename = "_field")] pub field: Option<String>, #[serde(rename = "_message")] pub message: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SantanderPixQRCodeErrorResponse { #[serde(rename = "type")] pub field_type: Secret<String>, pub title: String, pub status: i64, pub detail: Option<String>, pub correlation_id: Option<String>, #[serde(rename = "violacoes")] pub violations: Option<Vec<SantanderViolations>>, } #[derive(Debug, Serialize, Deserialize)] pub struct SantanderViolations { #[serde(rename = "razao")] pub reason: Option<String>, #[serde(rename = "propriedade")] pub property: Option<String>, #[serde(rename = "valor")] pub value: Option<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SantanderWebhookBody { pub message: MessageCode, // meaning of this enum variant is not clear pub function: FunctionType, // event type of the webhook pub payment_type: WebhookPaymentType, pub issue_date: String, pub payment_date: String, pub bank_code: String, pub payment_channel: PaymentChannel, pub payment_kind: PaymentKind, pub covenant: String, pub type_of_person_agreement: enums::DocumentKind, pub agreement_document: String, pub bank_number: String, pub client_number: String, pub participant_code: String, pub tx_id: String, pub payer_document_type: enums::DocumentKind, pub payer_document_number: String, pub payer_name: String, pub final_beneficiary_document_type: enums::DocumentKind, pub final_beneficiary_document_number: String, pub final_beneficiary_name: String, pub due_date: String, pub nominal_value: StringMajorUnit, pub payed_value: String, pub interest_value: String, pub fine: String, pub deduction_value: String, pub rebate_value: String, pub iof_value: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum MessageCode { Wbhkpagest, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum FunctionType { Pagamento, // Payment Estorno, // Refund } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum WebhookPaymentType { Santander, OutrosBancos, Pix, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] /// Represents the channel through which a boleto payment was made. pub enum PaymentChannel { /// Payment made at a bank branch or ATM (self-service). AgenciasAutoAtendimento, /// Payment made through online banking. InternetBanking, /// Payment made at a physical correspondent agent (e.g., convenience stores, partner outlets). CorrespondenteBancarioFisico, /// Payment made via Santander’s call center. CentralDeAtendimento, /// Payment made via electronic file, typically for bulk company payments. ArquivoEletronico, /// Payment made via DDA (Débito Direto Autorizado) / electronic bill presentment system. Dda, /// Payment made via digital correspondent channels (apps, kiosks, digital partners). CorrespondenteBancarioDigital, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] /// Represents the type of payment instrument used to pay a boleto. pub enum PaymentKind { /// Payment made in cash or physical form (not via account or card). Especie, /// Payment made via direct debit from a bank account. DebitoEmConta, /// Payment made via credit card. CartaoDeCredito, /// Payment made via check. Cheque, } pub(crate) fn get_webhook_object_from_body( body: &[u8], ) -> CustomResult<SantanderWebhookBody, common_utils::errors::ParsingError> { let webhook: SantanderWebhookBody = body.parse_struct("SantanderIncomingWebhook")?; Ok(webhook) } pub(crate) fn get_santander_webhook_event( event_type: FunctionType, ) -> api_models::webhooks::IncomingWebhookEvent { // need to confirm about the other possible webhook event statues, as of now only two known match event_type { FunctionType::Pagamento => api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess, FunctionType::Estorno => api_models::webhooks::IncomingWebhookEvent::RefundSuccess, } }
crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
hyperswitch_connectors::src::connectors::santander::transformers
10,345
true
// File: crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs // Module: hyperswitch_connectors::src::connectors::bitpay::transformers use common_enums::enums; use common_utils::{request::Method, types::FloatMajorUnit}; use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::PaymentsAuthorizeRequestData, }; #[derive(Debug, Serialize)] pub struct BitpayRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for BitpayRouterData<T> { fn from((amount, router_data): (FloatMajorUnit, T)) -> Self { Self { amount, router_data, } } } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum TransactionSpeed { Low, #[default] Medium, High, } #[derive(Default, Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct BitpayPaymentsRequest { price: FloatMajorUnit, currency: String, #[serde(rename = "redirectURL")] redirect_url: String, #[serde(rename = "notificationURL")] notification_url: String, transaction_speed: TransactionSpeed, token: Secret<String>, order_id: String, } impl TryFrom<&BitpayRouterData<&types::PaymentsAuthorizeRouterData>> for BitpayPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BitpayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { get_crypto_specific_payment_data(item) } } // Auth Struct pub struct BitpayAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for BitpayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum BitpayPaymentStatus { #[default] New, Paid, Confirmed, Complete, Expired, Invalid, } impl From<BitpayPaymentStatus> for enums::AttemptStatus { fn from(item: BitpayPaymentStatus) -> Self { match item { BitpayPaymentStatus::New => Self::AuthenticationPending, BitpayPaymentStatus::Complete | BitpayPaymentStatus::Confirmed => Self::Charged, BitpayPaymentStatus::Expired => Self::Failure, _ => Self::Pending, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum ExceptionStatus { #[default] Unit, Bool(bool), String(String), } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BitpayPaymentResponseData { pub url: Option<url::Url>, pub status: BitpayPaymentStatus, pub price: FloatMajorUnit, pub currency: String, pub amount_paid: FloatMajorUnit, pub invoice_time: Option<FloatMajorUnit>, pub rate_refresh_time: Option<i64>, pub expiration_time: Option<i64>, pub current_time: Option<i64>, pub id: String, pub order_id: Option<String>, pub low_fee_detected: Option<bool>, pub display_amount_paid: Option<String>, pub exception_status: ExceptionStatus, pub redirect_url: Option<String>, pub refund_address_request_pending: Option<bool>, pub merchant_name: Option<Secret<String>>, pub token: Option<Secret<String>>, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct BitpayPaymentsResponse { data: BitpayPaymentResponseData, facade: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, BitpayPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, BitpayPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirection_data = item .response .data .url .map(|x| RedirectForm::from((x, Method::Get))); let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id.clone()); let attempt_status = item.response.data.status; Ok(Self { status: enums::AttemptStatus::from(attempt_status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: connector_id, redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item .response .data .order_id .or(Some(item.response.data.id)), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct BitpayRefundRequest { pub amount: FloatMajorUnit, } impl<F> TryFrom<&BitpayRouterData<&types::RefundsRouterData<F>>> for BitpayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BitpayRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount, }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] pub struct BitpayErrorResponse { pub error: String, pub code: Option<String>, pub message: Option<String>, } fn get_crypto_specific_payment_data( item: &BitpayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<BitpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> { let price = item.amount; let currency = item.router_data.request.currency.to_string(); let redirect_url = item.router_data.request.get_router_return_url()?; let notification_url = item.router_data.request.get_webhook_url()?; let transaction_speed = TransactionSpeed::Medium; let auth_type = item.router_data.connector_auth_type.clone(); let token = match auth_type { ConnectorAuthType::HeaderKey { api_key } => api_key, _ => String::default().into(), }; let order_id = item.router_data.connector_request_reference_id.clone(); Ok(BitpayPaymentsRequest { price, currency, redirect_url, notification_url, transaction_speed, token, order_id, }) } #[derive(Debug, Serialize, Deserialize)] pub struct BitpayWebhookDetails { pub event: Event, pub data: BitpayPaymentResponseData, } #[derive(Debug, Serialize, Deserialize)] pub struct Event { pub code: i64, pub name: WebhookEventType, } #[derive(Debug, Serialize, Deserialize)] pub enum WebhookEventType { #[serde(rename = "invoice_paidInFull")] Paid, #[serde(rename = "invoice_confirmed")] Confirmed, #[serde(rename = "invoice_completed")] Completed, #[serde(rename = "invoice_expired")] Expired, #[serde(rename = "invoice_failedToConfirm")] Invalid, #[serde(rename = "invoice_declined")] Declined, #[serde(rename = "invoice_refundComplete")] Refunded, #[serde(rename = "invoice_manuallyNotified")] Resent, #[serde(other)] Unknown, }
crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
hyperswitch_connectors::src::connectors::bitpay::transformers
2,236
true
// File: crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs // Module: hyperswitch_connectors::src::connectors::moneris::transformers use common_enums::enums; use common_utils::types::MinorUnit; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{CardData as _, PaymentsAuthorizeRequestData, RouterData as OtherRouterData}, }; const CLIENT_CREDENTIALS: &str = "client_credentials"; pub struct MonerisRouterData<T> { pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(MinorUnit, T)> for MonerisRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } pub mod auth_headers { pub const X_MERCHANT_ID: &str = "X-Merchant-Id"; pub const API_VERSION: &str = "Api-Version"; } #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MonerisPaymentsRequest { idempotency_key: String, amount: Amount, payment_method: PaymentMethod, automatic_capture: bool, } #[derive(Default, Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Amount { currency: enums::Currency, amount: MinorUnit, } #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(untagged)] pub enum PaymentMethod { Card(PaymentMethodCard), PaymentMethodId(PaymentMethodId), } #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentMethodCard { payment_method_source: PaymentMethodSource, card: MonerisCard, store_payment_method: StorePaymentMethod, } #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentMethodId { payment_method_source: PaymentMethodSource, payment_method_id: Secret<String>, } #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaymentMethodSource { Card, PaymentMethodId, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MonerisCard { card_number: cards::CardNumber, expiry_month: Secret<i64>, expiry_year: Secret<i64>, card_security_code: Secret<String>, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum StorePaymentMethod { DoNotStore, CardholderInitiated, MerchantInitiated, } impl TryFrom<&MonerisRouterData<&PaymentsAuthorizeRouterData>> for MonerisPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &MonerisRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { if item.router_data.is_three_ds() { Err(errors::ConnectorError::NotSupported { message: "Card 3DS".to_string(), connector: "Moneris", })? }; match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ref req_card) => { let idempotency_key = uuid::Uuid::new_v4().to_string(); let amount = Amount { currency: item.router_data.request.currency, amount: item.amount, }; let payment_method = PaymentMethod::Card(PaymentMethodCard { payment_method_source: PaymentMethodSource::Card, card: MonerisCard { card_number: req_card.card_number.clone(), expiry_month: Secret::new( req_card .card_exp_month .peek() .parse::<i64>() .change_context(errors::ConnectorError::ParsingFailed)?, ), expiry_year: Secret::new( req_card .get_expiry_year_4_digit() .peek() .parse::<i64>() .change_context(errors::ConnectorError::ParsingFailed)?, ), card_security_code: req_card.card_cvc.clone(), }, store_payment_method: if item .router_data .request .is_customer_initiated_mandate_payment() { StorePaymentMethod::CardholderInitiated } else { StorePaymentMethod::DoNotStore }, }); let automatic_capture = item.router_data.request.is_auto_capture()?; Ok(Self { idempotency_key, amount, payment_method, automatic_capture, }) } PaymentMethodData::MandatePayment => { let idempotency_key = uuid::Uuid::new_v4().to_string(); let amount = Amount { currency: item.router_data.request.currency, amount: item.amount, }; let automatic_capture = item.router_data.request.is_auto_capture()?; let payment_method = PaymentMethod::PaymentMethodId(PaymentMethodId { payment_method_source: PaymentMethodSource::PaymentMethodId, payment_method_id: item .router_data .request .connector_mandate_id() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "connector_mandate_id", })? .into(), }); Ok(Self { idempotency_key, amount, payment_method, automatic_capture, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } pub struct MonerisAuthType { pub(super) client_id: Secret<String>, pub(super) client_secret: Secret<String>, pub(super) merchant_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for MonerisAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { client_id: key1.to_owned(), client_secret: api_key.to_owned(), merchant_id: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Serialize, PartialEq)] pub struct MonerisAuthRequest { client_id: Secret<String>, client_secret: Secret<String>, grant_type: String, } impl TryFrom<&RefreshTokenRouterData> for MonerisAuthRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> { let auth = MonerisAuthType::try_from(&item.connector_auth_type)?; Ok(Self { client_id: auth.client_id.clone(), client_secret: auth.client_secret.clone(), grant_type: CLIENT_CREDENTIALS.to_string(), }) } } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct MonerisAuthResponse { access_token: Secret<String>, token_type: String, expires_in: String, } impl<F, T> TryFrom<ResponseRouterData<F, MonerisAuthResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, MonerisAuthResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(AccessToken { token: item.response.access_token, expires: item .response .expires_in .parse::<i64>() .change_context(errors::ConnectorError::ResponseDeserializationFailed)?, }), ..item.data }) } } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum MonerisPaymentStatus { Succeeded, #[default] Processing, Canceled, Declined, DeclinedRetry, Authorized, } impl From<MonerisPaymentStatus> for common_enums::AttemptStatus { fn from(item: MonerisPaymentStatus) -> Self { match item { MonerisPaymentStatus::Succeeded => Self::Charged, MonerisPaymentStatus::Authorized => Self::Authorized, MonerisPaymentStatus::Canceled => Self::Voided, MonerisPaymentStatus::Declined | MonerisPaymentStatus::DeclinedRetry => Self::Failure, MonerisPaymentStatus::Processing => Self::Pending, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MonerisPaymentsResponse { payment_status: MonerisPaymentStatus, payment_id: String, payment_method: MonerisPaymentMethodData, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MonerisPaymentMethodData { payment_method_id: Secret<String>, } impl<F, T> TryFrom<ResponseRouterData<F, MonerisPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, MonerisPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.payment_status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.payment_id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(Some(MandateReference { connector_mandate_id: Some( item.response .payment_method .payment_method_id .peek() .to_string(), ), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, })), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.payment_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MonerisPaymentsCaptureRequest { amount: Amount, idempotency_key: String, } impl TryFrom<&MonerisRouterData<&PaymentsCaptureRouterData>> for MonerisPaymentsCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &MonerisRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { let amount = Amount { currency: item.router_data.request.currency, amount: item.amount, }; let idempotency_key = uuid::Uuid::new_v4().to_string(); Ok(Self { amount, idempotency_key, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MonerisCancelRequest { idempotency_key: String, reason: Option<String>, } impl TryFrom<&PaymentsCancelRouterData> for MonerisCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let idempotency_key = uuid::Uuid::new_v4().to_string(); let reason = item.request.cancellation_reason.clone(); Ok(Self { idempotency_key, reason, }) } } #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MonerisRefundRequest { pub refund_amount: Amount, pub idempotency_key: String, pub reason: Option<String>, pub payment_id: String, } impl<F> TryFrom<&MonerisRouterData<&RefundsRouterData<F>>> for MonerisRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &MonerisRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let refund_amount = Amount { currency: item.router_data.request.currency, amount: item.amount, }; let idempotency_key = uuid::Uuid::new_v4().to_string(); let reason = item.router_data.request.reason.clone(); let payment_id = item.router_data.request.connector_transaction_id.clone(); Ok(Self { refund_amount, idempotency_key, reason, payment_id, }) } } #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RefundStatus { Succeeded, #[default] Processing, Declined, DeclinedRetry, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Declined | RefundStatus::DeclinedRetry => Self::Failure, RefundStatus::Processing => Self::Pending, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RefundResponse { refund_id: String, refund_status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.refund_id.to_string(), refund_status: enums::RefundStatus::from(item.response.refund_status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.refund_id.to_string(), refund_status: enums::RefundStatus::from(item.response.refund_status), }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MonerisErrorResponse { pub status: u16, pub category: String, pub title: String, pub errors: Option<Vec<MonerisError>>, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MonerisError { pub reason_code: String, pub parameter_name: String, } #[derive(Debug, Deserialize, Serialize)] pub struct MonerisAuthErrorResponse { pub error: String, pub error_description: Option<String>, }
crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs
hyperswitch_connectors::src::connectors::moneris::transformers
3,531
true
// File: crates/hyperswitch_connectors/src/connectors/volt/transformers.rs // Module: hyperswitch_connectors::src::connectors::volt::transformers use common_enums::enums; use common_utils::{id_type, pii::Email, request::Method, types::MinorUnit}; use hyperswitch_domain_models::{ payment_method_data::{BankRedirectData, PaymentMethodData}, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::Execute, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types, }; use hyperswitch_interfaces::{consts, errors}; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{self, is_payment_failure, AddressDetailsData, RouterData as _}, }; const PASSWORD: &str = "password"; pub struct VoltRouterData<T> { pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(MinorUnit, T)> for VoltRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } pub mod webhook_headers { pub const X_VOLT_SIGNED: &str = "X-Volt-Signed"; pub const X_VOLT_TIMED: &str = "X-Volt-Timed"; pub const USER_AGENT: &str = "User-Agent"; } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct VoltPaymentsRequest { amount: MinorUnit, currency_code: enums::Currency, #[serde(rename = "type")] transaction_type: TransactionType, merchant_internal_reference: String, shopper: ShopperDetails, payment_success_url: Option<String>, payment_failure_url: Option<String>, payment_pending_url: Option<String>, payment_cancel_url: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TransactionType { Bills, Goods, PersonToPerson, Other, Services, } #[derive(Debug, Serialize)] pub struct ShopperDetails { reference: id_type::CustomerId, email: Option<Email>, first_name: Secret<String>, last_name: Secret<String>, } impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &VoltRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::BankRedirect(ref bank_redirect) => match bank_redirect { BankRedirectData::OpenBankingUk { .. } => { let amount = item.amount; let currency_code = item.router_data.request.currency; let merchant_internal_reference = item.router_data.connector_request_reference_id.clone(); let payment_success_url = item.router_data.request.router_return_url.clone(); let payment_failure_url = item.router_data.request.router_return_url.clone(); let payment_pending_url = item.router_data.request.router_return_url.clone(); let payment_cancel_url = item.router_data.request.router_return_url.clone(); let address = item.router_data.get_billing_address()?; let first_name = address.get_first_name()?; let shopper = ShopperDetails { email: item.router_data.request.email.clone(), first_name: first_name.to_owned(), last_name: address.get_last_name().unwrap_or(first_name).to_owned(), reference: item.router_data.get_customer_id()?.to_owned(), }; let transaction_type = TransactionType::Services; //transaction_type is a form of enum, it is pre defined and value for this can not be taken from user so we are keeping it as Services as this transaction is type of service. Ok(Self { amount, currency_code, merchant_internal_reference, payment_success_url, payment_failure_url, payment_pending_url, payment_cancel_url, shopper, transaction_type, }) } BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Ideal { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::Sofort { .. } | BankRedirectData::Trustly { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::LocalBankRedirect {} => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Volt"), ) .into()) } }, PaymentMethodData::Card(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Volt"), ) .into()) } } } } #[derive(Debug, Clone, Serialize, PartialEq)] pub struct VoltAuthUpdateRequest { grant_type: String, client_id: Secret<String>, client_secret: Secret<String>, username: Secret<String>, password: Secret<String>, } impl TryFrom<&RefreshTokenRouterData> for VoltAuthUpdateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> { let auth = VoltAuthType::try_from(&item.connector_auth_type)?; Ok(Self { grant_type: PASSWORD.to_string(), username: auth.username, password: auth.password, client_id: auth.client_id, client_secret: auth.client_secret, }) } } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct VoltAuthUpdateResponse { pub access_token: Secret<String>, pub token_type: String, pub expires_in: i64, pub refresh_token: Secret<String>, } impl<F, T> TryFrom<ResponseRouterData<F, VoltAuthUpdateResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, VoltAuthUpdateResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(AccessToken { token: item.response.access_token, expires: item.response.expires_in, }), ..item.data }) } } pub struct VoltAuthType { pub(super) username: Secret<String>, pub(super) password: Secret<String>, pub(super) client_id: Secret<String>, pub(super) client_secret: Secret<String>, } impl TryFrom<&ConnectorAuthType> for VoltAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => Ok(Self { username: api_key.to_owned(), password: api_secret.to_owned(), client_id: key1.to_owned(), client_secret: key2.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } fn get_attempt_status( (item, current_status): (VoltPaymentStatus, enums::AttemptStatus), ) -> enums::AttemptStatus { match item { VoltPaymentStatus::Received | VoltPaymentStatus::Settled => enums::AttemptStatus::Charged, VoltPaymentStatus::Completed | VoltPaymentStatus::DelayedAtBank => { enums::AttemptStatus::Pending } VoltPaymentStatus::NewPayment | VoltPaymentStatus::BankRedirect | VoltPaymentStatus::AwaitingCheckoutAuthorisation => { enums::AttemptStatus::AuthenticationPending } VoltPaymentStatus::RefusedByBank | VoltPaymentStatus::RefusedByRisk | VoltPaymentStatus::NotReceived | VoltPaymentStatus::ErrorAtBank | VoltPaymentStatus::CancelledByUser | VoltPaymentStatus::AbandonedByUser | VoltPaymentStatus::Failed => enums::AttemptStatus::Failure, VoltPaymentStatus::Unknown => current_status, } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct VoltPaymentsResponse { checkout_url: String, id: String, } impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, VoltPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let url = item.response.checkout_url; let redirection_data = Some(RedirectForm::Form { endpoint: url, method: Method::Get, form_fields: Default::default(), }); Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Serialize, Clone, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[derive(strum::Display)] pub enum VoltPaymentStatus { NewPayment, Completed, Received, NotReceived, BankRedirect, DelayedAtBank, AwaitingCheckoutAuthorisation, RefusedByBank, RefusedByRisk, ErrorAtBank, CancelledByUser, AbandonedByUser, Failed, Settled, Unknown, } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum VoltPaymentsResponseData { PsyncResponse(VoltPsyncResponse), WebhookResponse(VoltPaymentWebhookObjectResource), } #[derive(Debug, Serialize, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct VoltPsyncResponse { status: VoltPaymentStatus, id: String, merchant_internal_reference: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response { VoltPaymentsResponseData::PsyncResponse(payment_response) => { let status = get_attempt_status((payment_response.status.clone(), item.data.status)); Ok(Self { status, response: if is_payment_failure(status) { Err(ErrorResponse { code: payment_response.status.clone().to_string(), message: payment_response.status.clone().to_string(), reason: Some(payment_response.status.to_string()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(payment_response.id), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( payment_response.id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: payment_response .merchant_internal_reference .or(Some(payment_response.id)), incremental_authorization_allowed: None, charges: None, }) }, ..item.data }) } VoltPaymentsResponseData::WebhookResponse(webhook_response) => { let detailed_status = webhook_response.detailed_status.clone(); let status = enums::AttemptStatus::from(webhook_response.status); Ok(Self { status, response: if is_payment_failure(status) { Err(ErrorResponse { code: detailed_status .clone() .map(|volt_status| volt_status.to_string()) .unwrap_or_else(|| consts::NO_ERROR_CODE.to_owned()), message: detailed_status .clone() .map(|volt_status| volt_status.to_string()) .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_owned()), reason: detailed_status .clone() .map(|volt_status| volt_status.to_string()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(webhook_response.payment.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( webhook_response.payment.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: webhook_response .merchant_internal_reference .or(Some(webhook_response.payment)), incremental_authorization_allowed: None, charges: None, }) }, ..item.data }) } } } } impl From<VoltWebhookPaymentStatus> for enums::AttemptStatus { fn from(status: VoltWebhookPaymentStatus) -> Self { match status { VoltWebhookPaymentStatus::Received => Self::Charged, VoltWebhookPaymentStatus::Failed | VoltWebhookPaymentStatus::NotReceived => { Self::Failure } VoltWebhookPaymentStatus::Completed | VoltWebhookPaymentStatus::Pending => { Self::Pending } } } } // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct VoltRefundRequest { pub amount: MinorUnit, pub external_reference: String, } impl<F> TryFrom<&VoltRouterData<&types::RefundsRouterData<F>>> for VoltRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &VoltRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount, external_reference: item.router_data.request.refund_id.clone(), }) } } #[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct RefundResponse { id: String, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::Pending, //We get Refund Status only by Webhooks }), ..item.data }) } } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct VoltPaymentWebhookBodyReference { pub payment: String, pub merchant_internal_reference: Option<String>, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct VoltRefundWebhookBodyReference { pub refund: String, pub external_reference: Option<String>, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "camelCase")] #[serde(untagged)] pub enum WebhookResponse { // the enum order shouldn't be changed as this is being used during serialization and deserialization Refund(VoltRefundWebhookBodyReference), Payment(VoltPaymentWebhookBodyReference), } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum VoltWebhookBodyEventType { Payment(VoltPaymentsWebhookBodyEventType), Refund(VoltRefundsWebhookBodyEventType), } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct VoltPaymentsWebhookBodyEventType { pub status: VoltWebhookPaymentStatus, pub detailed_status: Option<VoltDetailedStatus>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct VoltRefundsWebhookBodyEventType { pub status: VoltWebhookRefundsStatus, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum VoltWebhookObjectResource { Payment(VoltPaymentWebhookObjectResource), Refund(VoltRefundWebhookObjectResource), } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct VoltPaymentWebhookObjectResource { #[serde(alias = "id")] pub payment: String, pub merchant_internal_reference: Option<String>, pub status: VoltWebhookPaymentStatus, pub detailed_status: Option<VoltDetailedStatus>, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct VoltRefundWebhookObjectResource { pub refund: String, pub external_reference: Option<String>, pub status: VoltWebhookRefundsStatus, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum VoltWebhookPaymentStatus { Completed, Failed, Pending, Received, NotReceived, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum VoltWebhookRefundsStatus { RefundConfirmed, RefundFailed, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[derive(strum::Display)] pub enum VoltDetailedStatus { RefusedByRisk, RefusedByBank, ErrorAtBank, CancelledByUser, AbandonedByUser, Failed, Completed, BankRedirect, DelayedAtBank, AwaitingCheckoutAuthorisation, } impl From<VoltWebhookBodyEventType> for api_models::webhooks::IncomingWebhookEvent { fn from(status: VoltWebhookBodyEventType) -> Self { match status { VoltWebhookBodyEventType::Payment(payment_data) => match payment_data.status { VoltWebhookPaymentStatus::Received => Self::PaymentIntentSuccess, VoltWebhookPaymentStatus::Failed | VoltWebhookPaymentStatus::NotReceived => { Self::PaymentIntentFailure } VoltWebhookPaymentStatus::Completed | VoltWebhookPaymentStatus::Pending => { Self::PaymentIntentProcessing } }, VoltWebhookBodyEventType::Refund(refund_data) => match refund_data.status { VoltWebhookRefundsStatus::RefundConfirmed => Self::RefundSuccess, VoltWebhookRefundsStatus::RefundFailed => Self::RefundFailure, }, } } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct VoltErrorResponse { pub exception: VoltErrorException, } #[derive(Debug, Deserialize, Serialize)] pub struct VoltAuthErrorResponse { pub code: u64, pub message: String, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct VoltErrorException { pub code: u64, pub message: String, pub error_list: Option<Vec<VoltErrorList>>, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct VoltErrorList { pub property: String, pub message: String, }
crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
hyperswitch_connectors::src::connectors::volt::transformers
4,665
true
// File: crates/hyperswitch_connectors/src/connectors/noon/transformers.rs // Module: hyperswitch_connectors::src::connectors::noon::transformers use common_enums::enums::{self, AttemptStatus}; use common_utils::{ext_traits::Encode, pii, request::Method, types::StringMajorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{Execute, RSync}, router_request_types::{MandateRevokeRequestData, ResponseId}, router_response_types::{ MandateReference, MandateRevokeResponseData, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types::{ MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, CardData, GooglePayWalletData, PaymentsAuthorizeRequestData, RevokeMandateRequestData, RouterData as OtherRouterData, WalletData as OtherWalletData, }, }; // These needs to be accepted from SDK, need to be done after 1.0.0 stability as API contract will change const GOOGLEPAY_API_VERSION_MINOR: u8 = 0; const GOOGLEPAY_API_VERSION: u8 = 2; #[derive(Debug, Serialize)] pub struct NoonRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, pub mandate_amount: Option<StringMajorUnit>, } impl<T> From<(StringMajorUnit, T, Option<StringMajorUnit>)> for NoonRouterData<T> { fn from( (amount, router_data, mandate_amount): (StringMajorUnit, T, Option<StringMajorUnit>), ) -> Self { Self { amount, router_data, mandate_amount, } } } #[derive(Debug, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum NoonChannels { Web, } #[derive(Debug, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum NoonSubscriptionType { Unscheduled, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonSubscriptionData { #[serde(rename = "type")] subscription_type: NoonSubscriptionType, //Short description about the subscription. name: String, max_amount: StringMajorUnit, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonBillingAddress { street: Option<Secret<String>>, street2: Option<Secret<String>>, city: Option<String>, state_province: Option<Secret<String>>, country: Option<api_models::enums::CountryAlpha2>, postal_code: Option<Secret<String>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonBilling { address: NoonBillingAddress, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonOrder { amount: StringMajorUnit, currency: Option<enums::Currency>, channel: NoonChannels, category: Option<String>, reference: String, //Short description of the order. name: String, nvp: Option<NoonOrderNvp>, ip_address: Option<Secret<String, pii::IpAddress>>, } #[derive(Debug, Serialize)] pub struct NoonOrderNvp { #[serde(flatten)] inner: std::collections::BTreeMap<String, Secret<String>>, } fn get_value_as_string(value: &serde_json::Value) -> String { match value { serde_json::Value::String(string) => string.to_owned(), serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) | serde_json::Value::Array(_) | serde_json::Value::Object(_) => value.to_string(), } } impl NoonOrderNvp { pub fn new(metadata: &serde_json::Value) -> Self { let metadata_as_string = metadata.to_string(); let hash_map: std::collections::BTreeMap<String, serde_json::Value> = serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new()); let inner = hash_map .into_iter() .enumerate() .map(|(index, (hs_key, hs_value))| { let noon_key = format!("{}", index + 1); // to_string() function on serde_json::Value returns a string with "" quotes. Noon doesn't allow this. Hence get_value_as_string function let noon_value = format!("{hs_key}={}", get_value_as_string(&hs_value)); (noon_key, Secret::new(noon_value)) }) .collect(); Self { inner } } } #[derive(Debug, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum NoonPaymentActions { Authorize, Sale, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonConfiguration { tokenize_c_c: Option<bool>, payment_action: NoonPaymentActions, return_url: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonSubscription { subscription_identifier: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonCard { name_on_card: Option<Secret<String>>, number_plain: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvv: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonApplePayPaymentMethod { pub display_name: String, pub network: String, #[serde(rename = "type")] pub pm_type: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NoonApplePayHeader { ephemeral_public_key: Secret<String>, public_key_hash: Secret<String>, transaction_id: Secret<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct NoonApplePaymentData { version: Secret<String>, data: Secret<String>, signature: Secret<String>, header: NoonApplePayHeader, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonApplePayData { payment_data: NoonApplePaymentData, payment_method: NoonApplePayPaymentMethod, transaction_identifier: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonApplePayTokenData { token: NoonApplePayData, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonApplePay { payment_info: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonGooglePay { api_version_minor: u8, api_version: u8, payment_method_data: GooglePayWalletData, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonPayPal { return_url: String, } #[derive(Debug, Serialize)] #[serde(tag = "type", content = "data", rename_all = "UPPERCASE")] pub enum NoonPaymentData { Card(NoonCard), Subscription(NoonSubscription), ApplePay(NoonApplePay), GooglePay(NoonGooglePay), PayPal(NoonPayPal), } #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum NoonApiOperations { Initiate, Capture, Reverse, Refund, CancelSubscription, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonPaymentsRequest { api_operation: NoonApiOperations, order: NoonOrder, configuration: NoonConfiguration, payment_data: NoonPaymentData, subscription: Option<NoonSubscriptionData>, billing: Option<NoonBilling>, } impl TryFrom<&NoonRouterData<&PaymentsAuthorizeRouterData>> for NoonPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(data: &NoonRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { let item = data.router_data; let amount = &data.amount; let mandate_amount = &data.mandate_amount; let (payment_data, currency, category) = match item.request.connector_mandate_id() { Some(mandate_id) => ( NoonPaymentData::Subscription(NoonSubscription { subscription_identifier: Secret::new(mandate_id), }), None, None, ), _ => ( match item.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => Ok(NoonPaymentData::Card(NoonCard { name_on_card: item.get_optional_billing_full_name(), number_plain: req_card.card_number.clone(), expiry_month: req_card.card_exp_month.clone(), expiry_year: req_card.get_expiry_year_4_digit(), cvv: req_card.card_cvc, })), PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() { WalletData::GooglePay(google_pay_data) => { Ok(NoonPaymentData::GooglePay(NoonGooglePay { api_version_minor: GOOGLEPAY_API_VERSION_MINOR, api_version: GOOGLEPAY_API_VERSION, payment_method_data: GooglePayWalletData::try_from(google_pay_data) .change_context(errors::ConnectorError::InvalidDataFormat { field_name: "google_pay_data", })?, })) } WalletData::ApplePay(apple_pay_data) => { let payment_token_data = NoonApplePayTokenData { token: NoonApplePayData { payment_data: wallet_data .get_wallet_token_as_json("Apple Pay".to_string())?, payment_method: NoonApplePayPaymentMethod { display_name: apple_pay_data.payment_method.display_name, network: apple_pay_data.payment_method.network, pm_type: apple_pay_data.payment_method.pm_type, }, transaction_identifier: Secret::new( apple_pay_data.transaction_identifier, ), }, }; let payment_token = payment_token_data .encode_to_string_of_json() .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(NoonPaymentData::ApplePay(NoonApplePay { payment_info: Secret::new(payment_token), })) } WalletData::PaypalRedirect(_) => Ok(NoonPaymentData::PayPal(NoonPayPal { return_url: item.request.get_router_return_url()?, })), WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Noon"), )), }, PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Noon"), )) } }?, Some(item.request.currency), Some(item.request.order_category.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "order_category", }, )?), ), }; let ip_address = item.request.get_ip_address_as_optional(); let channel = NoonChannels::Web; let billing = item .get_optional_billing() .and_then(|billing_address| billing_address.address.as_ref()) .map(|address| NoonBilling { address: NoonBillingAddress { street: address.line1.clone(), street2: address.line2.clone(), city: address.city.clone(), // If state is passed in request, country becomes mandatory, keep a check while debugging failed payments state_province: address.state.clone(), country: address.country, postal_code: address.zip.clone(), }, }); // The description should not have leading or trailing whitespaces, also it should not have double whitespaces and a max 50 chars according to Noon's Docs let name: String = item .get_description()? .trim() .replace(" ", " ") .chars() .take(50) .collect(); let subscription = mandate_amount .as_ref() .map(|mandate_max_amount| NoonSubscriptionData { subscription_type: NoonSubscriptionType::Unscheduled, name: name.clone(), max_amount: mandate_max_amount.to_owned(), }); let tokenize_c_c = subscription.is_some().then_some(true); let order = NoonOrder { amount: amount.to_owned(), currency, channel, category, reference: item.connector_request_reference_id.clone(), name, nvp: item.request.metadata.as_ref().map(NoonOrderNvp::new), ip_address, }; let payment_action = if item.request.is_auto_capture()? { NoonPaymentActions::Sale } else { NoonPaymentActions::Authorize }; Ok(Self { api_operation: NoonApiOperations::Initiate, order, billing, configuration: NoonConfiguration { payment_action, return_url: item.request.router_return_url.clone(), tokenize_c_c, }, payment_data, subscription, }) } } // Auth Struct pub struct NoonAuthType { pub(super) api_key: Secret<String>, pub(super) application_identifier: Secret<String>, pub(super) business_identifier: Secret<String>, } impl TryFrom<&ConnectorAuthType> for NoonAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { api_key: api_key.to_owned(), application_identifier: api_secret.to_owned(), business_identifier: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Default, Debug, Deserialize, Serialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "UPPERCASE")] pub enum NoonPaymentStatus { Initiated, Authorized, Captured, PartiallyCaptured, PartiallyRefunded, PaymentInfoAdded, #[serde(rename = "3DS_ENROLL_INITIATED")] ThreeDsEnrollInitiated, #[serde(rename = "3DS_ENROLL_CHECKED")] ThreeDsEnrollChecked, #[serde(rename = "3DS_RESULT_VERIFIED")] ThreeDsResultVerified, MarkedForReview, Authenticated, PartiallyReversed, #[default] Pending, Cancelled, Failed, Refunded, Expired, Reversed, Rejected, Locked, } fn get_payment_status(data: (NoonPaymentStatus, AttemptStatus)) -> AttemptStatus { let (item, current_status) = data; match item { NoonPaymentStatus::Authorized => AttemptStatus::Authorized, NoonPaymentStatus::Captured | NoonPaymentStatus::PartiallyCaptured | NoonPaymentStatus::PartiallyRefunded | NoonPaymentStatus::Refunded => AttemptStatus::Charged, NoonPaymentStatus::Reversed | NoonPaymentStatus::PartiallyReversed => AttemptStatus::Voided, NoonPaymentStatus::Cancelled | NoonPaymentStatus::Expired => { AttemptStatus::AuthenticationFailed } NoonPaymentStatus::ThreeDsEnrollInitiated | NoonPaymentStatus::ThreeDsEnrollChecked => { AttemptStatus::AuthenticationPending } NoonPaymentStatus::ThreeDsResultVerified => AttemptStatus::AuthenticationSuccessful, NoonPaymentStatus::Failed | NoonPaymentStatus::Rejected => AttemptStatus::Failure, NoonPaymentStatus::Pending | NoonPaymentStatus::MarkedForReview => AttemptStatus::Pending, NoonPaymentStatus::Initiated | NoonPaymentStatus::PaymentInfoAdded | NoonPaymentStatus::Authenticated => AttemptStatus::Started, NoonPaymentStatus::Locked => current_status, } } #[derive(Debug, Serialize, Deserialize)] pub struct NoonSubscriptionObject { identifier: Secret<String>, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NoonPaymentsOrderResponse { status: NoonPaymentStatus, id: u64, error_code: u64, error_message: Option<String>, reference: Option<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NoonCheckoutData { post_url: url::Url, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NoonPaymentsResponseResult { order: NoonPaymentsOrderResponse, checkout_data: Option<NoonCheckoutData>, subscription: Option<NoonSubscriptionObject>, } #[derive(Debug, Serialize, Deserialize)] pub struct NoonPaymentsResponse { result: NoonPaymentsResponseResult, } impl<F, T> TryFrom<ResponseRouterData<F, NoonPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, NoonPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let order = item.response.result.order; let status = get_payment_status((order.status, item.data.status)); let redirection_data = item.response .result .checkout_data .map(|redirection_data| RedirectForm::Form { endpoint: redirection_data.post_url.to_string(), method: Method::Post, form_fields: std::collections::HashMap::new(), }); let mandate_reference = item.response .result .subscription .map(|subscription_data| MandateReference { connector_mandate_id: Some(subscription_data.identifier.expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }); Ok(Self { status, response: match order.error_message { Some(error_message) => Err(ErrorResponse { code: order.error_code.to_string(), message: error_message.clone(), reason: Some(error_message), status_code: item.http_code, attempt_status: Some(status), connector_transaction_id: Some(order.id.to_string()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), _ => { let connector_response_reference_id = order.reference.or(Some(order.id.to_string())); Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(order.id.to_string()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, charges: None, }) } }, ..item.data }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonActionTransaction { amount: StringMajorUnit, currency: enums::Currency, transaction_reference: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonActionOrder { id: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonPaymentsActionRequest { api_operation: NoonApiOperations, order: NoonActionOrder, transaction: NoonActionTransaction, } impl TryFrom<&NoonRouterData<&PaymentsCaptureRouterData>> for NoonPaymentsActionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(data: &NoonRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { let item = data.router_data; let amount = &data.amount; let order = NoonActionOrder { id: item.request.connector_transaction_id.clone(), }; let transaction = NoonActionTransaction { amount: amount.to_owned(), currency: item.request.currency, transaction_reference: None, }; Ok(Self { api_operation: NoonApiOperations::Capture, order, transaction, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonPaymentsCancelRequest { api_operation: NoonApiOperations, order: NoonActionOrder, } impl TryFrom<&PaymentsCancelRouterData> for NoonPaymentsCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let order = NoonActionOrder { id: item.request.connector_transaction_id.clone(), }; Ok(Self { api_operation: NoonApiOperations::Reverse, order, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonRevokeMandateRequest { api_operation: NoonApiOperations, subscription: NoonSubscriptionObject, } impl TryFrom<&MandateRevokeRouterData> for NoonRevokeMandateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &MandateRevokeRouterData) -> Result<Self, Self::Error> { Ok(Self { api_operation: NoonApiOperations::CancelSubscription, subscription: NoonSubscriptionObject { identifier: Secret::new(item.request.get_connector_mandate_id()?), }, }) } } impl<F> TryFrom<&NoonRouterData<&RefundsRouterData<F>>> for NoonPaymentsActionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(data: &NoonRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let item = data.router_data; let refund_amount = &data.amount; let order = NoonActionOrder { id: item.request.connector_transaction_id.clone(), }; let transaction = NoonActionTransaction { amount: refund_amount.to_owned(), currency: item.request.currency, transaction_reference: Some(item.request.refund_id.clone()), }; Ok(Self { api_operation: NoonApiOperations::Refund, order, transaction, }) } } #[derive(Debug, Deserialize, Serialize)] pub enum NoonRevokeStatus { Cancelled, } #[derive(Debug, Deserialize, Serialize)] pub struct NoonCancelSubscriptionObject { status: NoonRevokeStatus, } #[derive(Debug, Deserialize, Serialize)] pub struct NoonRevokeMandateResult { subscription: NoonCancelSubscriptionObject, } #[derive(Debug, Deserialize, Serialize)] pub struct NoonRevokeMandateResponse { result: NoonRevokeMandateResult, } impl<F> TryFrom< ResponseRouterData< F, NoonRevokeMandateResponse, MandateRevokeRequestData, MandateRevokeResponseData, >, > for RouterData<F, MandateRevokeRequestData, MandateRevokeResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, NoonRevokeMandateResponse, MandateRevokeRequestData, MandateRevokeResponseData, >, ) -> Result<Self, Self::Error> { match item.response.result.subscription.status { NoonRevokeStatus::Cancelled => Ok(Self { response: Ok(MandateRevokeResponseData { mandate_status: common_enums::MandateStatus::Revoked, }), ..item.data }), } } } #[derive(Debug, Default, Deserialize, Clone, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum RefundStatus { Success, Failed, #[default] Pending, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Success => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Pending => Self::Pending, } } } #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonPaymentsTransactionResponse { id: String, status: RefundStatus, } #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonRefundResponseResult { transaction: NoonPaymentsTransactionResponse, } #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundResponse { result: NoonRefundResponseResult, result_code: u32, class_description: String, message: String, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let response = &item.response; let refund_status = enums::RefundStatus::from(response.result.transaction.status.to_owned()); let response = if utils::is_refund_failure(refund_status) { Err(ErrorResponse { status_code: item.http_code, code: response.result_code.to_string(), message: response.class_description.clone(), reason: Some(response.message.clone()), attempt_status: None, connector_transaction_id: Some(response.result.transaction.id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(RefundsResponseData { connector_refund_id: item.response.result.transaction.id, refund_status, }) }; Ok(Self { response, ..item.data }) } } #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonRefundResponseTransactions { id: String, status: RefundStatus, transaction_reference: Option<String>, } #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonRefundSyncResponseResult { transactions: Vec<NoonRefundResponseTransactions>, } #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundSyncResponse { result: NoonRefundSyncResponseResult, result_code: u32, class_description: String, message: String, } impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundSyncResponse>, ) -> Result<Self, Self::Error> { let noon_transaction: &NoonRefundResponseTransactions = item .response .result .transactions .iter() .find(|transaction| { transaction .transaction_reference .clone() .is_some_and(|transaction_instance| { transaction_instance == item.data.request.refund_id }) }) .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; let refund_status = enums::RefundStatus::from(noon_transaction.status.to_owned()); let response = if utils::is_refund_failure(refund_status) { let response = &item.response; Err(ErrorResponse { status_code: item.http_code, code: response.result_code.to_string(), message: response.class_description.clone(), reason: Some(response.message.clone()), attempt_status: None, connector_transaction_id: Some(noon_transaction.id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(RefundsResponseData { connector_refund_id: noon_transaction.id.to_owned(), refund_status, }) }; Ok(Self { response, ..item.data }) } } #[derive(Debug, Deserialize, strum::Display)] pub enum NoonWebhookEventTypes { Authenticate, Authorize, Capture, Fail, Refund, Sale, #[serde(other)] Unknown, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NoonWebhookBody { pub order_id: u64, pub order_status: NoonPaymentStatus, pub event_type: NoonWebhookEventTypes, pub event_id: String, pub time_stamp: String, } #[derive(Debug, Deserialize)] pub struct NoonWebhookSignature { pub signature: String, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NoonWebhookOrderId { pub order_id: u64, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NoonWebhookEvent { pub order_status: NoonPaymentStatus, pub event_type: NoonWebhookEventTypes, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NoonWebhookObject { pub order_status: NoonPaymentStatus, pub order_id: u64, } /// This from will ensure that webhook body would be properly parsed into PSync response impl From<NoonWebhookObject> for NoonPaymentsResponse { fn from(value: NoonWebhookObject) -> Self { Self { result: NoonPaymentsResponseResult { order: NoonPaymentsOrderResponse { status: value.order_status, id: value.order_id, //For successful payments Noon Always populates error_code as 0. error_code: 0, error_message: None, reference: None, }, checkout_data: None, subscription: None, }, } } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonErrorResponse { pub result_code: u32, pub message: String, pub class_description: String, }
crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
hyperswitch_connectors::src::connectors::noon::transformers
7,040
true
// File: crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs // Module: hyperswitch_connectors::src::connectors::datatrans::transformers use std::collections::HashMap; use api_models::payments::{self, AdditionalPaymentData}; use common_enums::enums; use common_utils::{pii::Email, request::Method, types::MinorUnit}; use hyperswitch_domain_models::{ payment_method_data::{Card, PaymentMethodData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{PaymentsAuthorizeData, ResponseId, SetupMandateRequestData}, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types, }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors, }; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{ PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData, }, utils::{ get_unimplemented_payment_method_error_message, AdditionalCardInfo, CardData as _, PaymentsAuthorizeRequestData, RouterData as _, }, }; const TRANSACTION_ALREADY_CANCELLED: &str = "transaction already canceled"; const TRANSACTION_ALREADY_SETTLED: &str = "already settled"; const REDIRECTION_SBX_URL: &str = "https://pay.sandbox.datatrans.com"; const REDIRECTION_PROD_URL: &str = "https://pay.datatrans.com"; #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct DatatransErrorResponse { pub error: DatatransError, } pub struct DatatransAuthType { pub(super) merchant_id: Secret<String>, pub(super) passcode: Secret<String>, } pub struct DatatransRouterData<T> { pub amount: MinorUnit, pub router_data: T, } #[derive(Debug, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct DatatransPaymentsRequest { pub amount: Option<MinorUnit>, pub currency: enums::Currency, pub card: DataTransPaymentDetails, pub refno: String, pub auto_settle: bool, #[serde(skip_serializing_if = "Option::is_none")] pub redirect: Option<RedirectUrls>, pub option: Option<DataTransCreateAlias>, } #[derive(Debug, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct DataTransCreateAlias { pub create_alias: bool, } #[derive(Debug, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct RedirectUrls { pub success_url: Option<String>, pub cancel_url: Option<String>, pub error_url: Option<String>, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "snake_case")] pub enum TransactionType { Payment, Credit, CardCheck, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "snake_case")] pub enum TransactionStatus { Initialized, Authenticated, Authorized, Settled, Canceled, Transmitted, Failed, ChallengeOngoing, ChallengeRequired, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(untagged)] pub enum DatatransSyncResponse { Error(DatatransError), Response(SyncResponse), } #[derive(Debug, Deserialize, Serialize)] pub enum DataTransCaptureResponse { Error(DatatransError), Empty, } #[derive(Debug, Deserialize, Serialize)] pub enum DataTransCancelResponse { Error(DatatransError), Empty, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct SyncResponse { pub transaction_id: String, #[serde(rename = "type")] pub res_type: TransactionType, pub status: TransactionStatus, pub detail: SyncDetails, pub card: Option<SyncCardDetails>, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct SyncCardDetails { pub alias: Option<String>, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct SyncDetails { fail: Option<FailDetails>, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct FailDetails { reason: Option<String>, message: Option<String>, } #[derive(Serialize, Clone, Debug)] #[serde(rename_all = "camelCase")] #[serde(untagged)] pub enum DataTransPaymentDetails { Cards(PlainCardDetails), Mandate(MandateDetails), } #[derive(Serialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct PlainCardDetails { #[serde(rename = "type")] pub res_type: String, pub number: cards::CardNumber, pub expiry_month: Secret<String>, pub expiry_year: Secret<String>, pub cvv: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "3D")] pub three_ds: Option<ThreeDSecureData>, } #[derive(Serialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct MandateDetails { #[serde(rename = "type")] pub res_type: String, pub alias: String, pub expiry_month: Secret<String>, pub expiry_year: Secret<String>, } #[derive(Serialize, Clone, Debug)] pub struct ThreedsInfo { cardholder: CardHolder, } #[derive(Serialize, Clone, Debug)] #[serde(untagged)] pub enum ThreeDSecureData { Cardholder(ThreedsInfo), Authentication(ThreeDSData), } #[derive(Debug, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct ThreeDSData { #[serde(rename = "threeDSTransactionId")] pub three_ds_transaction_id: Option<Secret<String>>, pub cavv: Secret<String>, pub eci: Option<String>, pub xid: Option<Secret<String>>, #[serde(rename = "threeDSVersion")] pub three_ds_version: Option<String>, #[serde(rename = "authenticationResponse")] pub authentication_response: String, } #[derive(Debug, Serialize, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardHolder { cardholder_name: Secret<String>, email: Email, } #[derive(Debug, Clone, Serialize, Default, Deserialize)] pub struct DatatransError { pub code: String, pub message: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DatatransResponse { TransactionResponse(DatatransSuccessResponse), ErrorResponse(DatatransError), ThreeDSResponse(Datatrans3DSResponse), } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DatatransSuccessResponse { pub transaction_id: String, pub acquirer_authorization_code: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DatatransRefundsResponse { Success(DatatransSuccessResponse), Error(DatatransError), } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Datatrans3DSResponse { pub transaction_id: String, #[serde(rename = "3D")] pub three_ds_enrolled: ThreeDSEnolled, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeDSEnolled { pub enrolled: bool, } #[derive(Default, Debug, Serialize)] pub struct DatatransRefundRequest { pub amount: MinorUnit, pub currency: enums::Currency, pub refno: String, } #[derive(Debug, Serialize, Clone)] pub struct DataPaymentCaptureRequest { pub amount: MinorUnit, pub currency: enums::Currency, pub refno: String, } impl<T> TryFrom<(MinorUnit, T)> for DatatransRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } } impl TryFrom<&types::SetupMandateRouterData> for DatatransPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => Ok(Self { amount: None, currency: item.request.currency, card: DataTransPaymentDetails::Cards(PlainCardDetails { res_type: "PLAIN".to_string(), number: req_card.card_number.clone(), expiry_month: req_card.card_exp_month.clone(), expiry_year: req_card.get_card_expiry_year_2_digit()?, cvv: req_card.card_cvc.clone(), three_ds: Some(ThreeDSecureData::Cardholder(ThreedsInfo { cardholder: CardHolder { cardholder_name: item.get_billing_full_name()?, email: item.get_billing_email()?, }, })), }), refno: item.connector_request_reference_id.clone(), auto_settle: true, // zero auth doesn't support manual capture option: Some(DataTransCreateAlias { create_alias: true }), redirect: Some(RedirectUrls { success_url: item.request.router_return_url.clone(), cancel_url: item.request.router_return_url.clone(), error_url: item.request.router_return_url.clone(), }), }), PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Crypto(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Datatrans"), ))? } } } } impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>> for DatatransPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let is_mandate_payment = item.router_data.request.is_mandate_payment(); let option = is_mandate_payment.then_some(DataTransCreateAlias { create_alias: true }); // provides return url for only mandate payment(CIT) or 3ds through datatrans let redirect = if is_mandate_payment || (item.router_data.is_three_ds() && item.router_data.request.authentication_data.is_none()) { Some(RedirectUrls { success_url: item.router_data.request.router_return_url.clone(), cancel_url: item.router_data.request.router_return_url.clone(), error_url: item.router_data.request.router_return_url.clone(), }) } else { None }; Ok(Self { amount: Some(item.amount), currency: item.router_data.request.currency, card: create_card_details(item, &req_card)?, refno: item.router_data.connector_request_reference_id.clone(), auto_settle: item.router_data.request.is_auto_capture()?, option, redirect, }) } PaymentMethodData::MandatePayment => { let additional_payment_data = match item .router_data .request .additional_payment_method_data .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "additional_payment_method_data", })? { AdditionalPaymentData::Card(card) => *card, _ => Err(errors::ConnectorError::NotSupported { message: "Payment Method Not Supported".to_string(), connector: "DataTrans", })?, }; Ok(Self { amount: Some(item.amount), currency: item.router_data.request.currency, card: create_mandate_details(item, &additional_payment_data)?, refno: item.router_data.connector_request_reference_id.clone(), auto_settle: item.router_data.request.is_auto_capture()?, option: None, redirect: None, }) } PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Datatrans"), ))? } } } } impl TryFrom<&ConnectorAuthType> for DatatransAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { merchant_id: key1.clone(), passcode: api_key.clone(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } fn get_status(item: &DatatransResponse, is_auto_capture: bool) -> enums::AttemptStatus { match item { DatatransResponse::ErrorResponse(_) => enums::AttemptStatus::Failure, DatatransResponse::TransactionResponse(_) => { if is_auto_capture { enums::AttemptStatus::Charged } else { enums::AttemptStatus::Authorized } } DatatransResponse::ThreeDSResponse(_) => enums::AttemptStatus::AuthenticationPending, } } fn create_card_details( item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>, card: &Card, ) -> Result<DataTransPaymentDetails, error_stack::Report<errors::ConnectorError>> { let mut details = PlainCardDetails { res_type: "PLAIN".to_string(), number: card.card_number.clone(), expiry_month: card.card_exp_month.clone(), expiry_year: card.get_card_expiry_year_2_digit()?, cvv: card.card_cvc.clone(), three_ds: None, }; if let Some(auth_data) = &item.router_data.request.authentication_data { details.three_ds = Some(ThreeDSecureData::Authentication(ThreeDSData { three_ds_transaction_id: auth_data .threeds_server_transaction_id .clone() .map(Secret::new), cavv: auth_data.cavv.clone(), eci: auth_data.eci.clone(), xid: auth_data.ds_trans_id.clone().map(Secret::new), three_ds_version: auth_data .message_version .clone() .map(|version| version.to_string()), authentication_response: "Y".to_string(), })); } else if item.router_data.is_three_ds() { details.three_ds = Some(ThreeDSecureData::Cardholder(ThreedsInfo { cardholder: CardHolder { cardholder_name: item.router_data.get_billing_full_name()?, email: item.router_data.get_billing_email()?, }, })); } Ok(DataTransPaymentDetails::Cards(details)) } fn create_mandate_details( item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>, additional_card_details: &payments::AdditionalCardInfo, ) -> Result<DataTransPaymentDetails, error_stack::Report<errors::ConnectorError>> { let alias = item.router_data.request.get_connector_mandate_id()?; Ok(DataTransPaymentDetails::Mandate(MandateDetails { res_type: "ALIAS".to_string(), alias, expiry_month: additional_card_details.card_exp_month.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "card_exp_month", }, )?, expiry_year: additional_card_details.get_card_expiry_year_2_digit()?, })) } impl From<SyncResponse> for enums::AttemptStatus { fn from(item: SyncResponse) -> Self { match item.res_type { TransactionType::Payment => match item.status { TransactionStatus::Authorized => Self::Authorized, TransactionStatus::Settled | TransactionStatus::Transmitted => Self::Charged, TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => { Self::AuthenticationPending } TransactionStatus::Canceled => Self::Voided, TransactionStatus::Failed => Self::Failure, TransactionStatus::Initialized | TransactionStatus::Authenticated => Self::Pending, }, TransactionType::CardCheck => match item.status { TransactionStatus::Settled | TransactionStatus::Transmitted | TransactionStatus::Authorized => Self::Charged, TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => { Self::AuthenticationPending } TransactionStatus::Canceled => Self::Voided, TransactionStatus::Failed => Self::Failure, TransactionStatus::Initialized | TransactionStatus::Authenticated => Self::Pending, }, TransactionType::Credit => Self::Failure, } } } impl From<SyncResponse> for enums::RefundStatus { fn from(item: SyncResponse) -> Self { match item.res_type { TransactionType::Credit => match item.status { TransactionStatus::Settled | TransactionStatus::Transmitted => Self::Success, TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => { Self::Pending } TransactionStatus::Initialized | TransactionStatus::Authenticated | TransactionStatus::Authorized | TransactionStatus::Canceled | TransactionStatus::Failed => Self::Failure, }, TransactionType::Payment | TransactionType::CardCheck => Self::Failure, } } } impl<F> TryFrom<ResponseRouterData<F, DatatransResponse, PaymentsAuthorizeData, PaymentsResponseData>> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, DatatransResponse, PaymentsAuthorizeData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let status = get_status(&item.response, item.data.request.is_auto_capture()?); let response = match &item.response { DatatransResponse::ErrorResponse(error) => Err(ErrorResponse { code: error.code.clone(), message: error.message.clone(), reason: Some(error.message.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), DatatransResponse::TransactionResponse(response) => { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( response.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) } DatatransResponse::ThreeDSResponse(response) => { let redirection_link = match item.data.test_mode { Some(true) => format!("{REDIRECTION_SBX_URL}/v1/start"), Some(false) | None => format!("{REDIRECTION_PROD_URL}/v1/start"), }; Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( response.transaction_id.clone(), ), redirection_data: Box::new(Some(RedirectForm::Form { endpoint: format!("{}/{}", redirection_link, response.transaction_id), method: Method::Get, form_fields: HashMap::new(), })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) } }; Ok(Self { status, response, ..item.data }) } } impl<F> TryFrom<ResponseRouterData<F, DatatransResponse, SetupMandateRequestData, PaymentsResponseData>> for RouterData<F, SetupMandateRequestData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, DatatransResponse, SetupMandateRequestData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { // zero auth doesn't support manual capture let status = get_status(&item.response, true); let response = match &item.response { DatatransResponse::ErrorResponse(error) => Err(ErrorResponse { code: error.code.clone(), message: error.message.clone(), reason: Some(error.message.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), DatatransResponse::TransactionResponse(response) => { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( response.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) } DatatransResponse::ThreeDSResponse(response) => { let redirection_link = match item.data.test_mode { Some(true) => format!("{REDIRECTION_SBX_URL}/v1/start"), Some(false) | None => format!("{REDIRECTION_PROD_URL}/v1/start"), }; Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( response.transaction_id.clone(), ), redirection_data: Box::new(Some(RedirectForm::Form { endpoint: format!("{}/{}", redirection_link, response.transaction_id), method: Method::Get, form_fields: HashMap::new(), })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) } }; Ok(Self { status, response, ..item.data }) } } impl<F> TryFrom<&DatatransRouterData<&types::RefundsRouterData<F>>> for DatatransRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DatatransRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), currency: item.router_data.request.currency, refno: item.router_data.request.refund_id.clone(), }) } } impl TryFrom<RefundsResponseRouterData<Execute, DatatransRefundsResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, DatatransRefundsResponse>, ) -> Result<Self, Self::Error> { match item.response { DatatransRefundsResponse::Error(error) => Ok(Self { response: Err(ErrorResponse { code: error.code.clone(), message: error.message.clone(), reason: Some(error.message), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), DatatransRefundsResponse::Success(response) => Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: response.transaction_id, refund_status: enums::RefundStatus::Success, }), ..item.data }), } } } impl TryFrom<RefundsResponseRouterData<RSync, DatatransSyncResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, DatatransSyncResponse>, ) -> Result<Self, Self::Error> { let response = match item.response { DatatransSyncResponse::Error(error) => Err(ErrorResponse { code: error.code.clone(), message: error.message.clone(), reason: Some(error.message), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), DatatransSyncResponse::Response(response) => Ok(RefundsResponseData { connector_refund_id: response.transaction_id.to_string(), refund_status: enums::RefundStatus::from(response), }), }; Ok(Self { response, ..item.data }) } } impl TryFrom<PaymentsSyncResponseRouterData<DatatransSyncResponse>> for types::PaymentsSyncRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsSyncResponseRouterData<DatatransSyncResponse>, ) -> Result<Self, Self::Error> { match item.response { DatatransSyncResponse::Error(error) => { let response = Err(ErrorResponse { code: error.code.clone(), message: error.message.clone(), reason: Some(error.message), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); Ok(Self { response, ..item.data }) } DatatransSyncResponse::Response(sync_response) => { let status = enums::AttemptStatus::from(sync_response.clone()); let response = if status == enums::AttemptStatus::Failure { let (code, message) = match sync_response.detail.fail { Some(fail_details) => ( fail_details.reason.unwrap_or(NO_ERROR_CODE.to_string()), fail_details.message.unwrap_or(NO_ERROR_MESSAGE.to_string()), ), None => (NO_ERROR_CODE.to_string(), NO_ERROR_MESSAGE.to_string()), }; Err(ErrorResponse { code, message: message.clone(), reason: Some(message), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { let mandate_reference = sync_response .card .as_ref() .and_then(|card| card.alias.as_ref()) .map(|alias| MandateReference { connector_mandate_id: Some(alias.clone()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }); Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( sync_response.transaction_id.to_string(), ), redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) }; Ok(Self { status, response, ..item.data }) } } } } impl TryFrom<&DatatransRouterData<&types::PaymentsCaptureRouterData>> for DataPaymentCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DatatransRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount, currency: item.router_data.request.currency, refno: item.router_data.connector_request_reference_id.clone(), }) } } impl TryFrom<PaymentsCaptureResponseRouterData<DataTransCaptureResponse>> for types::PaymentsCaptureRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsCaptureResponseRouterData<DataTransCaptureResponse>, ) -> Result<Self, Self::Error> { let status = match item.response { DataTransCaptureResponse::Error(error) => { if error.message == *TRANSACTION_ALREADY_SETTLED { common_enums::AttemptStatus::Charged } else { common_enums::AttemptStatus::Failure } } // Datatrans http code 204 implies Successful Capture //https://api-reference.datatrans.ch/#tag/v1transactions/operation/settle DataTransCaptureResponse::Empty => { if item.http_code == 204 { common_enums::AttemptStatus::Charged } else { common_enums::AttemptStatus::Failure } } }; Ok(Self { status, ..item.data }) } } impl TryFrom<PaymentsCancelResponseRouterData<DataTransCancelResponse>> for types::PaymentsCancelRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsCancelResponseRouterData<DataTransCancelResponse>, ) -> Result<Self, Self::Error> { let status = match item.response { // Datatrans http code 204 implies Successful Cancellation //https://api-reference.datatrans.ch/#tag/v1transactions/operation/cancel DataTransCancelResponse::Empty => { if item.http_code == 204 { common_enums::AttemptStatus::Voided } else { common_enums::AttemptStatus::Failure } } DataTransCancelResponse::Error(error) => { if error.message == *TRANSACTION_ALREADY_CANCELLED { common_enums::AttemptStatus::Voided } else { common_enums::AttemptStatus::Failure } } }; Ok(Self { status, ..item.data }) } }
crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
hyperswitch_connectors::src::connectors::datatrans::transformers
6,931
true
// File: crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs // Module: hyperswitch_connectors::src::connectors::jpmorgan::transformers use std::str::FromStr; use common_enums::enums::CaptureMethod; use common_utils::types::MinorUnit; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{PaymentsCancelData, ResponseId}, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, RefreshTokenRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ get_unimplemented_payment_method_error_message, CardData, RouterData as OtherRouterData, }, }; pub struct JpmorganRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> From<(MinorUnit, T)> for JpmorganRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Clone, Serialize)] pub struct JpmorganAuthUpdateRequest { pub grant_type: String, pub scope: String, } #[derive(Debug, Serialize, Deserialize)] pub struct JpmorganAuthUpdateResponse { pub access_token: Secret<String>, pub scope: String, pub token_type: String, pub expires_in: i64, } impl TryFrom<&RefreshTokenRouterData> for JpmorganAuthUpdateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(_item: &RefreshTokenRouterData) -> Result<Self, Self::Error> { Ok(Self { grant_type: String::from("client_credentials"), scope: String::from("jpm:payments:sandbox"), }) } } impl<F, T> TryFrom<ResponseRouterData<F, JpmorganAuthUpdateResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, JpmorganAuthUpdateResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(AccessToken { token: item.response.access_token, expires: item.response.expires_in, }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganPaymentsRequest { capture_method: CapMethod, amount: MinorUnit, currency: common_enums::Currency, merchant: JpmorganMerchant, payment_method_type: JpmorganPaymentMethodType, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganCard { account_number: Secret<String>, expiry: Expiry, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganPaymentMethodType { card: JpmorganCard, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Expiry { month: Secret<i32>, year: Secret<i32>, } #[derive(Serialize, Debug, Default, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganMerchantSoftware { company_name: Secret<String>, product_name: Secret<String>, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganMerchant { merchant_software: JpmorganMerchantSoftware, } fn map_capture_method( capture_method: CaptureMethod, ) -> Result<CapMethod, error_stack::Report<errors::ConnectorError>> { match capture_method { CaptureMethod::Automatic => Ok(CapMethod::Now), CaptureMethod::Manual => Ok(CapMethod::Manual), CaptureMethod::Scheduled | CaptureMethod::ManualMultiple | CaptureMethod::SequentialAutomatic => { Err(errors::ConnectorError::NotImplemented("Capture Method".to_string()).into()) } } } impl TryFrom<&JpmorganRouterData<&PaymentsAuthorizeRouterData>> for JpmorganPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &JpmorganRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { if item.router_data.is_three_ds() { return Err(errors::ConnectorError::NotSupported { message: "3DS payments".to_string(), connector: "Jpmorgan", } .into()); } let capture_method = map_capture_method(item.router_data.request.capture_method.unwrap_or_default()); let merchant_software = JpmorganMerchantSoftware { company_name: String::from("JPMC").into(), product_name: String::from("Hyperswitch").into(), }; let merchant = JpmorganMerchant { merchant_software }; let expiry: Expiry = Expiry { month: Secret::new( req_card .card_exp_month .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::RequestEncodingFailed)?, ), year: req_card.get_expiry_year_as_4_digit_i32()?, }; let account_number = Secret::new(req_card.card_number.to_string()); let card = JpmorganCard { account_number, expiry, }; let payment_method_type = JpmorganPaymentMethodType { card }; Ok(Self { capture_method: capture_method?, currency: item.router_data.request.currency, amount: item.amount, merchant, payment_method_type, }) } PaymentMethodData::CardDetailsForNetworkTransactionId(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("jpmorgan"), ) .into()), } } } //JP Morgan uses access token only due to which we aren't reading the fields in this struct #[derive(Debug)] pub struct JpmorganAuthType { pub(super) _api_key: Secret<String>, pub(super) _key1: Secret<String>, } impl TryFrom<&ConnectorAuthType> for JpmorganAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { _api_key: api_key.to_owned(), _key1: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum JpmorganTransactionStatus { Success, Denied, Error, } #[derive(Default, Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "UPPERCASE")] pub enum JpmorganTransactionState { Closed, Authorized, Voided, #[default] Pending, Declined, Error, } #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganPaymentsResponse { transaction_id: String, request_id: String, transaction_state: JpmorganTransactionState, response_status: String, response_code: String, response_message: String, payment_method_type: PaymentMethodType, capture_method: Option<CapMethod>, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Merchant { merchant_id: Option<String>, merchant_software: JpmorganMerchantSoftware, merchant_category_code: Option<String>, } #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentMethodType { card: Option<Card>, } #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Card { expiry: Option<ExpiryResponse>, card_type: Option<Secret<String>>, card_type_name: Option<Secret<String>>, masked_account_number: Option<Secret<String>>, card_type_indicators: Option<CardTypeIndicators>, network_response: Option<NetworkResponse>, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NetworkResponse { address_verification_result: Option<Secret<String>>, address_verification_result_code: Option<Secret<String>>, card_verification_result_code: Option<Secret<String>>, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ExpiryResponse { month: Option<Secret<i32>>, year: Option<Secret<i32>>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardTypeIndicators { issuance_country_code: Option<Secret<String>>, is_durbin_regulated: Option<bool>, card_product_types: Secret<Vec<String>>, } pub fn attempt_status_from_transaction_state( transaction_state: JpmorganTransactionState, ) -> common_enums::AttemptStatus { match transaction_state { JpmorganTransactionState::Authorized => common_enums::AttemptStatus::Authorized, JpmorganTransactionState::Closed => common_enums::AttemptStatus::Charged, JpmorganTransactionState::Declined | JpmorganTransactionState::Error => { common_enums::AttemptStatus::Failure } JpmorganTransactionState::Pending => common_enums::AttemptStatus::Pending, JpmorganTransactionState::Voided => common_enums::AttemptStatus::Voided, } } impl<F, T> TryFrom<ResponseRouterData<F, JpmorganPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, JpmorganPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let transaction_state = match item.response.transaction_state { JpmorganTransactionState::Closed => match item.response.capture_method { Some(CapMethod::Now) => JpmorganTransactionState::Closed, _ => JpmorganTransactionState::Authorized, }, JpmorganTransactionState::Authorized => JpmorganTransactionState::Authorized, JpmorganTransactionState::Voided => JpmorganTransactionState::Voided, JpmorganTransactionState::Pending => JpmorganTransactionState::Pending, JpmorganTransactionState::Declined => JpmorganTransactionState::Declined, JpmorganTransactionState::Error => JpmorganTransactionState::Error, }; let status = attempt_status_from_transaction_state(transaction_state); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.transaction_id.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganCaptureRequest { capture_method: Option<CapMethod>, amount: MinorUnit, currency: Option<common_enums::Currency>, } #[derive(Debug, Default, Copy, Serialize, Deserialize, Clone)] #[serde(rename_all = "UPPERCASE")] pub enum CapMethod { #[default] Now, Delayed, Manual, } impl TryFrom<&JpmorganRouterData<&PaymentsCaptureRouterData>> for JpmorganCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &JpmorganRouterData<&PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { let capture_method = Some(map_capture_method( item.router_data.request.capture_method.unwrap_or_default(), )?); Ok(Self { capture_method, amount: item.amount, currency: Some(item.router_data.request.currency), }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganCaptureResponse { pub transaction_id: String, pub request_id: String, pub transaction_state: JpmorganTransactionState, pub response_status: JpmorganTransactionStatus, pub response_code: String, pub response_message: String, pub payment_method_type: PaymentMethodTypeCapRes, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentMethodTypeCapRes { pub card: Option<CardCapRes>, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardCapRes { pub card_type: Option<Secret<String>>, pub card_type_name: Option<Secret<String>>, unmasked_account_number: Option<Secret<String>>, } impl<F, T> TryFrom<ResponseRouterData<F, JpmorganCaptureResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, JpmorganCaptureResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let status = attempt_status_from_transaction_state(item.response.transaction_state); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.transaction_id.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganPSyncResponse { transaction_id: String, transaction_state: JpmorganTransactionState, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum JpmorganResponseStatus { Success, Denied, Error, } impl<F, PaymentsSyncData> TryFrom<ResponseRouterData<F, JpmorganPSyncResponse, PaymentsSyncData, PaymentsResponseData>> for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, JpmorganPSyncResponse, PaymentsSyncData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let status = attempt_status_from_transaction_state(item.response.transaction_state); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.transaction_id.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct TransactionData { payment_type: Option<Secret<String>>, status_code: Secret<i32>, txn_secret: Option<Secret<String>>, tid: Option<Secret<i64>>, test_mode: Option<Secret<i8>>, status: Option<JpmorganTransactionStatus>, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganRefundRequest { pub merchant: MerchantRefundReq, pub amount: MinorUnit, pub currency: common_enums::Currency, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MerchantRefundReq { pub merchant_software: JpmorganMerchantSoftware, } impl<F> TryFrom<&JpmorganRouterData<&RefundsRouterData<F>>> for JpmorganRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &JpmorganRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let merchant_software = JpmorganMerchantSoftware { company_name: String::from("JPMC").into(), product_name: String::from("Hyperswitch").into(), }; let merchant = MerchantRefundReq { merchant_software }; let amount = item.amount; let currency = item.router_data.request.currency; Ok(Self { merchant, amount, currency, }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganRefundResponse { pub transaction_id: Option<String>, pub request_id: String, pub transaction_state: JpmorganTransactionState, pub amount: MinorUnit, pub currency: common_enums::Currency, pub response_status: JpmorganResponseStatus, pub response_code: String, pub response_message: String, pub transaction_reference_id: Option<String>, pub remaining_refundable_amount: Option<i64>, } #[derive(Debug, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for common_enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, } } } impl From<(JpmorganResponseStatus, JpmorganTransactionState)> for RefundStatus { fn from( (response_status, transaction_state): (JpmorganResponseStatus, JpmorganTransactionState), ) -> Self { match response_status { JpmorganResponseStatus::Success => match transaction_state { JpmorganTransactionState::Voided | JpmorganTransactionState::Closed => { Self::Succeeded } JpmorganTransactionState::Declined | JpmorganTransactionState::Error => { Self::Failed } JpmorganTransactionState::Pending | JpmorganTransactionState::Authorized => { Self::Processing } }, JpmorganResponseStatus::Denied | JpmorganResponseStatus::Error => Self::Failed, } } } impl TryFrom<RefundsResponseRouterData<Execute, JpmorganRefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, JpmorganRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item .response .transaction_id .clone() .ok_or(errors::ConnectorError::ResponseHandlingFailed)?, refund_status: RefundStatus::from(( item.response.response_status, item.response.transaction_state, )) .into(), }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganRefundSyncResponse { transaction_id: String, request_id: String, transaction_state: JpmorganTransactionState, amount: MinorUnit, currency: common_enums::Currency, response_status: JpmorganResponseStatus, response_code: String, } impl TryFrom<RefundsResponseRouterData<RSync, JpmorganRefundSyncResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, JpmorganRefundSyncResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction_id.clone(), refund_status: RefundStatus::from(( item.response.response_status, item.response.transaction_state, )) .into(), }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum ReversalReason { NoResponse, LateResponse, UnableToDeliver, CardDeclined, MacNotVerified, MacSyncError, ZekSyncError, SystemMalfunction, SuspectedFraud, } impl FromStr for ReversalReason { type Err = error_stack::Report<errors::ConnectorError>; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_uppercase().as_str() { "NO_RESPONSE" => Ok(Self::NoResponse), "LATE_RESPONSE" => Ok(Self::LateResponse), "UNABLE_TO_DELIVER" => Ok(Self::UnableToDeliver), "CARD_DECLINED" => Ok(Self::CardDeclined), "MAC_NOT_VERIFIED" => Ok(Self::MacNotVerified), "MAC_SYNC_ERROR" => Ok(Self::MacSyncError), "ZEK_SYNC_ERROR" => Ok(Self::ZekSyncError), "SYSTEM_MALFUNCTION" => Ok(Self::SystemMalfunction), "SUSPECTED_FRAUD" => Ok(Self::SuspectedFraud), _ => Err(report!(errors::ConnectorError::InvalidDataFormat { field_name: "cancellation_reason", })), } } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganCancelRequest { pub amount: Option<i64>, pub is_void: Option<bool>, pub reversal_reason: Option<ReversalReason>, } impl TryFrom<JpmorganRouterData<&PaymentsCancelRouterData>> for JpmorganCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: JpmorganRouterData<&PaymentsCancelRouterData>) -> Result<Self, Self::Error> { Ok(Self { amount: item.router_data.request.amount, is_void: Some(true), reversal_reason: item .router_data .request .cancellation_reason .as_ref() .map(|reason| ReversalReason::from_str(reason)) .transpose()?, }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganCancelResponse { transaction_id: String, request_id: String, response_status: JpmorganResponseStatus, response_code: String, response_message: String, payment_method_type: JpmorganPaymentMethodTypeCancelResponse, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganPaymentMethodTypeCancelResponse { pub card: CardCancelResponse, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardCancelResponse { pub card_type: Secret<String>, pub card_type_name: Secret<String>, } impl<F> TryFrom<ResponseRouterData<F, JpmorganCancelResponse, PaymentsCancelData, PaymentsResponseData>> for RouterData<F, PaymentsCancelData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, JpmorganCancelResponse, PaymentsCancelData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = match item.response.response_status { JpmorganResponseStatus::Success => common_enums::AttemptStatus::Voided, JpmorganResponseStatus::Denied | JpmorganResponseStatus::Error => { common_enums::AttemptStatus::Failure } }; Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.transaction_id.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct JpmorganValidationErrors { pub code: Option<String>, pub message: Option<String>, pub entity: Option<String>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct JpmorganErrorInformation { pub code: Option<String>, pub message: Option<String>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct JpmorganErrorResponse { pub response_status: JpmorganTransactionStatus, pub response_code: String, pub response_message: Option<String>, }
crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
hyperswitch_connectors::src::connectors::jpmorgan::transformers
5,817
true
// File: crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs // Module: hyperswitch_connectors::src::connectors::bluesnap::transformers use std::collections::HashMap; use api_models::{ payments::{ AmountInfo, ApplePayPaymentRequest, ApplePaySessionResponse, ApplepayCombinedSessionTokenData, ApplepaySessionTokenData, ApplepaySessionTokenMetadata, ApplepaySessionTokenResponse, NextActionCall, NoThirdPartySdkSessionResponse, SdkNextAction, SessionToken, }, webhooks::IncomingWebhookEvent, }; use base64::Engine; use common_enums::{enums, CountryAlpha2}; use common_utils::{ consts::{APPLEPAY_VALIDATION_URL, BASE64_ENGINE}, errors::CustomResult, ext_traits::{ByteSliceExt, Encode, OptionExt, StringExt, ValueExt}, pii::Email, types::{FloatMajorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ address::AddressDetails, payment_method_data::{self, PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::{ types::{PaymentsSessionResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ self, AddressDetailsData, ApplePay, CardData as _, ForeignTryFrom, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, RouterData as _, }, }; const DISPLAY_METADATA: &str = "Y"; #[derive(Debug, Serialize)] pub struct BluesnapRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> TryFrom<(StringMajorUnit, T)> for BluesnapRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapPaymentsRequest { amount: StringMajorUnit, #[serde(flatten)] payment_method: PaymentMethodDetails, currency: enums::Currency, card_transaction_type: BluesnapTxnType, transaction_fraud_info: Option<TransactionFraudInfo>, card_holder_info: Option<BluesnapCardHolderInfo>, merchant_transaction_id: Option<String>, transaction_meta_data: Option<BluesnapMetadata>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapMetadata { meta_data: Vec<RequestMetadata>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RequestMetadata { meta_key: Option<String>, meta_value: Option<String>, is_visible: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapCardHolderInfo { first_name: Secret<String>, last_name: Secret<String>, email: Email, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TransactionFraudInfo { fraud_session_id: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapCreateWalletToken { wallet_type: String, validation_url: Secret<String>, domain_name: String, display_name: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapThreeDSecureInfo { three_d_secure_reference_id: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum PaymentMethodDetails { CreditCard(Card), Wallet(BluesnapWallet), } #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Card { card_number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, security_code: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapWallet { wallet_type: BluesnapWalletTypes, encoded_payment_token: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapGooglePayObject { payment_method_data: utils::GooglePayWalletData, } #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BluesnapWalletTypes { GooglePay, ApplePay, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct EncodedPaymentToken { billing_contact: BillingDetails, token: ApplepayPaymentData, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BillingDetails { country_code: Option<CountryAlpha2>, address_lines: Option<Vec<Secret<String>>>, family_name: Option<Secret<String>>, given_name: Option<Secret<String>>, postal_code: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct ApplepayPaymentData { payment_data: ApplePayEncodedPaymentData, payment_method: ApplepayPaymentMethod, transaction_identifier: String, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct ApplepayPaymentMethod { display_name: String, network: String, #[serde(rename = "type")] pm_type: String, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ApplePayEncodedPaymentData { data: String, header: Option<ApplepayHeader>, signature: String, version: String, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct ApplepayHeader { ephemeral_public_key: Secret<String>, public_key_hash: Secret<String>, transaction_id: Secret<String>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct BluesnapConnectorMetaData { pub merchant_id: common_utils::id_type::MerchantId, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapPaymentsTokenRequest { cc_number: cards::CardNumber, exp_date: Secret<String>, } impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for BluesnapPaymentsTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BluesnapRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref ccard) => Ok(Self { cc_number: ccard.card_number.clone(), exp_date: ccard.get_expiry_date_as_mmyyyy("/"), }), PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( "Selected payment method via Token flow through bluesnap".to_string(), ) .into()) } } } } impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for BluesnapPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BluesnapRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let auth_mode = match item.router_data.request.capture_method { Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly, _ => BluesnapTxnType::AuthCapture, }; let transaction_meta_data = item.router_data .request .metadata .as_ref() .map(|metadata| BluesnapMetadata { meta_data: convert_metadata_to_request_metadata(metadata.to_owned()), }); let (payment_method, card_holder_info) = match item .router_data .request .payment_method_data .clone() { PaymentMethodData::Card(ref ccard) => Ok(( PaymentMethodDetails::CreditCard(Card { card_number: ccard.card_number.clone(), expiration_month: ccard.card_exp_month.clone(), expiration_year: ccard.get_expiry_year_4_digit(), security_code: ccard.card_cvc.clone(), }), get_card_holder_info( item.router_data.get_billing_address()?, item.router_data.request.get_email()?, )?, )), PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::GooglePay(payment_method_data) => { let gpay_ecrypted_object = BluesnapGooglePayObject { payment_method_data: utils::GooglePayWalletData::try_from( payment_method_data, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?, } .encode_to_string_of_json() .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(( PaymentMethodDetails::Wallet(BluesnapWallet { wallet_type: BluesnapWalletTypes::GooglePay, encoded_payment_token: Secret::new( BASE64_ENGINE.encode(gpay_ecrypted_object), ), }), None, )) } WalletData::ApplePay(payment_method_data) => { let apple_pay_payment_data = payment_method_data.get_applepay_decoded_payment_data()?; let apple_pay_payment_data: ApplePayEncodedPaymentData = apple_pay_payment_data .expose() .as_bytes() .parse_struct("ApplePayEncodedPaymentData") .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })?; let billing = item.router_data.get_billing()?.to_owned(); let billing_address = billing .address .get_required_value("billing_address") .change_context(errors::ConnectorError::MissingRequiredField { field_name: "billing", })?; let mut address = Vec::new(); if let Some(add) = billing_address.line1.to_owned() { address.push(add) } if let Some(add) = billing_address.line2.to_owned() { address.push(add) } if let Some(add) = billing_address.line3.to_owned() { address.push(add) } let apple_pay_object = EncodedPaymentToken { token: ApplepayPaymentData { payment_data: apple_pay_payment_data, payment_method: payment_method_data.payment_method.to_owned().into(), transaction_identifier: payment_method_data.transaction_identifier, }, billing_contact: BillingDetails { country_code: billing_address.country, address_lines: Some(address), family_name: billing_address.last_name.to_owned(), given_name: billing_address.first_name.to_owned(), postal_code: billing_address.zip, }, } .encode_to_string_of_json() .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(( PaymentMethodDetails::Wallet(BluesnapWallet { wallet_type: BluesnapWalletTypes::ApplePay, encoded_payment_token: Secret::new( BASE64_ENGINE.encode(apple_pay_object), ), }), get_card_holder_info( item.router_data.get_billing_address()?, item.router_data.request.get_email()?, )?, )) } WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::WeChatPayQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("bluesnap"), )), }, PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("bluesnap"), )) } }?; Ok(Self { amount: item.amount.to_owned(), payment_method, currency: item.router_data.request.currency, card_transaction_type: auth_mode, transaction_fraud_info: Some(TransactionFraudInfo { fraud_session_id: item.router_data.payment_id.clone(), }), card_holder_info, merchant_transaction_id: Some(item.router_data.connector_request_reference_id.clone()), transaction_meta_data, }) } } impl From<payment_method_data::ApplepayPaymentMethod> for ApplepayPaymentMethod { fn from(item: payment_method_data::ApplepayPaymentMethod) -> Self { Self { display_name: item.display_name, network: item.network, pm_type: item.pm_type, } } } impl TryFrom<&types::PaymentsSessionRouterData> for BluesnapCreateWalletToken { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsSessionRouterData) -> Result<Self, Self::Error> { let apple_pay_metadata = item.get_connector_meta()?.expose(); let applepay_metadata = apple_pay_metadata .clone() .parse_value::<ApplepayCombinedSessionTokenData>("ApplepayCombinedSessionTokenData") .map(|combined_metadata| { ApplepaySessionTokenMetadata::ApplePayCombined(combined_metadata.apple_pay_combined) }) .or_else(|_| { apple_pay_metadata .parse_value::<ApplepaySessionTokenData>("ApplepaySessionTokenData") .map(|old_metadata| { ApplepaySessionTokenMetadata::ApplePay(old_metadata.apple_pay) }) }) .change_context(errors::ConnectorError::ParsingFailed)?; let session_token_data = match applepay_metadata { ApplepaySessionTokenMetadata::ApplePay(apple_pay_data) => { Ok(apple_pay_data.session_token_data) } ApplepaySessionTokenMetadata::ApplePayCombined(_apple_pay_combined_data) => { Err(errors::ConnectorError::FlowNotSupported { flow: "apple pay combined".to_string(), connector: "bluesnap".to_string(), }) } }?; let domain_name = session_token_data.initiative_context.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "apple pay initiative_context", }, )?; Ok(Self { wallet_type: "APPLE_PAY".to_string(), validation_url: APPLEPAY_VALIDATION_URL.to_string().into(), domain_name, display_name: Some(session_token_data.display_name), }) } } impl ForeignTryFrom<( PaymentsSessionResponseRouterData<BluesnapWalletTokenResponse>, StringMajorUnit, )> for types::PaymentsSessionRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from( (item, apple_pay_amount): ( PaymentsSessionResponseRouterData<BluesnapWalletTokenResponse>, StringMajorUnit, ), ) -> Result<Self, Self::Error> { let response = &item.response; let wallet_token = BASE64_ENGINE .decode(response.wallet_token.clone().expose()) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let session_response: NoThirdPartySdkSessionResponse = wallet_token .parse_struct("NoThirdPartySdkSessionResponse") .change_context(errors::ConnectorError::ParsingFailed)?; let metadata = item.data.get_connector_meta()?.expose(); let applepay_metadata = metadata .clone() .parse_value::<ApplepayCombinedSessionTokenData>("ApplepayCombinedSessionTokenData") .map(|combined_metadata| { ApplepaySessionTokenMetadata::ApplePayCombined(combined_metadata.apple_pay_combined) }) .or_else(|_| { metadata .parse_value::<ApplepaySessionTokenData>("ApplepaySessionTokenData") .map(|old_metadata| { ApplepaySessionTokenMetadata::ApplePay(old_metadata.apple_pay) }) }) .change_context(errors::ConnectorError::ParsingFailed)?; let (payment_request_data, session_token_data) = match applepay_metadata { ApplepaySessionTokenMetadata::ApplePayCombined(_apple_pay_combined) => { Err(errors::ConnectorError::FlowNotSupported { flow: "apple pay combined".to_string(), connector: "bluesnap".to_string(), }) } ApplepaySessionTokenMetadata::ApplePay(apple_pay) => { Ok((apple_pay.payment_request_data, apple_pay.session_token_data)) } }?; Ok(Self { response: Ok(PaymentsResponseData::SessionResponse { session_token: SessionToken::ApplePay(Box::new(ApplepaySessionTokenResponse { session_token_data: Some(ApplePaySessionResponse::NoThirdPartySdk( session_response, )), payment_request_data: Some(ApplePayPaymentRequest { country_code: item.data.get_billing_country()?, currency_code: item.data.request.currency, total: AmountInfo { label: payment_request_data.label, total_type: Some("final".to_string()), amount: apple_pay_amount, }, merchant_capabilities: Some(payment_request_data.merchant_capabilities), supported_networks: Some(payment_request_data.supported_networks), merchant_identifier: Some(session_token_data.merchant_identifier), required_billing_contact_fields: None, required_shipping_contact_fields: None, recurring_payment_request: None, }), connector: "bluesnap".to_string(), delayed_session_token: false, sdk_next_action: { SdkNextAction { next_action: NextActionCall::Confirm, } }, connector_reference_id: None, connector_sdk_public_key: None, connector_merchant_id: None, })), }), ..item.data }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapCompletePaymentsRequest { amount: StringMajorUnit, currency: enums::Currency, card_transaction_type: BluesnapTxnType, pf_token: Secret<String>, three_d_secure: Option<BluesnapThreeDSecureInfo>, transaction_fraud_info: Option<TransactionFraudInfo>, card_holder_info: Option<BluesnapCardHolderInfo>, merchant_transaction_id: Option<String>, transaction_meta_data: Option<BluesnapMetadata>, } impl TryFrom<&BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for BluesnapCompletePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let redirection_response: BluesnapRedirectionResponse = item .router_data .request .redirect_response .as_ref() .and_then(|res| res.payload.to_owned()) .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.payload", })? .parse_value("BluesnapRedirectionResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let transaction_meta_data = item.router_data .request .metadata .as_ref() .map(|metadata| BluesnapMetadata { meta_data: convert_metadata_to_request_metadata(metadata.to_owned()), }); let token = item .router_data .request .redirect_response .clone() .and_then(|res| res.params.to_owned()) .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.params", })? .peek() .split_once('=') .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.params.paymentToken", })? .1 .to_string(); let redirection_result: BluesnapThreeDsResult = redirection_response .authentication_response .parse_struct("BluesnapThreeDsResult") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let auth_mode = match item.router_data.request.capture_method { Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly, _ => BluesnapTxnType::AuthCapture, }; Ok(Self { amount: item.amount.to_owned(), currency: item.router_data.request.currency, card_transaction_type: auth_mode, three_d_secure: Some(BluesnapThreeDSecureInfo { three_d_secure_reference_id: redirection_result .three_d_secure .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "three_d_secure_reference_id", })? .three_d_secure_reference_id, }), transaction_fraud_info: Some(TransactionFraudInfo { fraud_session_id: item.router_data.payment_id.clone(), }), card_holder_info: get_card_holder_info( item.router_data.get_billing_address()?, item.router_data.request.get_email()?, )?, merchant_transaction_id: Some(item.router_data.connector_request_reference_id.clone()), pf_token: Secret::new(token), transaction_meta_data, }) } } #[derive(Debug, Deserialize)] pub struct BluesnapRedirectionResponse { pub authentication_response: String, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapThreeDsResult { three_d_secure: Option<BluesnapThreeDsReference>, pub status: String, pub code: Option<String>, pub info: Option<RedirectErrorMessage>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RedirectErrorMessage { pub errors: Option<Vec<String>>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapThreeDsReference { three_d_secure_reference_id: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapVoidRequest { card_transaction_type: BluesnapTxnType, transaction_id: String, } impl TryFrom<&types::PaymentsCancelRouterData> for BluesnapVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { let card_transaction_type = BluesnapTxnType::AuthReversal; let transaction_id = item.request.connector_transaction_id.to_string(); Ok(Self { card_transaction_type, transaction_id, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapCaptureRequest { card_transaction_type: BluesnapTxnType, transaction_id: String, amount: Option<StringMajorUnit>, } impl TryFrom<&BluesnapRouterData<&types::PaymentsCaptureRouterData>> for BluesnapCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BluesnapRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { let card_transaction_type = BluesnapTxnType::Capture; let transaction_id = item .router_data .request .connector_transaction_id .to_string(); Ok(Self { card_transaction_type, transaction_id, amount: Some(item.amount.to_owned()), }) } } // Auth Struct pub struct BluesnapAuthType { pub(super) api_key: Secret<String>, pub(super) key1: Secret<String>, } impl TryFrom<&ConnectorAuthType> for BluesnapAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { Ok(Self { api_key: api_key.to_owned(), key1: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } } } // PaymentsResponse #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BluesnapTxnType { AuthOnly, AuthCapture, AuthReversal, Capture, Refund, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum BluesnapProcessingStatus { #[serde(alias = "success")] Success, #[default] #[serde(alias = "pending")] Pending, #[serde(alias = "fail")] Fail, #[serde(alias = "pending_merchant_review")] PendingMerchantReview, } impl ForeignTryFrom<(BluesnapTxnType, BluesnapProcessingStatus)> for enums::AttemptStatus { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from( item: (BluesnapTxnType, BluesnapProcessingStatus), ) -> Result<Self, Self::Error> { let (item_txn_status, item_processing_status) = item; Ok(match item_processing_status { BluesnapProcessingStatus::Success => match item_txn_status { BluesnapTxnType::AuthOnly => Self::Authorized, BluesnapTxnType::AuthReversal => Self::Voided, BluesnapTxnType::AuthCapture | BluesnapTxnType::Capture => Self::Charged, BluesnapTxnType::Refund => Self::Charged, }, BluesnapProcessingStatus::Pending | BluesnapProcessingStatus::PendingMerchantReview => { Self::Pending } BluesnapProcessingStatus::Fail => Self::Failure, }) } } impl From<BluesnapProcessingStatus> for enums::RefundStatus { fn from(item: BluesnapProcessingStatus) -> Self { match item { BluesnapProcessingStatus::Success => Self::Success, BluesnapProcessingStatus::Pending => Self::Pending, BluesnapProcessingStatus::PendingMerchantReview => Self::ManualReview, BluesnapProcessingStatus::Fail => Self::Failure, } } } impl From<BluesnapRefundStatus> for enums::RefundStatus { fn from(item: BluesnapRefundStatus) -> Self { match item { BluesnapRefundStatus::Success => Self::Success, BluesnapRefundStatus::Pending => Self::Pending, } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapPaymentsResponse { pub processing_info: ProcessingInfoResponse, pub transaction_id: String, pub card_transaction_type: BluesnapTxnType, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapWalletTokenResponse { wallet_type: String, wallet_token: Secret<String>, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Refund { refund_transaction_id: String, amount: StringMajorUnit, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ProcessingInfoResponse { pub processing_status: BluesnapProcessingStatus, pub authorization_code: Option<String>, pub network_transaction_id: Option<Secret<String>>, } impl<F, T> TryFrom<ResponseRouterData<F, BluesnapPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, BluesnapPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::foreign_try_from(( item.response.card_transaction_type, item.response.processing_info.processing_status, ))?, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.transaction_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Default, Debug, Serialize)] pub struct BluesnapRefundRequest { amount: Option<StringMajorUnit>, reason: Option<String>, } impl<F> TryFrom<&BluesnapRouterData<&types::RefundsRouterData<F>>> for BluesnapRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BluesnapRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { reason: item.router_data.request.reason.clone(), amount: Some(item.amount.to_owned()), }) } } #[derive(Debug, Clone, Default, Deserialize, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum BluesnapRefundStatus { Success, #[default] Pending, } #[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundResponse { refund_transaction_id: i32, refund_status: BluesnapRefundStatus, } impl TryFrom<RefundsResponseRouterData<RSync, BluesnapPaymentsResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, BluesnapPaymentsResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction_id.clone(), refund_status: enums::RefundStatus::from( item.response.processing_info.processing_status, ), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.refund_transaction_id.to_string(), refund_status: enums::RefundStatus::from(item.response.refund_status), }), ..item.data }) } } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapWebhookBody { pub merchant_transaction_id: String, pub reference_number: String, pub transaction_type: BluesnapWebhookEvents, pub reversal_ref_num: Option<String>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapWebhookObjectEventType { transaction_type: BluesnapWebhookEvents, cb_status: Option<BluesnapChargebackStatus>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BluesnapChargebackStatus { #[serde(alias = "New")] New, #[serde(alias = "Working")] Working, #[serde(alias = "Closed")] Closed, #[serde(alias = "Completed_Lost")] CompletedLost, #[serde(alias = "Completed_Pending")] CompletedPending, #[serde(alias = "Completed_Won")] CompletedWon, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BluesnapWebhookEvents { Decline, CcChargeFailed, Charge, Refund, Chargeback, ChargebackStatusChanged, #[serde(other)] Unknown, } impl TryFrom<BluesnapWebhookObjectEventType> for IncomingWebhookEvent { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(details: BluesnapWebhookObjectEventType) -> Result<Self, Self::Error> { match details.transaction_type { BluesnapWebhookEvents::Decline | BluesnapWebhookEvents::CcChargeFailed => { Ok(Self::PaymentIntentFailure) } BluesnapWebhookEvents::Charge => Ok(Self::PaymentIntentSuccess), BluesnapWebhookEvents::Refund => Ok(Self::RefundSuccess), BluesnapWebhookEvents::Chargeback | BluesnapWebhookEvents::ChargebackStatusChanged => { match details .cb_status .ok_or(errors::ConnectorError::WebhookEventTypeNotFound)? { BluesnapChargebackStatus::New | BluesnapChargebackStatus::Working => { Ok(Self::DisputeOpened) } BluesnapChargebackStatus::Closed => Ok(Self::DisputeExpired), BluesnapChargebackStatus::CompletedLost => Ok(Self::DisputeLost), BluesnapChargebackStatus::CompletedPending => Ok(Self::DisputeChallenged), BluesnapChargebackStatus::CompletedWon => Ok(Self::DisputeWon), } } BluesnapWebhookEvents::Unknown => Ok(Self::EventNotSupported), } } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapDisputeWebhookBody { pub invoice_charge_amount: FloatMajorUnit, pub currency: enums::Currency, pub reversal_reason: Option<String>, pub reversal_ref_num: String, pub cb_status: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapWebhookObjectResource { reference_number: String, transaction_type: BluesnapWebhookEvents, reversal_ref_num: Option<String>, } impl TryFrom<BluesnapWebhookObjectResource> for Value { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(details: BluesnapWebhookObjectResource) -> Result<Self, Self::Error> { let (card_transaction_type, processing_status, transaction_id) = match details .transaction_type { BluesnapWebhookEvents::Decline | BluesnapWebhookEvents::CcChargeFailed => Ok(( BluesnapTxnType::Capture, BluesnapProcessingStatus::Fail, details.reference_number, )), BluesnapWebhookEvents::Charge => Ok(( BluesnapTxnType::Capture, BluesnapProcessingStatus::Success, details.reference_number, )), BluesnapWebhookEvents::Chargeback | BluesnapWebhookEvents::ChargebackStatusChanged => { //It won't be consumed in dispute flow, so currently does not hold any significance return serde_json::to_value(details) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed); } BluesnapWebhookEvents::Refund => Ok(( BluesnapTxnType::Refund, BluesnapProcessingStatus::Success, details .reversal_ref_num .ok_or(errors::ConnectorError::WebhookResourceObjectNotFound)?, )), BluesnapWebhookEvents::Unknown => { Err(errors::ConnectorError::WebhookResourceObjectNotFound) } }?; let sync_struct = BluesnapPaymentsResponse { processing_info: ProcessingInfoResponse { processing_status, authorization_code: None, network_transaction_id: None, }, transaction_id, card_transaction_type, }; serde_json::to_value(sync_struct) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed) } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ErrorDetails { pub code: String, pub description: String, pub error_name: Option<String>, } #[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapErrorResponse { pub message: Vec<ErrorDetails>, } #[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapAuthErrorResponse { pub error_code: String, pub error_description: String, pub error_name: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BluesnapErrors { Payment(BluesnapErrorResponse), Auth(BluesnapAuthErrorResponse), General(String), } fn get_card_holder_info( address: &AddressDetails, email: Email, ) -> CustomResult<Option<BluesnapCardHolderInfo>, errors::ConnectorError> { let first_name = address.get_first_name()?; Ok(Some(BluesnapCardHolderInfo { first_name: first_name.clone(), last_name: address.get_last_name().unwrap_or(first_name).clone(), email, })) } impl From<ErrorDetails> for utils::ErrorCodeAndMessage { fn from(error: ErrorDetails) -> Self { Self { error_code: error.code.to_string(), error_message: error.error_name.unwrap_or(error.code), } } } fn convert_metadata_to_request_metadata(metadata: Value) -> Vec<RequestMetadata> { let hashmap: HashMap<Option<String>, Option<Value>> = serde_json::from_str(&metadata.to_string()).unwrap_or(HashMap::new()); let mut vector = Vec::<RequestMetadata>::new(); for (key, value) in hashmap { vector.push(RequestMetadata { meta_key: key, meta_value: value.map(|field_value| field_value.to_string()), is_visible: Some(DISPLAY_METADATA.to_string()), }); } vector }
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
hyperswitch_connectors::src::connectors::bluesnap::transformers
8,741
true
// File: crates/hyperswitch_connectors/src/connectors/wise/transformers.rs // Module: hyperswitch_connectors::src::connectors::wise::transformers #[cfg(feature = "payouts")] use api_models::payouts::Bank; #[cfg(feature = "payouts")] use api_models::payouts::PayoutMethodData; #[cfg(feature = "payouts")] use common_enums::PayoutEntityType; #[cfg(feature = "payouts")] use common_enums::{CountryAlpha2, PayoutStatus, PayoutType}; #[cfg(feature = "payouts")] use common_utils::pii::Email; use common_utils::types::FloatMajorUnit; use hyperswitch_domain_models::router_data::ConnectorAuthType; #[cfg(feature = "payouts")] use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData}; use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::{Deserialize, Serialize}; #[cfg(feature = "payouts")] use crate::types::PayoutsResponseRouterData; #[cfg(feature = "payouts")] use crate::utils::get_unimplemented_payment_method_error_message; #[cfg(feature = "payouts")] use crate::utils::{PayoutsData as _, RouterData as _}; type Error = error_stack::Report<ConnectorError>; #[derive(Debug, Serialize)] pub struct WiseRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for WiseRouterData<T> { fn from((amount, router_data): (FloatMajorUnit, T)) -> Self { Self { amount, router_data, } } } pub struct WiseAuthType { pub(super) api_key: Secret<String>, #[allow(dead_code)] pub(super) profile_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for WiseAuthType { type Error = Error; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.to_owned(), profile_id: key1.to_owned(), }), _ => Err(ConnectorError::FailedToObtainAuthType)?, } } } // Wise error response #[derive(Debug, Deserialize, Serialize)] pub struct ErrorResponse { pub timestamp: Option<String>, pub errors: Option<Vec<SubError>>, pub status: Option<WiseHttpStatus>, pub error: Option<String>, pub error_description: Option<String>, pub message: Option<String>, pub path: Option<String>, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum WiseHttpStatus { String(String), Number(u16), } impl Default for WiseHttpStatus { fn default() -> Self { Self::String("".to_string()) } } impl WiseHttpStatus { pub fn get_status(&self) -> String { match self { Self::String(val) => val.clone(), Self::Number(val) => val.to_string(), } } } #[derive(Debug, Deserialize, Serialize)] pub struct SubError { pub code: String, pub message: String, pub path: Option<String>, pub field: Option<String>, } // Payouts #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WiseRecipientCreateRequest { currency: String, #[serde(rename = "type")] recipient_type: RecipientType, profile: Secret<String>, account_holder_name: Secret<String>, details: WiseBankDetails, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] #[allow(dead_code)] pub enum RecipientType { Aba, Iban, SortCode, SwiftCode, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum AccountType { Checking, } #[cfg(feature = "payouts")] #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WiseBankDetails { legal_type: LegalType, account_type: Option<AccountType>, address: Option<WiseAddressDetails>, post_code: Option<String>, nationality: Option<String>, account_holder_name: Option<Secret<String>>, email: Option<Email>, account_number: Option<Secret<String>>, city: Option<String>, sort_code: Option<Secret<String>>, iban: Option<Secret<String>>, bic: Option<Secret<String>>, transit_number: Option<Secret<String>>, routing_number: Option<Secret<String>>, abartn: Option<Secret<String>>, swift_code: Option<Secret<String>>, payin_reference: Option<String>, psp_reference: Option<String>, tax_id: Option<String>, order_id: Option<String>, job: Option<String>, } #[cfg(feature = "payouts")] #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum LegalType { Business, #[default] Private, } #[cfg(feature = "payouts")] #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WiseAddressDetails { country: Option<CountryAlpha2>, country_code: Option<CountryAlpha2>, first_line: Option<Secret<String>>, post_code: Option<Secret<String>>, city: Option<String>, state: Option<Secret<String>>, } #[allow(dead_code)] #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WiseRecipientCreateResponse { id: i64, business: Option<i64>, profile: Option<i64>, account_holder_name: Secret<String>, currency: String, country: String, #[serde(rename = "type")] request_type: String, details: Option<WiseBankDetails>, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WisePayoutQuoteRequest { source_currency: String, target_currency: String, source_amount: Option<FloatMajorUnit>, target_amount: Option<FloatMajorUnit>, pay_out: WisePayOutOption, } #[cfg(feature = "payouts")] #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum WisePayOutOption { Balance, #[default] BankTransfer, Swift, SwiftOur, Interac, } #[allow(dead_code)] #[cfg(feature = "payouts")] #[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WisePayoutQuoteResponse { source_amount: f64, client_id: String, id: String, status: WiseStatus, profile: i64, rate: Option<i8>, source_currency: Option<String>, target_currency: Option<String>, user: Option<i64>, rate_type: Option<WiseRateType>, pay_out: Option<WisePayOutOption>, } #[cfg(feature = "payouts")] #[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum WiseRateType { #[default] Fixed, Floating, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WisePayoutCreateRequest { target_account: i64, quote_uuid: String, customer_transaction_id: String, details: WiseTransferDetails, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WiseTransferDetails { transfer_purpose: Option<String>, source_of_funds: Option<String>, transfer_purpose_sub_transfer_purpose: Option<String>, } #[allow(dead_code)] #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WisePayoutResponse { id: i64, user: i64, target_account: i64, source_account: Option<i64>, quote_uuid: String, status: WiseStatus, reference: Option<String>, rate: Option<f32>, business: Option<i64>, details: Option<WiseTransferDetails>, has_active_issues: Option<bool>, source_currency: Option<String>, source_value: Option<f64>, target_currency: Option<String>, target_value: Option<f64>, customer_transaction_id: Option<String>, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WisePayoutFulfillRequest { #[serde(rename = "type")] fund_type: FundType, } // NOTE - Only balance is allowed as time of incorporating this field - https://api-docs.transferwise.com/api-reference/transfer#fund #[cfg(feature = "payouts")] #[derive(Debug, Default, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum FundType { #[default] Balance, } #[allow(dead_code)] #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WiseFulfillResponse { status: WiseStatus, error_code: Option<String>, error_message: Option<String>, balance_transaction_id: Option<i64>, } #[cfg(feature = "payouts")] #[derive(Debug, Default, Clone, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum WiseStatus { Completed, Pending, Rejected, #[serde(rename = "cancelled")] Cancelled, #[serde(rename = "processing")] #[default] Processing, #[serde(rename = "incoming_payment_waiting")] IncomingPaymentWaiting, } #[cfg(feature = "payouts")] fn get_payout_address_details( address: Option<&hyperswitch_domain_models::address::Address>, ) -> Option<WiseAddressDetails> { address.and_then(|add| { add.address.as_ref().map(|a| WiseAddressDetails { country: a.country, country_code: a.country, first_line: a.line1.clone(), post_code: a.zip.clone(), city: a.city.clone(), state: a.state.clone(), }) }) } #[cfg(feature = "payouts")] fn get_payout_bank_details( payout_method_data: PayoutMethodData, address: Option<&hyperswitch_domain_models::address::Address>, entity_type: PayoutEntityType, ) -> Result<WiseBankDetails, ConnectorError> { let wise_address_details = match get_payout_address_details(address) { Some(a) => Ok(a), None => Err(ConnectorError::MissingRequiredField { field_name: "address", }), }?; match payout_method_data { PayoutMethodData::Bank(Bank::Ach(b)) => Ok(WiseBankDetails { legal_type: LegalType::from(entity_type), address: Some(wise_address_details), account_number: Some(b.bank_account_number.to_owned()), abartn: Some(b.bank_routing_number), account_type: Some(AccountType::Checking), ..WiseBankDetails::default() }), PayoutMethodData::Bank(Bank::Bacs(b)) => Ok(WiseBankDetails { legal_type: LegalType::from(entity_type), address: Some(wise_address_details), account_number: Some(b.bank_account_number.to_owned()), sort_code: Some(b.bank_sort_code), ..WiseBankDetails::default() }), PayoutMethodData::Bank(Bank::Sepa(b)) => Ok(WiseBankDetails { legal_type: LegalType::from(entity_type), address: Some(wise_address_details), iban: Some(b.iban.to_owned()), bic: b.bic, ..WiseBankDetails::default() }), _ => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Wise"), ))?, } } // Payouts recipient create request transform #[cfg(feature = "payouts")] impl<F> TryFrom<&WiseRouterData<&PayoutsRouterData<F>>> for WiseRecipientCreateRequest { type Error = Error; fn try_from(item_data: &WiseRouterData<&PayoutsRouterData<F>>) -> Result<Self, Self::Error> { let item = item_data.router_data; let request = item.request.to_owned(); let customer_details = request.customer_details.to_owned(); let payout_method_data = item.get_payout_method_data()?; let bank_details = get_payout_bank_details( payout_method_data.to_owned(), item.get_optional_billing(), item.request.entity_type, )?; let source_id = match item.connector_auth_type.to_owned() { ConnectorAuthType::BodyKey { api_key: _, key1 } => Ok(key1), _ => Err(ConnectorError::MissingRequiredField { field_name: "source_id for PayoutRecipient creation", }), }?; let payout_type = request.get_payout_type()?; match payout_type { PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => { Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Wise"), ))? } PayoutType::Bank => { let account_holder_name = customer_details .ok_or(ConnectorError::MissingRequiredField { field_name: "customer_details for PayoutRecipient creation", })? .name .ok_or(ConnectorError::MissingRequiredField { field_name: "customer_details.name for PayoutRecipient creation", })?; Ok(Self { profile: source_id, currency: request.destination_currency.to_string(), recipient_type: RecipientType::try_from(payout_method_data)?, account_holder_name, details: bank_details, }) } } } } // Payouts recipient fulfill response transform #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, WiseRecipientCreateResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( item: PayoutsResponseRouterData<F, WiseRecipientCreateResponse>, ) -> Result<Self, Self::Error> { let response: WiseRecipientCreateResponse = item.response; Ok(Self { response: Ok(PayoutsResponseData { status: Some(PayoutStatus::RequiresCreation), connector_payout_id: Some(response.id.to_string()), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } // Payouts quote request transform #[cfg(feature = "payouts")] impl<F> TryFrom<&WiseRouterData<&PayoutsRouterData<F>>> for WisePayoutQuoteRequest { type Error = Error; fn try_from(item_data: &WiseRouterData<&PayoutsRouterData<F>>) -> Result<Self, Self::Error> { let item = item_data.router_data; let request = item.request.to_owned(); let payout_type = request.get_payout_type()?; match payout_type { PayoutType::Bank => Ok(Self { source_amount: Some(item_data.amount), source_currency: request.source_currency.to_string(), target_amount: None, target_currency: request.destination_currency.to_string(), pay_out: WisePayOutOption::default(), }), PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => { Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Wise"), ))? } } } } // Payouts quote response transform #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, WisePayoutQuoteResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( item: PayoutsResponseRouterData<F, WisePayoutQuoteResponse>, ) -> Result<Self, Self::Error> { let response: WisePayoutQuoteResponse = item.response; Ok(Self { response: Ok(PayoutsResponseData { status: Some(PayoutStatus::RequiresCreation), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } // Payouts transfer creation request #[cfg(feature = "payouts")] impl<F> TryFrom<&PayoutsRouterData<F>> for WisePayoutCreateRequest { type Error = Error; fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let payout_type = request.get_payout_type()?; match payout_type { PayoutType::Bank => { let connector_customer_id = item.get_connector_customer_id()?; let quote_uuid = item.get_quote_id()?; let wise_transfer_details = WiseTransferDetails { transfer_purpose: None, source_of_funds: None, transfer_purpose_sub_transfer_purpose: None, }; let target_account: i64 = connector_customer_id.trim().parse().map_err(|_| { ConnectorError::MissingRequiredField { field_name: "profile", } })?; Ok(Self { target_account, quote_uuid, customer_transaction_id: uuid::Uuid::new_v4().to_string(), details: wise_transfer_details, }) } PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => { Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Wise"), ))? } } } } // Payouts transfer creation response #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, WisePayoutResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( item: PayoutsResponseRouterData<F, WisePayoutResponse>, ) -> Result<Self, Self::Error> { let response: WisePayoutResponse = item.response; let status = match PayoutStatus::from(response.status) { PayoutStatus::Cancelled => PayoutStatus::Cancelled, _ => PayoutStatus::RequiresFulfillment, }; Ok(Self { response: Ok(PayoutsResponseData { status: Some(status), connector_payout_id: Some(response.id.to_string()), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } // Payouts fulfill request transform #[cfg(feature = "payouts")] impl<F> TryFrom<&PayoutsRouterData<F>> for WisePayoutFulfillRequest { type Error = Error; fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let payout_type = item.request.get_payout_type()?; match payout_type { PayoutType::Bank => Ok(Self { fund_type: FundType::default(), }), PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => { Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Wise"), ))? } } } } // Payouts fulfill response transform #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, WiseFulfillResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( item: PayoutsResponseRouterData<F, WiseFulfillResponse>, ) -> Result<Self, Self::Error> { let response: WiseFulfillResponse = item.response; Ok(Self { response: Ok(PayoutsResponseData { status: Some(PayoutStatus::from(response.status)), connector_payout_id: Some( item.data .request .connector_payout_id .clone() .ok_or(ConnectorError::MissingConnectorTransactionID)?, ), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } #[cfg(feature = "payouts")] impl From<WiseStatus> for PayoutStatus { fn from(wise_status: WiseStatus) -> Self { match wise_status { WiseStatus::Completed => Self::Initiated, WiseStatus::Rejected => Self::Failed, WiseStatus::Cancelled => Self::Cancelled, WiseStatus::Pending | WiseStatus::Processing | WiseStatus::IncomingPaymentWaiting => { Self::Pending } } } } #[cfg(feature = "payouts")] impl From<PayoutEntityType> for LegalType { fn from(entity_type: PayoutEntityType) -> Self { match entity_type { PayoutEntityType::Individual | PayoutEntityType::Personal | PayoutEntityType::NonProfit | PayoutEntityType::NaturalPerson => Self::Private, PayoutEntityType::Company | PayoutEntityType::PublicSector | PayoutEntityType::Business => Self::Business, } } } #[cfg(feature = "payouts")] impl TryFrom<PayoutMethodData> for RecipientType { type Error = error_stack::Report<ConnectorError>; fn try_from(payout_method_type: PayoutMethodData) -> Result<Self, Self::Error> { match payout_method_type { PayoutMethodData::Bank(Bank::Ach(_)) => Ok(Self::Aba), PayoutMethodData::Bank(Bank::Bacs(_)) => Ok(Self::SortCode), PayoutMethodData::Bank(Bank::Sepa(_)) => Ok(Self::Iban), _ => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Wise"), ) .into()), } } } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] pub struct WisePayoutSyncResponse { id: u64, status: WiseSyncStatus, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum WiseSyncStatus { IncomingPaymentWaiting, IncomingPaymentInitiated, Processing, FundsConverted, OutgoingPaymentSent, Cancelled, FundsRefunded, BouncedBack, ChargedBack, Unknown, } #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, WisePayoutSyncResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( item: PayoutsResponseRouterData<F, WisePayoutSyncResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PayoutsResponseData { status: Some(PayoutStatus::from(item.response.status)), connector_payout_id: Some(item.response.id.to_string()), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } #[cfg(feature = "payouts")] impl From<WiseSyncStatus> for PayoutStatus { fn from(status: WiseSyncStatus) -> Self { match status { WiseSyncStatus::IncomingPaymentWaiting => Self::Pending, WiseSyncStatus::IncomingPaymentInitiated => Self::Pending, WiseSyncStatus::Processing => Self::Pending, WiseSyncStatus::FundsConverted => Self::Pending, WiseSyncStatus::OutgoingPaymentSent => Self::Success, WiseSyncStatus::Cancelled => Self::Cancelled, WiseSyncStatus::FundsRefunded => Self::Reversed, WiseSyncStatus::BouncedBack => Self::Pending, WiseSyncStatus::ChargedBack => Self::Reversed, WiseSyncStatus::Unknown => Self::Ineligible, } } } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] pub struct WisePayoutsWebhookBody { pub data: WisePayoutsWebhookData, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] pub struct WisePayoutsWebhookData { pub resource: WisePayoutsWebhookResource, pub current_state: WiseSyncStatus, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] pub struct WisePayoutsWebhookResource { pub id: u64, } #[cfg(feature = "payouts")] impl From<WisePayoutsWebhookData> for WisePayoutSyncResponse { fn from(data: WisePayoutsWebhookData) -> Self { Self { id: data.resource.id, status: data.current_state, } } } #[cfg(feature = "payouts")] pub fn get_wise_webhooks_event( state: WiseSyncStatus, ) -> api_models::webhooks::IncomingWebhookEvent { match state { WiseSyncStatus::IncomingPaymentWaiting => { api_models::webhooks::IncomingWebhookEvent::PayoutProcessing } WiseSyncStatus::IncomingPaymentInitiated => { api_models::webhooks::IncomingWebhookEvent::PayoutProcessing } WiseSyncStatus::Processing => api_models::webhooks::IncomingWebhookEvent::PayoutProcessing, WiseSyncStatus::FundsConverted => { api_models::webhooks::IncomingWebhookEvent::PayoutProcessing } WiseSyncStatus::OutgoingPaymentSent => { api_models::webhooks::IncomingWebhookEvent::PayoutSuccess } WiseSyncStatus::Cancelled => api_models::webhooks::IncomingWebhookEvent::PayoutCancelled, WiseSyncStatus::FundsRefunded => api_models::webhooks::IncomingWebhookEvent::PayoutReversed, WiseSyncStatus::BouncedBack => api_models::webhooks::IncomingWebhookEvent::PayoutProcessing, WiseSyncStatus::ChargedBack => api_models::webhooks::IncomingWebhookEvent::PayoutReversed, WiseSyncStatus::Unknown => api_models::webhooks::IncomingWebhookEvent::EventNotSupported, } }
crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
hyperswitch_connectors::src::connectors::wise::transformers
5,871
true
// File: crates/hyperswitch_connectors/src/connectors/placetopay/transformers.rs // Module: hyperswitch_connectors::src::connectors::placetopay::transformers use common_enums::{enums, Currency}; use common_utils::{consts::BASE64_ENGINE, date_time, types::MinorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types, }; use hyperswitch_interfaces::errors; use masking::{PeekInterface, Secret}; use ring::digest; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, generate_random_bytes, BrowserInformationData, CardData as _, PaymentsAuthorizeRequestData, PaymentsSyncRequestData, RouterData as _, }, }; pub struct PlacetopayRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> From<(MinorUnit, T)> for PlacetopayRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayPaymentsRequest { auth: PlacetopayAuth, payment: PlacetopayPayment, instrument: PlacetopayInstrument, ip_address: Secret<String, common_utils::pii::IpAddress>, user_agent: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum PlacetopayAuthorizeAction { Checkin, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayAuthType { login: Secret<String>, tran_key: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayAuth { login: Secret<String>, tran_key: Secret<String>, nonce: Secret<String>, seed: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayPayment { reference: String, description: String, amount: PlacetopayAmount, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayAmount { currency: Currency, total: MinorUnit, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayInstrument { card: PlacetopayCard, } #[derive(Debug, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct PlacetopayCard { number: cards::CardNumber, expiration: Secret<String>, cvv: Secret<String>, } impl TryFrom<&PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>> for PlacetopayPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let browser_info = item.router_data.request.get_browser_info()?; let ip_address = browser_info.get_ip_address()?; let user_agent = browser_info.get_user_agent()?; let auth = PlacetopayAuth::try_from(&item.router_data.connector_auth_type)?; let payment = PlacetopayPayment { reference: item.router_data.connector_request_reference_id.clone(), description: item.router_data.get_description()?, amount: PlacetopayAmount { currency: item.router_data.request.currency, total: item.amount, }, }; match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let card = PlacetopayCard { number: req_card.card_number.clone(), expiration: req_card .clone() .get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?, cvv: req_card.card_cvc.clone(), }; Ok(Self { ip_address, user_agent, auth, payment, instrument: PlacetopayInstrument { card: card.to_owned(), }, }) } PaymentMethodData::Wallet(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Placetopay"), ) .into()) } } } } impl TryFrom<&ConnectorAuthType> for PlacetopayAuth { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { let placetopay_auth = PlacetopayAuthType::try_from(auth_type)?; let nonce_bytes = generate_random_bytes(16); let now = date_time::date_as_yyyymmddthhmmssmmmz() .change_context(errors::ConnectorError::RequestEncodingFailed)?; let seed = format!("{}+00:00", now.split_at(now.len() - 5).0); let mut context = digest::Context::new(&digest::SHA256); context.update(&nonce_bytes); context.update(seed.as_bytes()); context.update(placetopay_auth.tran_key.peek().as_bytes()); let encoded_digest = base64::Engine::encode(&BASE64_ENGINE, context.finish()); let nonce = Secret::new(base64::Engine::encode(&BASE64_ENGINE, &nonce_bytes)); Ok(Self { login: placetopay_auth.login, tran_key: encoded_digest.into(), nonce, seed, }) } } impl TryFrom<&ConnectorAuthType> for PlacetopayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { Ok(Self { login: api_key.to_owned(), tran_key: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PlacetopayTransactionStatus { Ok, Failed, Approved, // ApprovedPartial, // PartialExpired, Rejected, Pending, PendingValidation, PendingProcess, // Refunded, // Reversed, Error, // Unknown, // Manual, // Dispute, //The statuses that are commented out are awaiting clarification on the connector. } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayStatusResponse { status: PlacetopayTransactionStatus, } impl From<PlacetopayTransactionStatus> for enums::AttemptStatus { fn from(item: PlacetopayTransactionStatus) -> Self { match item { PlacetopayTransactionStatus::Approved | PlacetopayTransactionStatus::Ok => { Self::Charged } PlacetopayTransactionStatus::Failed | PlacetopayTransactionStatus::Rejected | PlacetopayTransactionStatus::Error => Self::Failure, PlacetopayTransactionStatus::Pending | PlacetopayTransactionStatus::PendingValidation | PlacetopayTransactionStatus::PendingProcess => Self::Pending, } } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayPaymentsResponse { status: PlacetopayStatusResponse, internal_reference: u64, authorization: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, PlacetopayPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PlacetopayPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.status.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.internal_reference.to_string(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: item .response .authorization .clone() .map(|authorization| serde_json::json!(authorization)), network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } // REFUND : // Type definition for RefundRequest #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayRefundRequest { auth: PlacetopayAuth, internal_reference: u64, action: PlacetopayNextAction, authorization: Option<String>, } impl<F> TryFrom<&types::RefundsRouterData<F>> for PlacetopayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { if item.request.minor_refund_amount == item.request.minor_payment_amount { let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?; let internal_reference = item .request .connector_transaction_id .parse::<u64>() .change_context(errors::ConnectorError::RequestEncodingFailed)?; let action = PlacetopayNextAction::Reverse; let authorization = match item.request.connector_metadata.clone() { Some(metadata) => metadata.as_str().map(|auth| auth.to_string()), None => None, }; Ok(Self { auth, internal_reference, action, authorization, }) } else { Err(errors::ConnectorError::NotSupported { message: "Partial Refund".to_string(), connector: "placetopay", } .into()) } } } impl From<PlacetopayRefundStatus> for enums::RefundStatus { fn from(item: PlacetopayRefundStatus) -> Self { match item { PlacetopayRefundStatus::Ok | PlacetopayRefundStatus::Approved | PlacetopayRefundStatus::Refunded => Self::Success, PlacetopayRefundStatus::Failed | PlacetopayRefundStatus::Rejected | PlacetopayRefundStatus::Error => Self::Failure, PlacetopayRefundStatus::Pending | PlacetopayRefundStatus::PendingProcess | PlacetopayRefundStatus::PendingValidation => Self::Pending, } } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PlacetopayRefundStatus { Ok, Failed, Approved, // ApprovedPartial, // PartialExpired, Rejected, Pending, PendingValidation, PendingProcess, Refunded, // Reversed, Error, // Unknown, // Manual, // Dispute, //The statuses that are commented out are awaiting clarification on the connector. } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayRefundStatusResponse { status: PlacetopayRefundStatus, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayRefundResponse { status: PlacetopayRefundStatusResponse, internal_reference: u64, } impl TryFrom<RefundsResponseRouterData<Execute, PlacetopayRefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, PlacetopayRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.internal_reference.to_string(), refund_status: enums::RefundStatus::from(item.response.status.status), }), ..item.data }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayRsyncRequest { auth: PlacetopayAuth, internal_reference: u64, } impl TryFrom<&types::RefundsRouterData<RSync>> for PlacetopayRsyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundsRouterData<RSync>) -> Result<Self, Self::Error> { let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?; let internal_reference = item .request .connector_transaction_id .parse::<u64>() .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Self { auth, internal_reference, }) } } impl TryFrom<RefundsResponseRouterData<RSync, PlacetopayRefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, PlacetopayRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.internal_reference.to_string(), refund_status: enums::RefundStatus::from(item.response.status.status), }), ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayErrorResponse { pub status: PlacetopayError, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayError { pub status: PlacetopayErrorStatus, pub message: String, pub reason: String, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PlacetopayErrorStatus { Failed, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayPsyncRequest { auth: PlacetopayAuth, internal_reference: u64, } impl TryFrom<&types::PaymentsSyncRouterData> for PlacetopayPsyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?; let internal_reference = item .request .get_connector_transaction_id()? .parse::<u64>() .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Self { auth, internal_reference, }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PlacetopayNextActionRequest { auth: PlacetopayAuth, internal_reference: u64, action: PlacetopayNextAction, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum PlacetopayNextAction { Refund, Reverse, Void, Process, Checkout, } impl TryFrom<&types::PaymentsCaptureRouterData> for PlacetopayNextActionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?; let internal_reference = item .request .connector_transaction_id .parse::<u64>() .change_context(errors::ConnectorError::RequestEncodingFailed)?; let action = PlacetopayNextAction::Checkout; Ok(Self { auth, internal_reference, action, }) } } impl TryFrom<&types::PaymentsCancelRouterData> for PlacetopayNextActionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?; let internal_reference = item .request .connector_transaction_id .parse::<u64>() .change_context(errors::ConnectorError::RequestEncodingFailed)?; let action = PlacetopayNextAction::Void; Ok(Self { auth, internal_reference, action, }) } }
crates/hyperswitch_connectors/src/connectors/placetopay/transformers.rs
hyperswitch_connectors::src::connectors::placetopay::transformers
3,948
true
// File: crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs // Module: hyperswitch_connectors::src::connectors::worldline::transformers use common_enums::enums::{AttemptStatus, BankNames, CaptureMethod, CountryAlpha2, Currency}; use common_utils::{pii::Email, request::Method}; use hyperswitch_domain_models::{ payment_method_data::{BankRedirectData, PaymentMethodData}, router_data::{ConnectorAuthType, RouterData}, router_flow_types::{ payments::Authorize, refunds::{Execute, RSync}, }, router_request_types::{PaymentsAuthorizeData, ResponseId}, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::{api::CurrencyUnit, errors}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{self, CardData, RouterData as RouterDataUtils}, }; #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Card { pub card_number: cards::CardNumber, pub cardholder_name: Secret<String>, pub cvv: Secret<String>, pub expiry_date: Secret<String>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct CardPaymentMethod { pub card: Card, pub requires_approval: bool, pub payment_product_id: u16, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AmountOfMoney { pub amount: i64, pub currency_code: String, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct References { pub merchant_reference: String, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Order { pub amount_of_money: AmountOfMoney, pub customer: Customer, pub references: References, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct BillingAddress { pub city: Option<String>, pub country_code: Option<CountryAlpha2>, pub house_number: Option<Secret<String>>, pub state: Option<Secret<String>>, pub state_code: Option<Secret<String>>, pub street: Option<Secret<String>>, pub zip: Option<Secret<String>>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct ContactDetails { pub email_address: Option<Email>, pub mobile_phone_number: Option<Secret<String>>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Customer { pub billing_address: BillingAddress, pub contact_details: Option<ContactDetails>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Name { pub first_name: Option<Secret<String>>, pub surname: Option<Secret<String>>, pub surname_prefix: Option<Secret<String>>, pub title: Option<Secret<String>>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Shipping { pub city: Option<String>, pub country_code: Option<CountryAlpha2>, pub house_number: Option<Secret<String>>, pub name: Option<Name>, pub state: Option<Secret<String>>, pub state_code: Option<String>, pub street: Option<Secret<String>>, pub zip: Option<Secret<String>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum WorldlinePaymentMethod { CardPaymentMethodSpecificInput(Box<CardPaymentMethod>), RedirectPaymentMethodSpecificInput(Box<RedirectPaymentMethod>), } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct RedirectPaymentMethod { pub payment_product_id: u16, pub redirection_data: RedirectionData, #[serde(flatten)] pub payment_method_specific_data: PaymentMethodSpecificData, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct RedirectionData { pub return_url: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum PaymentMethodSpecificData { PaymentProduct816SpecificInput(Box<Giropay>), PaymentProduct809SpecificInput(Box<Ideal>), } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Giropay { pub bank_account_iban: BankAccountIban, } #[derive(Debug, Serialize)] pub struct Ideal { #[serde(rename = "issuerId")] pub issuer_id: Option<WorldlineBic>, } #[derive(Debug, Serialize)] pub enum WorldlineBic { #[serde(rename = "ABNANL2A")] Abnamro, #[serde(rename = "ASNBNL21")] Asn, #[serde(rename = "FRBKNL2L")] Friesland, #[serde(rename = "KNABNL2H")] Knab, #[serde(rename = "RABONL2U")] Rabobank, #[serde(rename = "RBRBNL21")] Regiobank, #[serde(rename = "SNSBNL2A")] Sns, #[serde(rename = "TRIONL2U")] Triodos, #[serde(rename = "FVLBNL22")] Vanlanschot, #[serde(rename = "INGBNL2A")] Ing, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankAccountIban { pub account_holder_name: Secret<String>, pub iban: Option<Secret<String>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentsRequest { #[serde(flatten)] pub payment_data: WorldlinePaymentMethod, pub order: Order, pub shipping: Option<Shipping>, } #[derive(Debug, Serialize)] pub struct WorldlineRouterData<T> { amount: i64, router_data: T, } impl<T> TryFrom<(&CurrencyUnit, Currency, i64, T)> for WorldlineRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (_currency_unit, _currency, amount, item): (&CurrencyUnit, Currency, i64, T), ) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } } impl TryFrom< &WorldlineRouterData<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>>, > for PaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &WorldlineRouterData< &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>, >, ) -> Result<Self, Self::Error> { let payment_data = match &item.router_data.request.payment_method_data { PaymentMethodData::Card(card) => { let card_holder_name = item.router_data.get_optional_billing_full_name(); WorldlinePaymentMethod::CardPaymentMethodSpecificInput(Box::new( make_card_request(&item.router_data.request, card, card_holder_name)?, )) } PaymentMethodData::BankRedirect(bank_redirect) => { WorldlinePaymentMethod::RedirectPaymentMethodSpecificInput(Box::new( make_bank_redirect_request(item.router_data, bank_redirect)?, )) } PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("worldline"), ))? } }; let billing_address = item.router_data.get_billing()?; let customer = build_customer_info(billing_address, &item.router_data.request.email)?; let order = Order { amount_of_money: AmountOfMoney { amount: item.amount, currency_code: item.router_data.request.currency.to_string().to_uppercase(), }, customer, references: References { merchant_reference: item.router_data.connector_request_reference_id.clone(), }, }; let shipping = item .router_data .get_optional_shipping() .and_then(|shipping| shipping.address.clone()) .map(Shipping::from); Ok(Self { payment_data, order, shipping, }) } } #[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)] pub enum Gateway { Amex = 2, Discover = 128, MasterCard = 3, Visa = 1, } impl TryFrom<utils::CardIssuer> for Gateway { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> { match issuer { utils::CardIssuer::AmericanExpress => Ok(Self::Amex), utils::CardIssuer::Master => Ok(Self::MasterCard), utils::CardIssuer::Discover => Ok(Self::Discover), utils::CardIssuer::Visa => Ok(Self::Visa), _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("worldline"), ) .into()), } } } impl TryFrom<&BankNames> for WorldlineBic { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(bank: &BankNames) -> Result<Self, Self::Error> { match bank { BankNames::AbnAmro => Ok(Self::Abnamro), BankNames::AsnBank => Ok(Self::Asn), BankNames::Ing => Ok(Self::Ing), BankNames::Knab => Ok(Self::Knab), BankNames::Rabobank => Ok(Self::Rabobank), BankNames::Regiobank => Ok(Self::Regiobank), BankNames::SnsBank => Ok(Self::Sns), BankNames::TriodosBank => Ok(Self::Triodos), BankNames::VanLanschot => Ok(Self::Vanlanschot), BankNames::FrieslandBank => Ok(Self::Friesland), _ => Err(errors::ConnectorError::FlowNotSupported { flow: bank.to_string(), connector: "Worldline".to_string(), } .into()), } } } fn make_card_request( req: &PaymentsAuthorizeData, ccard: &hyperswitch_domain_models::payment_method_data::Card, card_holder_name: Option<Secret<String>>, ) -> Result<CardPaymentMethod, error_stack::Report<errors::ConnectorError>> { let expiry_year = ccard.card_exp_year.peek(); let secret_value = format!( "{}{}", ccard.card_exp_month.peek(), &expiry_year .get(expiry_year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? ); let expiry_date: Secret<String> = Secret::new(secret_value); let card = Card { card_number: ccard.card_number.clone(), cardholder_name: card_holder_name.unwrap_or(Secret::new("".to_string())), cvv: ccard.card_cvc.clone(), expiry_date, }; #[allow(clippy::as_conversions)] let payment_product_id = Gateway::try_from(ccard.get_card_issuer()?)? as u16; let card_payment_method_specific_input = CardPaymentMethod { card, requires_approval: matches!(req.capture_method, Some(CaptureMethod::Manual)), payment_product_id, }; Ok(card_payment_method_specific_input) } fn make_bank_redirect_request( req: &PaymentsAuthorizeRouterData, bank_redirect: &BankRedirectData, ) -> Result<RedirectPaymentMethod, error_stack::Report<errors::ConnectorError>> { let return_url = req.request.router_return_url.clone(); let redirection_data = RedirectionData { return_url }; let (payment_method_specific_data, payment_product_id) = match bank_redirect { BankRedirectData::Giropay { bank_account_iban, .. } => ( { PaymentMethodSpecificData::PaymentProduct816SpecificInput(Box::new(Giropay { bank_account_iban: BankAccountIban { account_holder_name: req.get_billing_full_name()?.to_owned(), iban: bank_account_iban.clone(), }, })) }, 816, ), BankRedirectData::Ideal { bank_name, .. } => ( { PaymentMethodSpecificData::PaymentProduct809SpecificInput(Box::new(Ideal { issuer_id: bank_name .map(|bank_name| WorldlineBic::try_from(&bank_name)) .transpose()?, })) }, 809, ), BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::Sofort { .. } | BankRedirectData::Trustly { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::LocalBankRedirect {} => { return Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("worldline"), ) .into()) } }; Ok(RedirectPaymentMethod { payment_product_id, redirection_data, payment_method_specific_data, }) } fn get_address( billing: &hyperswitch_domain_models::address::Address, ) -> Option<( &hyperswitch_domain_models::address::Address, &hyperswitch_domain_models::address::AddressDetails, )> { let address = billing.address.as_ref()?; address.country.as_ref()?; Some((billing, address)) } fn build_customer_info( billing_address: &hyperswitch_domain_models::address::Address, email: &Option<Email>, ) -> Result<Customer, error_stack::Report<errors::ConnectorError>> { let (billing, address) = get_address(billing_address).ok_or(errors::ConnectorError::MissingRequiredField { field_name: "billing.address.country", })?; let number_with_country_code = billing.phone.as_ref().and_then(|phone| { phone.number.as_ref().and_then(|number| { phone .country_code .as_ref() .map(|cc| Secret::new(format!("{}{}", cc, number.peek()))) }) }); Ok(Customer { billing_address: BillingAddress { ..address.clone().into() }, contact_details: Some(ContactDetails { mobile_phone_number: number_with_country_code, email_address: email.clone(), }), }) } impl From<hyperswitch_domain_models::address::AddressDetails> for BillingAddress { fn from(value: hyperswitch_domain_models::address::AddressDetails) -> Self { Self { city: value.city, country_code: value.country, state: value.state, zip: value.zip, ..Default::default() } } } impl From<hyperswitch_domain_models::address::AddressDetails> for Shipping { fn from(value: hyperswitch_domain_models::address::AddressDetails) -> Self { Self { city: value.city, country_code: value.country, name: Some(Name { first_name: value.first_name, surname: value.last_name, ..Default::default() }), state: value.state, zip: value.zip, ..Default::default() } } } pub struct WorldlineAuthType { pub api_key: Secret<String>, pub api_secret: Secret<String>, pub merchant_account_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for WorldlineAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } = auth_type { Ok(Self { api_key: api_key.to_owned(), api_secret: api_secret.to_owned(), merchant_account_id: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } #[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaymentStatus { Captured, Paid, ChargebackNotification, Cancelled, Rejected, RejectedCapture, PendingApproval, CaptureRequested, #[default] Processing, Created, Redirected, } fn get_status(item: (PaymentStatus, CaptureMethod)) -> AttemptStatus { let (status, capture_method) = item; match status { PaymentStatus::Captured | PaymentStatus::Paid | PaymentStatus::ChargebackNotification => { AttemptStatus::Charged } PaymentStatus::Cancelled => AttemptStatus::Voided, PaymentStatus::Rejected => AttemptStatus::Failure, PaymentStatus::RejectedCapture => AttemptStatus::CaptureFailed, PaymentStatus::CaptureRequested => { if matches!( capture_method, CaptureMethod::Automatic | CaptureMethod::SequentialAutomatic ) { AttemptStatus::Pending } else { AttemptStatus::CaptureInitiated } } PaymentStatus::PendingApproval => AttemptStatus::Authorized, PaymentStatus::Created => AttemptStatus::Started, PaymentStatus::Redirected => AttemptStatus::AuthenticationPending, _ => AttemptStatus::Pending, } } /// capture_method is not part of response from connector. /// This is used to decide payment status while converting connector response to RouterData. /// To keep this try_from logic generic in case of AUTHORIZE, SYNC and CAPTURE flows capture_method will be set from RouterData request. #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct Payment { pub id: String, pub status: PaymentStatus, #[serde(skip_deserializing)] pub capture_method: CaptureMethod, } impl<F, T> TryFrom<ResponseRouterData<F, Payment, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, Payment, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: get_status((item.response.status, item.response.capture_method)), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentResponse { pub payment: Payment, pub merchant_action: Option<MerchantAction>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantAction { pub redirect_data: RedirectData, } #[derive(Debug, Deserialize, Serialize)] pub struct RedirectData { #[serde(rename = "redirectURL")] pub redirect_url: Url, } impl<F, T> TryFrom<ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirection_data = item .response .merchant_action .map(|action| action.redirect_data.redirect_url) .map(|redirect_url| RedirectForm::from((redirect_url, Method::Get))); Ok(Self { status: get_status(( item.response.payment.status, item.response.payment.capture_method, )), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.payment.id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Default, Debug, Serialize)] pub struct ApproveRequest {} impl TryFrom<&PaymentsCaptureRouterData> for ApproveRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(_item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> { Ok(Self {}) } } #[derive(Default, Debug, Serialize)] pub struct WorldlineRefundRequest { amount_of_money: AmountOfMoney, } impl<F> TryFrom<&RefundsRouterData<F>> for WorldlineRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> { Ok(Self { amount_of_money: AmountOfMoney { amount: item.request.refund_amount, currency_code: item.request.currency.to_string(), }, }) } } #[allow(dead_code)] #[derive(Debug, Default, Deserialize, Clone, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum RefundStatus { Cancelled, Rejected, Refunded, #[default] Processing, } impl From<RefundStatus> for common_enums::enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Refunded => Self::Success, RefundStatus::Cancelled | RefundStatus::Rejected => Self::Failure, RefundStatus::Processing => Self::Pending, } } } #[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = common_enums::enums::RefundStatus::from(item.response.status); Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.clone(), refund_status, }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = common_enums::enums::RefundStatus::from(item.response.status); Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.clone(), refund_status, }), ..item.data }) } } #[derive(Default, Debug, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Error { pub code: Option<String>, pub property_name: Option<String>, pub message: Option<String>, } #[derive(Default, Debug, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ErrorResponse { pub error_id: Option<String>, pub errors: Vec<Error>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WebhookBody { pub api_version: Option<String>, pub id: String, pub created: String, pub merchant_id: common_utils::id_type::MerchantId, #[serde(rename = "type")] pub event_type: WebhookEvent, pub payment: Option<serde_json::Value>, pub refund: Option<serde_json::Value>, pub payout: Option<serde_json::Value>, pub token: Option<serde_json::Value>, } #[derive(Debug, Deserialize)] pub enum WebhookEvent { #[serde(rename = "payment.rejected")] Rejected, #[serde(rename = "payment.rejected_capture")] RejectedCapture, #[serde(rename = "payment.paid")] Paid, #[serde(other)] Unknown, }
crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
hyperswitch_connectors::src::connectors::worldline::transformers
5,711
true
// File: crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs // Module: hyperswitch_connectors::src::connectors::deutschebank::transformers use std::collections::HashMap; use cards::CardNumber; use common_enums::{enums, PaymentMethod}; use common_utils::{ext_traits::ValueExt, pii::Email, types::MinorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankDebitData, PaymentMethodData}, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ payments::{Authorize, Capture, CompleteAuthorize, PSync}, refunds::{Execute, RSync}, }, router_request_types::{ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData, ResponseId, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{consts, errors}; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, RefundsRequestData, RouterData as OtherRouterData, }, }; pub struct DeutschebankRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> From<(MinorUnit, T)> for DeutschebankRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } pub struct DeutschebankAuthType { pub(super) client_id: Secret<String>, pub(super) merchant_id: Secret<String>, pub(super) client_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for DeutschebankAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { client_id: api_key.to_owned(), merchant_id: key1.to_owned(), client_key: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Default, Debug, Serialize, PartialEq)] pub struct DeutschebankAccessTokenRequest { pub grant_type: String, pub client_id: Secret<String>, pub client_secret: Secret<String>, pub scope: String, } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct DeutschebankAccessTokenResponse { pub access_token: Secret<String>, pub expires_in: i64, pub expires_on: i64, pub scope: String, pub token_type: String, } impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(AccessToken { token: item.response.access_token, expires: item.response.expires_in, }), ..item.data }) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum DeutschebankSEPAApproval { Click, Email, Sms, Dynamic, } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankMandatePostRequest { approval_by: DeutschebankSEPAApproval, email_address: Email, iban: Secret<String>, first_name: Secret<String>, last_name: Secret<String>, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum DeutschebankPaymentsRequest { MandatePost(DeutschebankMandatePostRequest), DirectDebit(DeutschebankDirectDebitRequest), CreditCard(Box<DeutschebankThreeDSInitializeRequest>), } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequest { means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment, tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data, amount_total: DeutschebankThreeDSInitializeRequestAmountTotal, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestMeansOfPayment { credit_card: DeutschebankThreeDSInitializeRequestCreditCard, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestCreditCard { number: CardNumber, expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry, code: Secret<String>, cardholder: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestCreditCardExpiry { year: Secret<String>, month: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestAmountTotal { amount: MinorUnit, currency: api_models::enums::Currency, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestTds20Data { communication_data: DeutschebankThreeDSInitializeRequestCommunicationData, customer_data: DeutschebankThreeDSInitializeRequestCustomerData, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestCommunicationData { method_notification_url: String, cres_notification_url: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestCustomerData { billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData, cardholder_email: Email, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct DeutschebankThreeDSInitializeRequestCustomerBillingData { street: Secret<String>, postal_code: Secret<String>, city: String, state: Secret<String>, country: String, } impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> for DeutschebankPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DeutschebankRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item .router_data .request .mandate_id .clone() .and_then(|mandate_id| mandate_id.mandate_reference_id) { None => { // To facilitate one-off payments via SEPA with Deutsche Bank, we are considering not storing the connector mandate ID in our system if future usage is on-session. // We will only check for customer acceptance to make a one-off payment. we will be storing the connector mandate details only when setup future usage is off-session. match item.router_data.request.payment_method_data.clone() { PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => { if item.router_data.request.customer_acceptance.is_some() { let billing_address = item.router_data.get_billing_address()?; Ok(Self::MandatePost(DeutschebankMandatePostRequest { approval_by: DeutschebankSEPAApproval::Click, email_address: item.router_data.request.get_email()?, iban: Secret::from(iban.peek().replace(" ", "")), first_name: billing_address.get_first_name()?.clone(), last_name: billing_address.get_last_name()?.clone(), })) } else { Err(errors::ConnectorError::MissingRequiredField { field_name: "customer_acceptance", } .into()) } } PaymentMethodData::Card(ccard) => { if !item.router_data.clone().is_three_ds() { Err(errors::ConnectorError::NotSupported { message: "Non-ThreeDs".to_owned(), connector: "deutschebank", } .into()) } else { let billing_address = item.router_data.get_billing_address()?; Ok(Self::CreditCard(Box::new(DeutschebankThreeDSInitializeRequest { means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment { credit_card: DeutschebankThreeDSInitializeRequestCreditCard { number: ccard.clone().card_number, expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry { year: ccard.get_expiry_year_4_digit(), month: ccard.card_exp_month, }, code: ccard.card_cvc, cardholder: item.router_data.get_billing_full_name()?, }}, amount_total: DeutschebankThreeDSInitializeRequestAmountTotal { amount: item.amount, currency: item.router_data.request.currency, }, tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data { communication_data: DeutschebankThreeDSInitializeRequestCommunicationData { method_notification_url: item.router_data.request.get_complete_authorize_url()?, cres_notification_url: item.router_data.request.get_complete_authorize_url()?, }, customer_data: DeutschebankThreeDSInitializeRequestCustomerData { billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData { street: billing_address.get_line1()?.clone(), postal_code: billing_address.get_zip()?.clone(), city: billing_address.get_city()?.to_string(), state: billing_address.get_state()?.clone(), country: item.router_data.get_billing_country()?.to_string(), }, cardholder_email: item.router_data.request.get_email()?, } } }))) } } _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("deutschebank"), ) .into()), } } Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => { let mandate_metadata: DeutschebankMandateMetadata = mandate_data .get_mandate_metadata() .ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)? .clone() .parse_value("DeutschebankMandateMetadata") .change_context(errors::ConnectorError::ParsingFailed)?; Ok(Self::DirectDebit(DeutschebankDirectDebitRequest { amount_total: DeutschebankAmount { amount: item.amount, currency: item.router_data.request.currency, }, means_of_payment: DeutschebankMeansOfPayment { bank_account: DeutschebankBankAccount { account_holder: mandate_metadata.account_holder, iban: mandate_metadata.iban, }, }, mandate: DeutschebankMandate { reference: mandate_metadata.reference, signed_on: mandate_metadata.signed_on, }, })) } Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) | Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("deutschebank"), ) .into()) } } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DeutschebankThreeDSInitializeResponse { outcome: DeutschebankThreeDSInitializeResponseOutcome, challenge_required: Option<DeutschebankThreeDSInitializeResponseChallengeRequired>, processed: Option<DeutschebankThreeDSInitializeResponseProcessed>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DeutschebankThreeDSInitializeResponseProcessed { rc: String, message: String, tx_id: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum DeutschebankThreeDSInitializeResponseOutcome { Processed, ChallengeRequired, MethodRequired, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DeutschebankThreeDSInitializeResponseChallengeRequired { acs_url: String, creq: String, } impl TryFrom< ResponseRouterData< Authorize, DeutschebankThreeDSInitializeResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Authorize, DeutschebankThreeDSInitializeResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response.outcome { DeutschebankThreeDSInitializeResponseOutcome::Processed => { match item.response.processed { Some(processed) => Ok(Self { status: if is_response_success(&processed.rc) { match item.data.request.is_auto_capture()? { true => common_enums::AttemptStatus::Charged, false => common_enums::AttemptStatus::Authorized, } } else { common_enums::AttemptStatus::AuthenticationFailed }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( processed.tx_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(processed.tx_id.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }), None => { let response_string = format!("{:?}", item.response); Err( errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from( response_string, )) .into(), ) } } } DeutschebankThreeDSInitializeResponseOutcome::ChallengeRequired => { match item.response.challenge_required { Some(challenge) => Ok(Self { status: common_enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(Some( RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url: challenge.acs_url, creq: challenge.creq, }, )), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), None => { let response_string = format!("{:?}", item.response); Err( errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from( response_string, )) .into(), ) } } } DeutschebankThreeDSInitializeResponseOutcome::MethodRequired => Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: consts::NO_ERROR_CODE.to_owned(), message: "METHOD_REQUIRED Flow not supported for deutschebank 3ds payments".to_owned(), reason: Some("METHOD_REQUIRED Flow is not currently supported for deutschebank 3ds payments".to_owned()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None,network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum DeutschebankSEPAMandateStatus { Created, PendingApproval, PendingSecondaryApproval, PendingReview, PendingSubmission, Submitted, Active, Failed, Discarded, Expired, Replaced, } impl From<DeutschebankSEPAMandateStatus> for common_enums::AttemptStatus { fn from(item: DeutschebankSEPAMandateStatus) -> Self { match item { DeutschebankSEPAMandateStatus::Active | DeutschebankSEPAMandateStatus::Created | DeutschebankSEPAMandateStatus::PendingApproval | DeutschebankSEPAMandateStatus::PendingSecondaryApproval | DeutschebankSEPAMandateStatus::PendingReview | DeutschebankSEPAMandateStatus::PendingSubmission | DeutschebankSEPAMandateStatus::Submitted => Self::AuthenticationPending, DeutschebankSEPAMandateStatus::Failed | DeutschebankSEPAMandateStatus::Discarded | DeutschebankSEPAMandateStatus::Expired | DeutschebankSEPAMandateStatus::Replaced => Self::Failure, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DeutschebankMandateMetadata { account_holder: Secret<String>, iban: Secret<String>, reference: Secret<String>, signed_on: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DeutschebankMandatePostResponse { rc: String, message: String, mandate_id: Option<String>, reference: Option<String>, approval_date: Option<String>, language: Option<String>, approval_by: Option<DeutschebankSEPAApproval>, state: Option<DeutschebankSEPAMandateStatus>, } fn get_error_response(error_code: String, error_reason: String, status_code: u16) -> ErrorResponse { ErrorResponse { code: error_code.to_string(), message: error_reason.clone(), reason: Some(error_reason), status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, } } fn is_response_success(rc: &String) -> bool { rc == "0" } impl TryFrom< ResponseRouterData< Authorize, DeutschebankMandatePostResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Authorize, DeutschebankMandatePostResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let signed_on = match item.response.approval_date.clone() { Some(date) => date.chars().take(10).collect(), None => time::OffsetDateTime::now_utc().date().to_string(), }; let response_code = item.response.rc.clone(); let is_response_success = is_response_success(&response_code); match ( item.response.reference.clone(), item.response.state.clone(), is_response_success, ) { (Some(reference), Some(state), true) => Ok(Self { status: common_enums::AttemptStatus::from(state), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(Some(RedirectForm::Form { endpoint: item.data.request.get_complete_authorize_url()?, method: common_utils::request::Method::Get, form_fields: HashMap::from([ ("reference".to_string(), reference.clone()), ("signed_on".to_string(), signed_on.clone()), ]), })), mandate_reference: if item.data.request.is_mandate_payment() { Box::new(Some(MandateReference { connector_mandate_id: item.response.mandate_id, payment_method_id: None, mandate_metadata: Some(Secret::new( serde_json::json!(DeutschebankMandateMetadata { account_holder: item.data.get_billing_address()?.get_full_name()?, iban: match item.data.request.payment_method_data.clone() { PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => Ok(Secret::from(iban.peek().replace(" ", ""))), _ => Err(errors::ConnectorError::MissingRequiredField { field_name: "payment_method_data.bank_debit.sepa_bank_debit.iban" }), }?, reference: Secret::from(reference.clone()), signed_on, }), )), connector_mandate_request_reference_id: None, })) } else { Box::new(None) }, connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), _ => Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }), } } } impl TryFrom< ResponseRouterData< Authorize, DeutschebankPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Authorize, DeutschebankPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_code = item.response.rc.clone(); if is_response_success(&response_code) { Ok(Self { status: match item.data.request.is_auto_capture()? { true => common_enums::AttemptStatus::Charged, false => common_enums::AttemptStatus::Authorized, }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }) } } } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct DeutschebankAmount { amount: MinorUnit, currency: api_models::enums::Currency, } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankMeansOfPayment { bank_account: DeutschebankBankAccount, } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankBankAccount { account_holder: Secret<String>, iban: Secret<String>, } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankMandate { reference: Secret<String>, signed_on: String, } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankDirectDebitRequest { amount_total: DeutschebankAmount, means_of_payment: DeutschebankMeansOfPayment, mandate: DeutschebankMandate, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum DeutschebankCompleteAuthorizeRequest { DeutschebankDirectDebitRequest(DeutschebankDirectDebitRequest), DeutschebankThreeDSCompleteAuthorizeRequest(DeutschebankThreeDSCompleteAuthorizeRequest), } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankThreeDSCompleteAuthorizeRequest { cres: String, } impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>> for DeutschebankCompleteAuthorizeRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { if matches!(item.router_data.payment_method, PaymentMethod::Card) { let redirect_response_payload = item .router_data .request .get_redirect_response_payload()? .expose(); let cres = redirect_response_payload .get("cres") .and_then(|v| v.as_str()) .map(String::from) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "cres" })?; Ok(Self::DeutschebankThreeDSCompleteAuthorizeRequest( DeutschebankThreeDSCompleteAuthorizeRequest { cres }, )) } else { match item.router_data.request.payment_method_data.clone() { Some(PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. })) => { let account_holder = item.router_data.get_billing_address()?.get_full_name()?; let redirect_response = item.router_data.request.redirect_response.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "redirect_response", }, )?; let queries_params = redirect_response .params .map(|param| { let mut queries = HashMap::<String, String>::new(); let values = param.peek().split('&').collect::<Vec<&str>>(); for value in values { let pair = value.split('=').collect::<Vec<&str>>(); queries.insert( pair.first() .ok_or( errors::ConnectorError::ResponseDeserializationFailed, )? .to_string(), pair.get(1) .ok_or( errors::ConnectorError::ResponseDeserializationFailed, )? .to_string(), ); } Ok::<_, errors::ConnectorError>(queries) }) .transpose()? .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; let reference = Secret::from( queries_params .get("reference") .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "reference", })? .to_owned(), ); let signed_on = queries_params .get("signed_on") .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "signed_on", })? .to_owned(); Ok(Self::DeutschebankDirectDebitRequest( DeutschebankDirectDebitRequest { amount_total: DeutschebankAmount { amount: item.amount, currency: item.router_data.request.currency, }, means_of_payment: DeutschebankMeansOfPayment { bank_account: DeutschebankBankAccount { account_holder, iban: Secret::from(iban.peek().replace(" ", "")), }, }, mandate: { DeutschebankMandate { reference, signed_on, } }, }, )) } _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("deutschebank"), ) .into()), } } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum DeutschebankTXAction { Authorization, Capture, Credit, Preauthorization, Refund, Reversal, RiskCheck, #[serde(rename = "verify-mop")] VerifyMop, Payment, AccountInformation, } #[derive(Debug, Deserialize, Serialize, PartialEq)] pub struct BankAccount { account_holder: Option<Secret<String>>, bank_name: Option<Secret<String>>, bic: Option<Secret<String>>, iban: Option<Secret<String>>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] pub struct TransactionBankAccountInfo { bank_account: Option<BankAccount>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] pub struct DeutschebankTransactionInfo { back_state: Option<String>, ip_address: Option<Secret<String>>, #[serde(rename = "type")] pm_type: Option<String>, transaction_bankaccount_info: Option<TransactionBankAccountInfo>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] pub struct DeutschebankPaymentsResponse { rc: String, message: String, timestamp: String, back_ext_id: Option<String>, back_rc: Option<String>, event_id: Option<String>, kind: Option<String>, tx_action: Option<DeutschebankTXAction>, tx_id: String, amount_total: Option<DeutschebankAmount>, transaction_info: Option<DeutschebankTransactionInfo>, } impl TryFrom< ResponseRouterData< CompleteAuthorize, DeutschebankPaymentsResponse, CompleteAuthorizeData, PaymentsResponseData, >, > for RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< CompleteAuthorize, DeutschebankPaymentsResponse, CompleteAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_code = item.response.rc.clone(); if is_response_success(&response_code) { Ok(Self { status: match item.data.request.is_auto_capture()? { true => common_enums::AttemptStatus::Charged, false => common_enums::AttemptStatus::Authorized, }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }) } } } #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum DeutschebankTransactionKind { Directdebit, #[serde(rename = "CREDITCARD_3DS20")] Creditcard3ds20, } #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankCaptureRequest { changed_amount: MinorUnit, kind: DeutschebankTransactionKind, } impl TryFrom<&DeutschebankRouterData<&PaymentsCaptureRouterData>> for DeutschebankCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DeutschebankRouterData<&PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { if matches!(item.router_data.payment_method, PaymentMethod::BankDebit) { Ok(Self { changed_amount: item.amount, kind: DeutschebankTransactionKind::Directdebit, }) } else if item.router_data.is_three_ds() && matches!(item.router_data.payment_method, PaymentMethod::Card) { Ok(Self { changed_amount: item.amount, kind: DeutschebankTransactionKind::Creditcard3ds20, }) } else { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("deutschebank"), ) .into()) } } } impl TryFrom< ResponseRouterData< Capture, DeutschebankPaymentsResponse, PaymentsCaptureData, PaymentsResponseData, >, > for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Capture, DeutschebankPaymentsResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_code = item.response.rc.clone(); if is_response_success(&response_code) { Ok(Self { status: common_enums::AttemptStatus::Charged, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } else { Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }) } } } impl TryFrom< ResponseRouterData< PSync, DeutschebankPaymentsResponse, PaymentsSyncData, PaymentsResponseData, >, > for RouterData<PSync, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< PSync, DeutschebankPaymentsResponse, PaymentsSyncData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_code = item.response.rc.clone(); let status = if is_response_success(&response_code) { item.response .tx_action .and_then(|tx_action| match tx_action { DeutschebankTXAction::Preauthorization => { Some(common_enums::AttemptStatus::Authorized) } DeutschebankTXAction::Authorization | DeutschebankTXAction::Capture => { Some(common_enums::AttemptStatus::Charged) } DeutschebankTXAction::Credit | DeutschebankTXAction::Refund | DeutschebankTXAction::Reversal | DeutschebankTXAction::RiskCheck | DeutschebankTXAction::VerifyMop | DeutschebankTXAction::Payment | DeutschebankTXAction::AccountInformation => None, }) } else { Some(common_enums::AttemptStatus::Failure) }; match status { Some(common_enums::AttemptStatus::Failure) => Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }), Some(status) => Ok(Self { status, ..item.data }), None => Ok(Self { ..item.data }), } } } #[derive(Debug, Serialize)] pub struct DeutschebankReversalRequest { kind: DeutschebankTransactionKind, } impl TryFrom<&PaymentsCancelRouterData> for DeutschebankReversalRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { if matches!(item.payment_method, PaymentMethod::BankDebit) { Ok(Self { kind: DeutschebankTransactionKind::Directdebit, }) } else if item.is_three_ds() && matches!(item.payment_method, PaymentMethod::Card) { Ok(Self { kind: DeutschebankTransactionKind::Creditcard3ds20, }) } else { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("deutschebank"), ) .into()) } } } impl TryFrom<PaymentsCancelResponseRouterData<DeutschebankPaymentsResponse>> for PaymentsCancelRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsCancelResponseRouterData<DeutschebankPaymentsResponse>, ) -> Result<Self, Self::Error> { let response_code = item.response.rc.clone(); if is_response_success(&response_code) { Ok(Self { status: common_enums::AttemptStatus::Voided, ..item.data }) } else { Ok(Self { status: common_enums::AttemptStatus::VoidFailed, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }) } } } #[derive(Debug, Serialize)] pub struct DeutschebankRefundRequest { changed_amount: MinorUnit, kind: DeutschebankTransactionKind, } impl<F> TryFrom<&DeutschebankRouterData<&RefundsRouterData<F>>> for DeutschebankRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &DeutschebankRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { if matches!(item.router_data.payment_method, PaymentMethod::BankDebit) { Ok(Self { changed_amount: item.amount, kind: DeutschebankTransactionKind::Directdebit, }) } else if item.router_data.is_three_ds() && matches!(item.router_data.payment_method, PaymentMethod::Card) { Ok(Self { changed_amount: item.amount, kind: DeutschebankTransactionKind::Creditcard3ds20, }) } else { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("deutschebank"), ) .into()) } } } impl TryFrom<RefundsResponseRouterData<Execute, DeutschebankPaymentsResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, DeutschebankPaymentsResponse>, ) -> Result<Self, Self::Error> { let response_code = item.response.rc.clone(); if is_response_success(&response_code) { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.tx_id, refund_status: enums::RefundStatus::Success, }), ..item.data }) } else { Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }) } } } impl TryFrom<RefundsResponseRouterData<RSync, DeutschebankPaymentsResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, DeutschebankPaymentsResponse>, ) -> Result<Self, Self::Error> { let response_code = item.response.rc.clone(); let status = if is_response_success(&response_code) { item.response .tx_action .and_then(|tx_action| match tx_action { DeutschebankTXAction::Credit | DeutschebankTXAction::Refund => { Some(enums::RefundStatus::Success) } DeutschebankTXAction::Preauthorization | DeutschebankTXAction::Authorization | DeutschebankTXAction::Capture | DeutschebankTXAction::Reversal | DeutschebankTXAction::RiskCheck | DeutschebankTXAction::VerifyMop | DeutschebankTXAction::Payment | DeutschebankTXAction::AccountInformation => None, }) } else { Some(enums::RefundStatus::Failure) }; match status { Some(enums::RefundStatus::Failure) => Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(get_error_response( response_code.clone(), item.response.message.clone(), item.http_code, )), ..item.data }), Some(refund_status) => Ok(Self { response: Ok(RefundsResponseData { refund_status, connector_refund_id: item.data.request.get_connector_refund_id()?, }), ..item.data }), None => Ok(Self { ..item.data }), } } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct PaymentsErrorResponse { pub rc: String, pub message: String, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct AccessTokenErrorResponse { pub cause: String, pub description: String, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(untagged)] pub enum DeutschebankError { PaymentsErrorResponse(PaymentsErrorResponse), AccessTokenErrorResponse(AccessTokenErrorResponse), }
crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
hyperswitch_connectors::src::connectors::deutschebank::transformers
8,778
true
// File: crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs // Module: hyperswitch_connectors::src::connectors::razorpay::transformers use std::collections::HashMap; use api_models::payments::PollConfig; use common_enums::enums; use common_utils::{ errors::CustomResult, pii::{self, Email, IpAddress}, types::MinorUnit, }; use hyperswitch_domain_models::{ payment_method_data::{PaymentMethodData, UpiData}, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{PaymentsAuthorizeData, ResponseId}, router_response_types::{PaymentsResponseData, RefundsResponseData}, types, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use time::{Duration, OffsetDateTime}; use crate::{ types::{CreateOrderResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ get_unimplemented_payment_method_error_message, missing_field_err, PaymentsAuthorizeRequestData, RouterData as OtherRouterData, }, }; pub struct RazorpayRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> TryFrom<(MinorUnit, T)> for RazorpayRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } } pub const VERSION: i32 = 1; #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct RazorpayOrderRequest { pub amount: MinorUnit, pub currency: enums::Currency, pub receipt: String, pub partial_payment: Option<bool>, pub first_payment_min_amount: Option<MinorUnit>, pub notes: Option<RazorpayNotes>, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum RazorpayNotes { Map(HashMap<String, String>), EmptyMap(HashMap<String, String>), } impl TryFrom<&RazorpayRouterData<&types::CreateOrderRouterData>> for RazorpayOrderRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &RazorpayRouterData<&types::CreateOrderRouterData>, ) -> Result<Self, Self::Error> { let currency = item.router_data.request.currency; let receipt = item.router_data.connector_request_reference_id.clone(); Ok(Self { amount: item.amount, currency, receipt, partial_payment: None, first_payment_min_amount: None, notes: None, }) } } #[derive(Debug, Serialize, Deserialize)] pub struct RazorpayMetaData { pub order_id: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct RazorpayOrderResponse { pub id: String, } impl TryFrom<CreateOrderResponseRouterData<RazorpayOrderResponse>> for types::CreateOrderRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: CreateOrderResponseRouterData<RazorpayOrderResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PaymentsResponseData::PaymentsCreateOrderResponse { order_id: item.response.id.clone(), }), ..item.data }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct UpiDetails { flow: UpiFlow, vpa: Secret<String, pii::UpiVpaMaskingStrategy>, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum UpiFlow { Collect, Intent, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct RazorpayPaymentsRequest { amount: MinorUnit, currency: enums::Currency, order_id: String, email: Email, contact: Secret<String>, method: RazorpayPaymentMethod, upi: UpiDetails, #[serde(skip_serializing_if = "Option::is_none")] ip: Option<Secret<String, IpAddress>>, #[serde(skip_serializing_if = "Option::is_none")] user_agent: Option<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum RazorpayPaymentMethod { Upi, } impl TryFrom<&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>> for RazorpayPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &RazorpayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let payment_router_data = item.router_data; let router_request = &payment_router_data.request; let payment_method_data = &router_request.payment_method_data; let (razorpay_payment_method, upi_details) = match payment_method_data { PaymentMethodData::Upi(upi_type_data) => match upi_type_data { UpiData::UpiCollect(upi_collect_data) => { let vpa_secret = upi_collect_data .vpa_id .clone() .ok_or_else(missing_field_err("payment_method_data.upi.collect.vpa_id"))?; ( RazorpayPaymentMethod::Upi, UpiDetails { flow: UpiFlow::Collect, vpa: vpa_secret, }, ) } UpiData::UpiIntent(_) | UpiData::UpiQr(_) => { Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("razorpay"), ))? } }, _ => Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("razorpay"), ))?, }; let contact_number = item.router_data.get_billing_phone_number()?; let order_id = router_request.get_order_id()?; let email = item.router_data.get_billing_email()?; let ip = router_request.get_ip_address_as_optional(); let user_agent = router_request.get_optional_user_agent(); Ok(Self { amount: item.amount, currency: router_request.currency, order_id, email, contact: contact_number, method: razorpay_payment_method, upi: upi_details, ip, user_agent, }) } } pub struct RazorpayAuthType { pub(super) razorpay_id: Secret<String>, pub(super) razorpay_secret: Secret<String>, } impl TryFrom<&ConnectorAuthType> for RazorpayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { razorpay_id: api_key.to_owned(), razorpay_secret: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct NextAction { pub action: String, pub url: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RazorpayPaymentsResponse { pub razorpay_payment_id: String, } impl<F> TryFrom< ResponseRouterData< F, RazorpayPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, RazorpayPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let connector_metadata = get_wait_screen_metadata()?; let order_id = item.data.request.get_order_id()?; Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.razorpay_payment_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some(order_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct WaitScreenData { display_from_timestamp: i128, display_to_timestamp: Option<i128>, poll_config: Option<PollConfig>, } pub fn get_wait_screen_metadata() -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> { let current_time = OffsetDateTime::now_utc().unix_timestamp_nanos(); Ok(Some(serde_json::json!(WaitScreenData { display_from_timestamp: current_time, display_to_timestamp: Some(current_time + Duration::minutes(5).whole_nanoseconds()), poll_config: Some(PollConfig { delay_in_secs: 5, frequency: 5, }), }))) } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RazorpaySyncResponse { items: Vec<RazorpaySyncItem>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RazorpaySyncItem { id: String, status: RazorpayStatus, } #[derive(Debug, Copy, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RazorpayStatus { Created, Authorized, Captured, Refunded, Failed, } fn get_psync_razorpay_payment_status(razorpay_status: RazorpayStatus) -> enums::AttemptStatus { match razorpay_status { RazorpayStatus::Created => enums::AttemptStatus::Pending, RazorpayStatus::Authorized => enums::AttemptStatus::Authorized, RazorpayStatus::Captured | RazorpayStatus::Refunded => enums::AttemptStatus::Charged, RazorpayStatus::Failed => enums::AttemptStatus::Failure, } } impl<F, T> TryFrom<ResponseRouterData<F, RazorpaySyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, RazorpaySyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let status = match item.response.items.last() { Some(last_item) => { let razorpay_status = last_item.status; get_psync_razorpay_payment_status(razorpay_status) } None => item.data.status, }; Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Default, Debug, Serialize)] #[serde(rename_all = "snake_case")] pub struct RazorpayRefundRequest { pub amount: MinorUnit, } impl<F> TryFrom<&RazorpayRouterData<&types::RefundsRouterData<F>>> for RazorpayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &RazorpayRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount, }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct RazorpayRefundResponse { pub id: String, pub status: RazorpayRefundStatus, } #[derive(Debug, Serialize, Eq, PartialEq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum RazorpayRefundStatus { Created, Processed, Failed, Pending, } impl From<RazorpayRefundStatus> for enums::RefundStatus { fn from(item: RazorpayRefundStatus) -> Self { match item { RazorpayRefundStatus::Processed => Self::Success, RazorpayRefundStatus::Pending | RazorpayRefundStatus::Created => Self::Pending, RazorpayRefundStatus::Failed => Self::Failure, } } } impl TryFrom<RefundsResponseRouterData<Execute, RazorpayRefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RazorpayRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } // This code can be used later when Razorpay webhooks are implemented // #[derive(Debug, Deserialize, Serialize)] // #[serde(untagged)] // pub enum RazorpayPaymentsResponseData { // PsyncResponse(RazorpaySyncResponse), // WebhookResponse(WebhookPaymentEntity), // } // impl From<RazorpayWebhookPaymentStatus> for enums::AttemptStatus { // fn from(status: RazorpayWebhookPaymentStatus) -> Self { // match status { // RazorpayWebhookPaymentStatus::Authorized => Self::Authorized, // RazorpayWebhookPaymentStatus::Captured => Self::Charged, // RazorpayWebhookPaymentStatus::Failed => Self::Failure, // } // } // } // impl<F, T> TryFrom<ResponseRouterData<F, RazorpayPaymentsResponseData, T, PaymentsResponseData>> // for RouterData<F, T, PaymentsResponseData> // { // type Error = error_stack::Report<errors::ConnectorError>; // fn try_from( // item: ResponseRouterData<F, RazorpayPaymentsResponseData, T, PaymentsResponseData>, // ) -> Result<Self, Self::Error> { // match item.response { // RazorpayPaymentsResponseData::PsyncResponse(sync_response) => { // let status = get_psync_razorpay_payment_status(sync_response.status.clone()); // Ok(Self { // status, // response: if is_payment_failure(status) { // Err(RouterErrorResponse { // code: sync_response.status.clone().to_string(), // message: sync_response.status.clone().to_string(), // reason: Some(sync_response.status.to_string()), // status_code: item.http_code, // attempt_status: Some(status), // connector_transaction_id: None, // network_advice_code: None, // network_decline_code: None, // network_error_message: None, // }) // } else { // Ok(PaymentsResponseData::TransactionResponse { // resource_id: ResponseId::NoResponseId, // redirection_data: Box::new(None), // mandate_reference: Box::new(None), // connector_metadata: None, // network_txn_id: None, // connector_response_reference_id: None, // incremental_authorization_allowed: None, // charges: None, // }) // }, // ..item.data // }) // } // RazorpayPaymentsResponseData::WebhookResponse(webhook_payment_entity) => { // let razorpay_status = webhook_payment_entity.status; // let status = enums::AttemptStatus::from(razorpay_status.clone()); // Ok(Self { // status, // response: if is_payment_failure(status) { // Err(RouterErrorResponse { // code: razorpay_status.clone().to_string(), // message: razorpay_status.clone().to_string(), // reason: Some(razorpay_status.to_string()), // status_code: item.http_code, // attempt_status: Some(status), // connector_transaction_id: Some(webhook_payment_entity.id.clone()), // network_advice_code: None, // network_decline_code: None, // network_error_message: None, // }) // } else { // Ok(PaymentsResponseData::TransactionResponse { // resource_id: ResponseId::ConnectorTransactionId( // webhook_payment_entity.id.clone(), // ), // redirection_data: Box::new(None), // mandate_reference: Box::new(None), // connector_metadata: None, // network_txn_id: None, // connector_response_reference_id: Some(webhook_payment_entity.id), // incremental_authorization_allowed: None, // charges: None, // }) // }, // ..item.data // }) // } // } // } // } impl TryFrom<RefundsResponseRouterData<RSync, RazorpayRefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RazorpayRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum ErrorResponse { RazorpayErrorResponse(RazorpayErrorResponse), RazorpayStringError(String), RazorpayError(RazorpayErrorMessage), } #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct RazorpayErrorMessage { pub message: String, } #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct RazorpayErrorResponse { pub error: RazorpayError, } #[serde_with::skip_serializing_none] #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct RazorpayError { pub code: String, pub description: String, pub source: Option<String>, pub step: Option<String>, pub reason: Option<String>, pub metadata: Option<Metadata>, } #[serde_with::skip_serializing_none] #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct Metadata { pub order_id: Option<String>, } // This code can be used later when Razorpay webhooks are implemented // #[derive(Debug, Serialize, Deserialize)] // pub struct RazorpayWebhookPayload { // pub event: RazorpayWebhookEventType, // pub payload: RazorpayWebhookPayloadBody, // } // #[derive(Debug, Serialize, Deserialize)] // #[serde(untagged)] // pub enum RazorpayWebhookEventType { // Payments(RazorpayWebhookPaymentEvent), // Refunds(RazorpayWebhookRefundEvent), // } // #[derive(Debug, Serialize, Deserialize)] // pub struct RazorpayWebhookPayloadBody { // pub refund: Option<RazorpayRefundWebhookPayload>, // pub payment: RazorpayPaymentWebhookPayload, // } // #[derive(Debug, Serialize, Deserialize)] // pub struct RazorpayPaymentWebhookPayload { // pub entity: WebhookPaymentEntity, // } // #[derive(Debug, Serialize, Deserialize)] // pub struct RazorpayRefundWebhookPayload { // pub entity: WebhookRefundEntity, // } // #[derive(Debug, Serialize, Deserialize)] // pub struct WebhookRefundEntity { // pub id: String, // pub status: RazorpayWebhookRefundEvent, // } // #[derive(Debug, Serialize, Eq, PartialEq, Deserialize)] // pub enum RazorpayWebhookRefundEvent { // #[serde(rename = "refund.created")] // Created, // #[serde(rename = "refund.processed")] // Processed, // #[serde(rename = "refund.failed")] // Failed, // #[serde(rename = "refund.speed_change")] // SpeedChange, // } // #[derive(Debug, Serialize, Deserialize)] // pub struct WebhookPaymentEntity { // pub id: String, // pub status: RazorpayWebhookPaymentStatus, // } // #[derive(Debug, Serialize, Eq, PartialEq, Clone, Deserialize)] // #[serde(rename_all = "snake_case")] // pub enum RazorpayWebhookPaymentStatus { // Authorized, // Captured, // Failed, // } // #[derive(Debug, Serialize, Eq, PartialEq, Deserialize)] // pub enum RazorpayWebhookPaymentEvent { // #[serde(rename = "payment.authorized")] // Authorized, // #[serde(rename = "payment.captured")] // Captured, // #[serde(rename = "payment.failed")] // Failed, // } // impl TryFrom<RazorpayWebhookEventType> for api_models::webhooks::IncomingWebhookEvent { // type Error = errors::ConnectorError; // fn try_from(event_type: RazorpayWebhookEventType) -> Result<Self, Self::Error> { // match event_type { // RazorpayWebhookEventType::Payments(payment_event) => match payment_event { // RazorpayWebhookPaymentEvent::Authorized => { // Ok(Self::PaymentIntentAuthorizationSuccess) // } // RazorpayWebhookPaymentEvent::Captured => Ok(Self::PaymentIntentSuccess), // RazorpayWebhookPaymentEvent::Failed => Ok(Self::PaymentIntentFailure), // }, // RazorpayWebhookEventType::Refunds(refund_event) => match refund_event { // RazorpayWebhookRefundEvent::Processed => Ok(Self::RefundSuccess), // RazorpayWebhookRefundEvent::Created => Ok(Self::RefundSuccess), // RazorpayWebhookRefundEvent::Failed => Ok(Self::RefundFailure), // RazorpayWebhookRefundEvent::SpeedChange => Ok(Self::EventNotSupported), // }, // } // } // }
crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs
hyperswitch_connectors::src::connectors::razorpay::transformers
4,831
true
// File: crates/hyperswitch_connectors/src/connectors/blackhawknetwork/transformers.rs // Module: hyperswitch_connectors::src::connectors::blackhawknetwork::transformers use common_enums::{enums, Currency}; use common_utils::types::{MinorUnit, StringMajorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{GiftCardData, PaymentMethodData}, router_data::{ AccessToken, ConnectorAuthType, ErrorResponse, PaymentMethodBalance, RouterData, }, router_flow_types::refunds::{Execute, RSync}, router_request_types::{PaymentsPreProcessingData, ResponseId}, router_response_types::{PaymentsResponseData, PreprocessingResponseId, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::{consts::NO_ERROR_MESSAGE, errors}; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::types::{RefundsResponseRouterData, ResponseRouterData}; pub struct BlackhawknetworkRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for BlackhawknetworkRouterData<T> { fn from((amount, item): (StringMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Clone)] pub struct BlackhawknetworkAuthType { pub(super) client_id: Secret<String>, pub(super) client_secret: Secret<String>, pub(super) product_line_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for BlackhawknetworkAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { client_id: api_key.clone(), client_secret: api_secret.clone(), product_line_id: key1.clone(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType) .attach_printable("Unsupported authentication type for Blackhawk Network"), } } } #[derive(Debug, Serialize, Deserialize)] pub struct BlackhawknetworkAccessTokenRequest { pub grant_type: String, pub client_id: Secret<String>, pub client_secret: Secret<String>, pub scope: String, } impl<F, T> TryFrom<ResponseRouterData<F, BlackhawknetworkTokenResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, BlackhawknetworkTokenResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(AccessToken { token: item.response.access_token, expires: item.response.expires_in, }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BlackhawknetworkVerifyAccountRequest { pub account_number: Secret<String>, pub product_line_id: Secret<String>, pub account_type: AccountType, #[serde(skip_serializing_if = "Option::is_none")] pub pin: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub cvv2: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub expiration_date: Option<Secret<String>>, } impl TryFrom<&PaymentsPreProcessingRouterData> for BlackhawknetworkVerifyAccountRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> { let auth = BlackhawknetworkAuthType::try_from(&item.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let gift_card_data = match &item.request.payment_method_data { Some(PaymentMethodData::GiftCard(gc)) => match gc.as_ref() { GiftCardData::BhnCardNetwork(data) => data, _ => { return Err(errors::ConnectorError::FlowNotSupported { flow: "Balance".to_string(), connector: "BlackHawkNetwork".to_string(), } .into()) } }, _ => { return Err(errors::ConnectorError::FlowNotSupported { flow: "Balance".to_string(), connector: "BlackHawkNetwork".to_string(), } .into()) } }; Ok(Self { account_number: gift_card_data.account_number.clone(), product_line_id: auth.product_line_id, account_type: AccountType::GiftCard, pin: gift_card_data.pin.clone(), cvv2: gift_card_data.cvv2.clone(), expiration_date: gift_card_data.expiration_date.clone().map(Secret::new), }) } } impl<F> TryFrom< ResponseRouterData< F, BlackhawknetworkVerifyAccountResponse, PaymentsPreProcessingData, PaymentsResponseData, >, > for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BlackhawknetworkVerifyAccountResponse, PaymentsPreProcessingData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PaymentsResponseData::PreProcessingResponse { pre_processing_id: PreprocessingResponseId::PreProcessingId( item.response.account.entity_id, ), connector_metadata: None, session_token: None, connector_response_reference_id: None, }), payment_method_balance: Some(PaymentMethodBalance { currency: item.response.account.currency, amount: item.response.account.balance, }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize)] pub struct BlackhawknetworkTokenResponse { pub access_token: Secret<String>, pub expires_in: i64, } #[derive(Serialize, Debug)] pub struct BlackhawknetworkPaymentsRequest { pub account_id: String, pub amount: StringMajorUnit, pub currency: Currency, } impl TryFrom<&BlackhawknetworkRouterData<&PaymentsAuthorizeRouterData>> for BlackhawknetworkPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BlackhawknetworkRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match &item.router_data.request.payment_method_data { PaymentMethodData::GiftCard(_gift_card) => { let account_id = item .router_data .preprocessing_id .to_owned() .ok_or_else(|| { errors::ConnectorError::MissingConnectorRelatedTransactionID { id: "entity_id".to_string(), } })?; Ok(Self { account_id, amount: item.amount.clone(), currency: item.router_data.request.currency, }) } _ => Err(error_stack::Report::new( errors::ConnectorError::NotImplemented("Non-gift card payment method".to_string()), )), } } } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum BlackhawknetworkRedeemResponse { Success(BlackhawknetworkPaymentsResponse), Error(BlackhawknetworkErrorResponse), } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct BlackhawknetworkPaymentsResponse { pub id: String, #[serde(rename = "transactionStatus")] pub status: BlackhawknetworkAttemptStatus, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum BlackhawknetworkAttemptStatus { Approved, Declined, Pending, } impl<F, T> TryFrom<ResponseRouterData<F, BlackhawknetworkRedeemResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, BlackhawknetworkRedeemResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response { BlackhawknetworkRedeemResponse::Success(response) => Ok(Self { status: match response.status { BlackhawknetworkAttemptStatus::Approved => enums::AttemptStatus::Charged, BlackhawknetworkAttemptStatus::Declined => enums::AttemptStatus::Failure, BlackhawknetworkAttemptStatus::Pending => enums::AttemptStatus::Pending, }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), BlackhawknetworkRedeemResponse::Error(error_response) => Ok(Self { response: Err(ErrorResponse { status_code: item.http_code, code: error_response.error.clone(), message: error_response .error_description .clone() .unwrap_or(NO_ERROR_MESSAGE.to_string()), reason: error_response.error_description, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } #[derive(Default, Debug, Serialize)] pub struct BlackhawknetworkRefundRequest { pub amount: StringMajorUnit, } impl<F> TryFrom<&BlackhawknetworkRouterData<&RefundsRouterData<F>>> for BlackhawknetworkRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &BlackhawknetworkRouterData<&RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } #[allow(dead_code)] #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize, Clone, Copy)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum AccountType { CreditCard, GiftCard, LoyaltyCard, PhoneCard, } #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum AccountStatus { New, Activated, Closed, } impl From<AccountStatus> for common_enums::AttemptStatus { fn from(item: AccountStatus) -> Self { match item { AccountStatus::New | AccountStatus::Activated => Self::Pending, AccountStatus::Closed => Self::Failure, } } } #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct AccountInformation { pub entity_id: String, pub balance: MinorUnit, pub currency: Currency, pub status: AccountStatus, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct BlackhawknetworkVerifyAccountResponse { account: AccountInformation, } #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct BlackhawknetworkErrorResponse { pub error: String, pub error_description: Option<String>, }
crates/hyperswitch_connectors/src/connectors/blackhawknetwork/transformers.rs
hyperswitch_connectors::src::connectors::blackhawknetwork::transformers
2,900
true
// File: crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs // Module: hyperswitch_connectors::src::connectors::nexinets::transformers use base64::Engine; use cards::CardNumber; use common_enums::{enums, AttemptStatus}; use common_utils::{consts, errors::CustomResult, request::Method}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{ ApplePayWalletData, BankRedirectData, Card, PaymentMethodData, WalletData, }, router_data::{ConnectorAuthType, RouterData}, router_flow_types::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, WalletData as _, }, }; #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsPaymentsRequest { initial_amount: i64, currency: enums::Currency, channel: NexinetsChannel, product: NexinetsProduct, payment: Option<NexinetsPaymentDetails>, #[serde(rename = "async")] nexinets_async: NexinetsAsyncDetails, merchant_order_id: Option<String>, } #[derive(Debug, Serialize, Default)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum NexinetsChannel { #[default] Ecom, } #[derive(Default, Debug, Serialize)] #[serde(rename_all = "lowercase")] pub enum NexinetsProduct { #[default] Creditcard, Paypal, Giropay, Sofort, Eps, Ideal, Applepay, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] #[serde(untagged)] pub enum NexinetsPaymentDetails { Card(Box<NexiCardDetails>), Wallet(Box<NexinetsWalletDetails>), BankRedirects(Box<NexinetsBankRedirects>), } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexiCardDetails { #[serde(flatten)] card_data: CardDataDetails, cof_contract: Option<CofContract>, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum CardDataDetails { CardDetails(Box<CardDetails>), PaymentInstrument(Box<PaymentInstrument>), } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardDetails { card_number: CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, verification: Secret<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentInstrument { payment_instrument_id: Option<Secret<String>>, } #[derive(Debug, Serialize)] pub struct CofContract { #[serde(rename = "type")] recurring_type: RecurringType, } #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RecurringType { Unscheduled, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsBankRedirects { bic: Option<NexinetsBIC>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsAsyncDetails { pub success_url: Option<String>, pub cancel_url: Option<String>, pub failure_url: Option<String>, } #[derive(Debug, Serialize)] pub enum NexinetsBIC { #[serde(rename = "ABNANL2A")] AbnAmro, #[serde(rename = "ASNBNL21")] AsnBank, #[serde(rename = "BUNQNL2A")] Bunq, #[serde(rename = "INGBNL2A")] Ing, #[serde(rename = "KNABNL2H")] Knab, #[serde(rename = "RABONL2U")] Rabobank, #[serde(rename = "RBRBNL21")] Regiobank, #[serde(rename = "SNSBNL2A")] SnsBank, #[serde(rename = "TRIONL2U")] TriodosBank, #[serde(rename = "FVLBNL22")] VanLanschot, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum NexinetsWalletDetails { ApplePayToken(Box<ApplePayDetails>), } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayDetails { payment_data: serde_json::Value, payment_method: ApplepayPaymentMethod, transaction_identifier: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayPaymentMethod { display_name: String, network: String, #[serde(rename = "type")] token_type: String, } impl TryFrom<&PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let return_url = item.request.router_return_url.clone(); let nexinets_async = NexinetsAsyncDetails { success_url: return_url.clone(), cancel_url: return_url.clone(), failure_url: return_url, }; let (payment, product) = get_payment_details_and_product(item)?; let merchant_order_id = match item.payment_method { // Merchant order id is sent only in case of card payment enums::PaymentMethod::Card => Some(item.connector_request_reference_id.clone()), _ => None, }; Ok(Self { initial_amount: item.request.amount, currency: item.request.currency, channel: NexinetsChannel::Ecom, product, payment, nexinets_async, merchant_order_id, }) } } // Auth Struct pub struct NexinetsAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for NexinetsAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => { let auth_key = format!("{}:{}", key1.peek(), api_key.peek()); let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key)); Ok(Self { api_key: Secret::new(auth_header), }) } _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } } } // PaymentsResponse #[derive(Debug, Deserialize, Clone, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum NexinetsPaymentStatus { Success, Pending, Ok, Failure, Declined, InProgress, Expired, Aborted, } fn get_status(status: NexinetsPaymentStatus, method: NexinetsTransactionType) -> AttemptStatus { match status { NexinetsPaymentStatus::Success => match method { NexinetsTransactionType::Preauth => AttemptStatus::Authorized, NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => { AttemptStatus::Charged } NexinetsTransactionType::Cancel => AttemptStatus::Voided, }, NexinetsPaymentStatus::Declined | NexinetsPaymentStatus::Failure | NexinetsPaymentStatus::Expired | NexinetsPaymentStatus::Aborted => match method { NexinetsTransactionType::Preauth => AttemptStatus::AuthorizationFailed, NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => { AttemptStatus::CaptureFailed } NexinetsTransactionType::Cancel => AttemptStatus::VoidFailed, }, NexinetsPaymentStatus::Ok => match method { NexinetsTransactionType::Preauth => AttemptStatus::Authorized, _ => AttemptStatus::Pending, }, NexinetsPaymentStatus::Pending => AttemptStatus::AuthenticationPending, NexinetsPaymentStatus::InProgress => AttemptStatus::Pending, } } impl TryFrom<&enums::BankNames> for NexinetsBIC { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(bank: &enums::BankNames) -> Result<Self, Self::Error> { match bank { enums::BankNames::AbnAmro => Ok(Self::AbnAmro), enums::BankNames::AsnBank => Ok(Self::AsnBank), enums::BankNames::Bunq => Ok(Self::Bunq), enums::BankNames::Ing => Ok(Self::Ing), enums::BankNames::Knab => Ok(Self::Knab), enums::BankNames::Rabobank => Ok(Self::Rabobank), enums::BankNames::Regiobank => Ok(Self::Regiobank), enums::BankNames::SnsBank => Ok(Self::SnsBank), enums::BankNames::TriodosBank => Ok(Self::TriodosBank), enums::BankNames::VanLanschot => Ok(Self::VanLanschot), _ => Err(errors::ConnectorError::FlowNotSupported { flow: bank.to_string(), connector: "Nexinets".to_string(), } .into()), } } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsPreAuthOrDebitResponse { order_id: String, transaction_type: NexinetsTransactionType, transactions: Vec<NexinetsTransaction>, payment_instrument: PaymentInstrument, redirect_url: Option<Url>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsTransaction { pub transaction_id: String, #[serde(rename = "type")] pub transaction_type: NexinetsTransactionType, pub currency: enums::Currency, pub status: NexinetsPaymentStatus, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum NexinetsTransactionType { Preauth, Debit, Capture, Cancel, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct NexinetsPaymentsMetadata { pub transaction_id: Option<String>, pub order_id: Option<String>, pub psync_flow: NexinetsTransactionType, } impl<F, T> TryFrom<ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let transaction = match item.response.transactions.first() { Some(order) => order, _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, }; let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata { transaction_id: Some(transaction.transaction_id.clone()), order_id: Some(item.response.order_id.clone()), psync_flow: item.response.transaction_type.clone(), }) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let redirection_data = item .response .redirect_url .map(|url| RedirectForm::from((url, Method::Get))); let resource_id = match item.response.transaction_type.clone() { NexinetsTransactionType::Preauth => ResponseId::NoResponseId, NexinetsTransactionType::Debit => { ResponseId::ConnectorTransactionId(transaction.transaction_id.clone()) } _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, }; let mandate_reference = item .response .payment_instrument .payment_instrument_id .map(|id| MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }); Ok(Self { status: get_status(transaction.status.clone(), item.response.transaction_type), response: Ok(PaymentsResponseData::TransactionResponse { resource_id, redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata: Some(connector_metadata), network_txn_id: None, connector_response_reference_id: Some(item.response.order_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsCaptureOrVoidRequest { pub initial_amount: i64, pub currency: enums::Currency, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsOrder { pub order_id: String, } impl TryFrom<&PaymentsCaptureRouterData> for NexinetsCaptureOrVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> { Ok(Self { initial_amount: item.request.amount_to_capture, currency: item.request.currency, }) } } impl TryFrom<&PaymentsCancelRouterData> for NexinetsCaptureOrVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { Ok(Self { initial_amount: item.request.get_amount()?, currency: item.request.get_currency()?, }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsPaymentResponse { pub transaction_id: String, pub status: NexinetsPaymentStatus, pub order: NexinetsOrder, #[serde(rename = "type")] pub transaction_type: NexinetsTransactionType, } impl<F, T> TryFrom<ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let transaction_id = Some(item.response.transaction_id.clone()); let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata { transaction_id, order_id: Some(item.response.order.order_id.clone()), psync_flow: item.response.transaction_type.clone(), }) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let resource_id = match item.response.transaction_type.clone() { NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => { ResponseId::ConnectorTransactionId(item.response.transaction_id) } _ => ResponseId::NoResponseId, }; Ok(Self { status: get_status(item.response.status, item.response.transaction_type), response: Ok(PaymentsResponseData::TransactionResponse { resource_id, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: Some(connector_metadata), network_txn_id: None, connector_response_reference_id: Some(item.response.order.order_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } // REFUND : // Type definition for RefundRequest #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsRefundRequest { pub initial_amount: i64, pub currency: enums::Currency, } impl<F> TryFrom<&RefundsRouterData<F>> for NexinetsRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> { Ok(Self { initial_amount: item.request.refund_amount, currency: item.request.currency, }) } } // Type definition for Refund Response #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NexinetsRefundResponse { pub transaction_id: String, pub status: RefundStatus, pub order: NexinetsOrder, #[serde(rename = "type")] pub transaction_type: RefundType, } #[allow(dead_code)] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RefundStatus { Success, Ok, Failure, Declined, InProgress, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RefundType { Refund, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Success => Self::Success, RefundStatus::Failure | RefundStatus::Declined => Self::Failure, RefundStatus::InProgress | RefundStatus::Ok => Self::Pending, } } } impl TryFrom<RefundsResponseRouterData<Execute, NexinetsRefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, NexinetsRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction_id, refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, NexinetsRefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, NexinetsRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction_id, refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] pub struct NexinetsErrorResponse { pub status: u16, pub code: u16, pub message: String, pub errors: Vec<OrderErrorDetails>, } #[derive(Debug, Deserialize, Clone, Serialize)] pub struct OrderErrorDetails { pub code: u16, pub message: String, pub field: Option<String>, } fn get_payment_details_and_product( item: &PaymentsAuthorizeRouterData, ) -> Result< (Option<NexinetsPaymentDetails>, NexinetsProduct), error_stack::Report<errors::ConnectorError>, > { match &item.request.payment_method_data { PaymentMethodData::Card(card) => Ok(( Some(get_card_data(item, card)?), NexinetsProduct::Creditcard, )), PaymentMethodData::Wallet(wallet) => Ok(get_wallet_details(wallet)?), PaymentMethodData::BankRedirect(bank_redirect) => match bank_redirect { BankRedirectData::Eps { .. } => Ok((None, NexinetsProduct::Eps)), BankRedirectData::Giropay { .. } => Ok((None, NexinetsProduct::Giropay)), BankRedirectData::Ideal { bank_name, .. } => Ok(( Some(NexinetsPaymentDetails::BankRedirects(Box::new( NexinetsBankRedirects { bic: bank_name .map(|bank_name| NexinetsBIC::try_from(&bank_name)) .transpose()?, }, ))), NexinetsProduct::Ideal, )), BankRedirectData::Sofort { .. } => Ok((None, NexinetsProduct::Sofort)), BankRedirectData::BancontactCard { .. } | BankRedirectData::Blik { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::Trustly { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::LocalBankRedirect {} => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nexinets"), ))? } }, PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nexinets"), ))? } } } fn get_card_data( item: &PaymentsAuthorizeRouterData, card: &Card, ) -> Result<NexinetsPaymentDetails, errors::ConnectorError> { let (card_data, cof_contract) = match item.request.is_mandate_payment() { true => { let card_data = match item.request.off_session { Some(true) => CardDataDetails::PaymentInstrument(Box::new(PaymentInstrument { payment_instrument_id: item.request.connector_mandate_id().map(Secret::new), })), _ => CardDataDetails::CardDetails(Box::new(get_card_details(card)?)), }; let cof_contract = Some(CofContract { recurring_type: RecurringType::Unscheduled, }); (card_data, cof_contract) } false => ( CardDataDetails::CardDetails(Box::new(get_card_details(card)?)), None, ), }; Ok(NexinetsPaymentDetails::Card(Box::new(NexiCardDetails { card_data, cof_contract, }))) } fn get_applepay_details( wallet_data: &WalletData, applepay_data: &ApplePayWalletData, ) -> CustomResult<ApplePayDetails, errors::ConnectorError> { let payment_data = WalletData::get_wallet_token_as_json(wallet_data, "Apple Pay".to_string())?; Ok(ApplePayDetails { payment_data, payment_method: ApplepayPaymentMethod { display_name: applepay_data.payment_method.display_name.to_owned(), network: applepay_data.payment_method.network.to_owned(), token_type: applepay_data.payment_method.pm_type.to_owned(), }, transaction_identifier: applepay_data.transaction_identifier.to_owned(), }) } fn get_card_details(req_card: &Card) -> Result<CardDetails, errors::ConnectorError> { Ok(CardDetails { card_number: req_card.card_number.clone(), expiry_month: req_card.card_exp_month.clone(), expiry_year: req_card.get_card_expiry_year_2_digit()?, verification: req_card.card_cvc.clone(), }) } fn get_wallet_details( wallet: &WalletData, ) -> Result< (Option<NexinetsPaymentDetails>, NexinetsProduct), error_stack::Report<errors::ConnectorError>, > { match wallet { WalletData::PaypalRedirect(_) => Ok((None, NexinetsProduct::Paypal)), WalletData::ApplePay(applepay_data) => Ok(( Some(NexinetsPaymentDetails::Wallet(Box::new( NexinetsWalletDetails::ApplePayToken(Box::new(get_applepay_details( wallet, applepay_data, )?)), ))), NexinetsProduct::Applepay, )), WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect { .. } | WalletData::GooglePay(_) | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect { .. } | WalletData::VippsRedirect { .. } | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nexinets"), ))?, } } pub fn get_order_id( meta: &NexinetsPaymentsMetadata, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { let order_id = meta.order_id.clone().ok_or( errors::ConnectorError::MissingConnectorRelatedTransactionID { id: "order_id".to_string(), }, )?; Ok(order_id) } pub fn get_transaction_id( meta: &NexinetsPaymentsMetadata, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { let transaction_id = meta.transaction_id.clone().ok_or( errors::ConnectorError::MissingConnectorRelatedTransactionID { id: "transaction_id".to_string(), }, )?; Ok(transaction_id) }
crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
hyperswitch_connectors::src::connectors::nexinets::transformers
6,022
true
// File: crates/hyperswitch_connectors/src/connectors/hyperswitch_vault/transformers.rs // Module: hyperswitch_connectors::src::connectors::hyperswitch_vault::transformers use common_utils::pii::Email; use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, RouterData}, router_flow_types::vault::ExternalVaultCreateFlow, router_response_types::{ ConnectorCustomerResponseData, PaymentsResponseData, VaultResponseData, }, types::{ConnectorCustomerRouterData, VaultRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{types::ResponseRouterData, utils}; #[derive(Default, Debug, Serialize)] pub struct HyperswitchVaultCreateRequest { customer_id: String, } impl TryFrom<&VaultRouterData<ExternalVaultCreateFlow>> for HyperswitchVaultCreateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &VaultRouterData<ExternalVaultCreateFlow>) -> Result<Self, Self::Error> { let customer_id = item .request .connector_customer_id .clone() .ok_or_else(utils::missing_field_err("connector_customer"))?; Ok(Self { customer_id }) } } pub struct HyperswitchVaultAuthType { pub(super) api_key: Secret<String>, pub(super) profile_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for HyperswitchVaultAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, api_secret, .. } => Ok(Self { api_key: api_key.to_owned(), profile_id: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct HyperswitchVaultCreateResponse { id: Secret<String>, client_secret: Secret<String>, } impl<F, T> TryFrom<ResponseRouterData<F, HyperswitchVaultCreateResponse, T, VaultResponseData>> for RouterData<F, T, VaultResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, HyperswitchVaultCreateResponse, T, VaultResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(VaultResponseData::ExternalVaultCreateResponse { session_id: item.response.id, client_secret: item.response.client_secret, }), ..item.data }) } } #[derive(Default, Debug, Serialize)] pub struct HyperswitchVaultCustomerCreateRequest { name: Option<Secret<String>>, email: Option<Email>, } impl TryFrom<&ConnectorCustomerRouterData> for HyperswitchVaultCustomerCreateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &ConnectorCustomerRouterData) -> Result<Self, Self::Error> { Ok(Self { name: item.request.name.clone(), email: item.request.email.clone(), }) } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct HyperswitchVaultCustomerCreateResponse { id: String, } impl<F, T> TryFrom<ResponseRouterData<F, HyperswitchVaultCustomerCreateResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, HyperswitchVaultCustomerCreateResponse, T, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PaymentsResponseData::ConnectorCustomerResponse( ConnectorCustomerResponseData::new_with_customer_id(item.response.id), )), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize)] pub struct HyperswitchVaultErrorResponse { pub error: HyperswitchVaultErrorDetails, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct HyperswitchVaultErrorDetails { #[serde(alias = "type")] pub error_type: String, pub message: Option<String>, pub code: String, }
crates/hyperswitch_connectors/src/connectors/hyperswitch_vault/transformers.rs
hyperswitch_connectors::src::connectors::hyperswitch_vault::transformers
962
true
// File: crates/hyperswitch_connectors/src/connectors/plaid/transformers.rs // Module: hyperswitch_connectors::src::connectors::plaid::transformers use api_models::payments::OpenBankingSessionToken; use common_enums::{AttemptStatus, Currency}; use common_utils::types::FloatMajorUnit; use hyperswitch_domain_models::{ payment_method_data::{OpenBankingData, PaymentMethodData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_request_types::ResponseId, router_response_types::PaymentsResponseData, types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData}, }; use hyperswitch_interfaces::errors::ConnectorError; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{PaymentsPostProcessingRouterData, ResponseRouterData}, utils::is_payment_failure, }; pub struct PlaidRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for PlaidRouterData<T> { fn from((amount, item): (FloatMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Default, Debug, Serialize)] pub struct PlaidPaymentsRequest { amount: PlaidAmount, recipient_id: String, reference: String, #[serde(skip_serializing_if = "Option::is_none")] schedule: Option<PlaidSchedule>, #[serde(skip_serializing_if = "Option::is_none")] options: Option<PlaidOptions>, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidAmount { currency: Currency, value: FloatMajorUnit, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidSchedule { interval: String, interval_execution_day: String, start_date: String, end_date: Option<String>, adjusted_start_date: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidOptions { request_refund_details: bool, iban: Option<Secret<String>>, bacs: Option<PlaidBacs>, scheme: String, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidBacs { account: Secret<String>, sort_code: Secret<String>, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct PlaidLinkTokenRequest { client_name: String, country_codes: Vec<String>, language: String, products: Vec<String>, user: User, payment_initiation: PlaidPaymentInitiation, redirect_uri: Option<String>, android_package_name: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct User { pub client_user_id: String, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidPaymentInitiation { payment_id: String, } impl TryFrom<&PlaidRouterData<&PaymentsAuthorizeRouterData>> for PlaidPaymentsRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &PlaidRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::OpenBanking(ref data) => match data { OpenBankingData::OpenBankingPIS { .. } => { let amount = item.amount; let currency = item.router_data.request.currency; let payment_id = item.router_data.payment_id.clone(); let id_len = payment_id.len(); let reference = if id_len > 18 { payment_id.get(id_len - 18..id_len).map(|id| id.to_string()) } else { Some(payment_id) } .ok_or(ConnectorError::MissingRequiredField { field_name: "payment_id", })?; let recipient_type = item .router_data .additional_merchant_data .as_ref() .map(|merchant_data| match merchant_data { api_models::admin::AdditionalMerchantData::OpenBankingRecipientData( data, ) => data.clone(), }) .ok_or(ConnectorError::MissingRequiredField { field_name: "additional_merchant_data", })?; let recipient_id = match recipient_type { api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => { Ok(id.peek().to_string()) } _ => Err(ConnectorError::MissingRequiredField { field_name: "ConnectorRecipientId", }), }?; Ok(Self { amount: PlaidAmount { currency, value: amount, }, reference, recipient_id, schedule: None, options: None, }) } }, _ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } impl TryFrom<&PaymentsSyncRouterData> for PlaidSyncRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> { match item.request.connector_transaction_id { ResponseId::ConnectorTransactionId(ref id) => Ok(Self { payment_id: id.clone(), }), _ => Err((ConnectorError::MissingConnectorTransactionID).into()), } } } impl TryFrom<&PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &PaymentsPostProcessingRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data { PaymentMethodData::OpenBanking(ref data) => match data { OpenBankingData::OpenBankingPIS { .. } => { let headers = item.header_payload.clone(); let platform = headers .as_ref() .and_then(|headers| headers.x_client_platform.clone()); let (is_android, is_ios) = match platform { Some(common_enums::ClientPlatform::Android) => (true, false), Some(common_enums::ClientPlatform::Ios) => (false, true), _ => (false, false), }; Ok(Self { client_name: "Hyperswitch".to_string(), country_codes: item .request .country .map(|code| vec![code.to_string()]) .ok_or(ConnectorError::MissingRequiredField { field_name: "billing.address.country", })?, language: "en".to_string(), products: vec!["payment_initiation".to_string()], user: User { client_user_id: item .request .customer_id .clone() .map(|id| id.get_string_repr().to_string()) .unwrap_or("default cust".to_string()), }, payment_initiation: PlaidPaymentInitiation { payment_id: item .request .connector_transaction_id .clone() .ok_or(ConnectorError::MissingConnectorTransactionID)?, }, android_package_name: if is_android { headers .as_ref() .and_then(|headers| headers.x_app_id.clone()) } else { None }, redirect_uri: if is_ios { headers .as_ref() .and_then(|headers| headers.x_redirect_uri.clone()) } else { None }, }) } }, _ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } pub struct PlaidAuthType { pub client_id: Secret<String>, pub secret: Secret<String>, } impl TryFrom<&ConnectorAuthType> for PlaidAuthType { type Error = error_stack::Report<ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { client_id: api_key.to_owned(), secret: key1.to_owned(), }), _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[derive(strum::Display)] pub enum PlaidPaymentStatus { PaymentStatusInputNeeded, PaymentStatusInitiated, PaymentStatusInsufficientFunds, PaymentStatusFailed, PaymentStatusBlocked, PaymentStatusCancelled, PaymentStatusExecuted, PaymentStatusSettled, PaymentStatusEstablished, PaymentStatusRejected, PaymentStatusAuthorising, } impl From<PlaidPaymentStatus> for AttemptStatus { fn from(item: PlaidPaymentStatus) -> Self { match item { PlaidPaymentStatus::PaymentStatusAuthorising => Self::Authorizing, PlaidPaymentStatus::PaymentStatusBlocked | PlaidPaymentStatus::PaymentStatusInsufficientFunds | PlaidPaymentStatus::PaymentStatusRejected => Self::AuthorizationFailed, PlaidPaymentStatus::PaymentStatusCancelled => Self::Voided, PlaidPaymentStatus::PaymentStatusEstablished => Self::Authorized, PlaidPaymentStatus::PaymentStatusExecuted | PlaidPaymentStatus::PaymentStatusSettled | PlaidPaymentStatus::PaymentStatusInitiated => Self::Charged, PlaidPaymentStatus::PaymentStatusFailed => Self::Failure, PlaidPaymentStatus::PaymentStatusInputNeeded => Self::AuthenticationPending, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PlaidPaymentsResponse { status: PlaidPaymentStatus, payment_id: String, } impl<F, T> TryFrom<ResponseRouterData<F, PlaidPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, PlaidPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let status = AttemptStatus::from(item.response.status.clone()); Ok(Self { status, response: if is_payment_failure(status) { Err(ErrorResponse { // populating status everywhere as plaid only sends back a status code: item.response.status.clone().to_string(), message: item.response.status.clone().to_string(), reason: Some(item.response.status.to_string()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.payment_id), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.payment_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.payment_id), incremental_authorization_allowed: None, charges: None, }) }, ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidLinkTokenResponse { link_token: String, } impl<F, T> TryFrom<ResponseRouterData<F, PlaidLinkTokenResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, PlaidLinkTokenResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let session_token = Some(OpenBankingSessionToken { open_banking_session_token: item.response.link_token, }); Ok(Self { status: AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::PostProcessingResponse { session_token }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidSyncRequest { payment_id: String, } #[derive(Debug, Serialize, Deserialize)] pub struct PlaidSyncResponse { payment_id: String, amount: PlaidAmount, status: PlaidPaymentStatus, recipient_id: String, reference: String, last_status_update: String, adjusted_reference: Option<String>, schedule: Option<PlaidSchedule>, iban: Option<Secret<String>>, bacs: Option<PlaidBacs>, scheme: Option<String>, adjusted_scheme: Option<String>, request_id: String, } impl<F, T> TryFrom<ResponseRouterData<F, PlaidSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, PlaidSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let status = AttemptStatus::from(item.response.status.clone()); Ok(Self { status, response: if is_payment_failure(status) { Err(ErrorResponse { // populating status everywhere as plaid only sends back a status code: item.response.status.clone().to_string(), message: item.response.status.clone().to_string(), reason: Some(item.response.status.to_string()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.payment_id), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.payment_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.payment_id), incremental_authorization_allowed: None, charges: None, }) }, ..item.data }) } } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct PlaidErrorResponse { pub display_message: Option<String>, pub error_code: Option<String>, pub error_message: String, pub error_type: Option<String>, }
crates/hyperswitch_connectors/src/connectors/plaid/transformers.rs
hyperswitch_connectors::src::connectors::plaid::transformers
3,120
true
// File: crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs // Module: hyperswitch_connectors::src::connectors::affirm::transformers use common_enums::{enums, CountryAlpha2, Currency}; use common_utils::{pii, request::Method, types::MinorUnit}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::{PayLaterData, PaymentMethodData}, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{PaymentsCancelData, PaymentsCaptureData, ResponseId}, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{PaymentsAuthorizeRequestData, RouterData as OtherRouterData}, }; pub struct AffirmRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> From<(MinorUnit, T)> for AffirmRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Serialize)] pub struct AffirmPaymentsRequest { pub merchant: Merchant, pub items: Vec<Item>, pub shipping: Option<Shipping>, pub billing: Option<Billing>, pub total: MinorUnit, pub currency: Currency, pub order_id: Option<String>, } #[derive(Debug, Serialize)] pub struct AffirmCompleteAuthorizeRequest { pub order_id: Option<String>, pub reference_id: Option<String>, pub transaction_id: String, } impl TryFrom<&PaymentsCompleteAuthorizeRouterData> for AffirmCompleteAuthorizeRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> { let transaction_id = item.request.connector_transaction_id.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "connector_transaction_id", }, )?; let reference_id = item.reference_id.clone(); let order_id = item.connector_request_reference_id.clone(); Ok(Self { transaction_id, order_id: Some(order_id), reference_id, }) } } #[derive(Debug, Serialize)] pub struct Merchant { pub public_api_key: Secret<String>, pub user_confirmation_url: String, pub user_cancel_url: String, pub user_confirmation_url_action: Option<String>, pub use_vcn: Option<String>, pub name: Option<String>, } #[derive(Debug, Serialize)] pub struct Item { pub display_name: String, pub sku: String, pub unit_price: MinorUnit, pub qty: i64, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Shipping { pub name: Name, pub address: Address, #[serde(skip_serializing_if = "Option::is_none")] pub phone_number: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub email: Option<pii::Email>, } #[derive(Debug, Serialize)] pub struct Billing { pub name: Name, pub address: Address, #[serde(skip_serializing_if = "Option::is_none")] pub phone_number: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub email: Option<pii::Email>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Name { pub first: Option<Secret<String>>, pub last: Option<Secret<String>>, pub full: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Address { pub line1: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub line2: Option<Secret<String>>, pub city: Option<String>, pub state: Option<Secret<String>>, pub zipcode: Option<Secret<String>>, pub country: Option<CountryAlpha2>, } #[derive(Debug, Serialize)] pub struct Metadata { #[serde(skip_serializing_if = "Option::is_none")] pub shipping_type: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub entity_name: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub platform_type: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub platform_version: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub platform_affirm: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub webhook_session_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub mode: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub customer: Option<Value>, #[serde(skip_serializing_if = "Option::is_none")] pub itinerary: Option<Vec<Value>>, #[serde(skip_serializing_if = "Option::is_none")] pub checkout_channel_type: Option<String>, #[serde(rename = "BOPIS", skip_serializing_if = "Option::is_none")] pub bopis: Option<bool>, } #[derive(Debug, Serialize)] pub struct Discount { pub discount_amount: MinorUnit, pub discount_display_name: String, pub discount_code: Option<String>, } impl TryFrom<&AffirmRouterData<&PaymentsAuthorizeRouterData>> for AffirmPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &AffirmRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let router_data = &item.router_data; let request = &router_data.request; let billing = Some(Billing { name: Name { first: item.router_data.get_optional_billing_first_name(), last: item.router_data.get_optional_billing_last_name(), full: item.router_data.get_optional_billing_full_name(), }, address: Address { line1: item.router_data.get_optional_billing_line1(), line2: item.router_data.get_optional_billing_line2(), city: item.router_data.get_optional_billing_city(), state: item.router_data.get_optional_billing_state(), zipcode: item.router_data.get_optional_billing_zip(), country: item.router_data.get_optional_billing_country(), }, phone_number: item.router_data.get_optional_billing_phone_number(), email: item.router_data.get_optional_billing_email(), }); let shipping = Some(Shipping { name: Name { first: item.router_data.get_optional_shipping_first_name(), last: item.router_data.get_optional_shipping_last_name(), full: item.router_data.get_optional_shipping_full_name(), }, address: Address { line1: item.router_data.get_optional_shipping_line1(), line2: item.router_data.get_optional_shipping_line2(), city: item.router_data.get_optional_shipping_city(), state: item.router_data.get_optional_shipping_state(), zipcode: item.router_data.get_optional_shipping_zip(), country: item.router_data.get_optional_shipping_country(), }, phone_number: item.router_data.get_optional_shipping_phone_number(), email: item.router_data.get_optional_shipping_email(), }); match request.payment_method_data.clone() { PaymentMethodData::PayLater(PayLaterData::AffirmRedirect {}) => { let items = match request.order_details.clone() { Some(order_details) => order_details .iter() .map(|data| { Ok(Item { display_name: data.product_name.clone(), sku: data.product_id.clone().unwrap_or_default(), unit_price: data.amount, qty: data.quantity.into(), }) }) .collect::<Result<Vec<_>, _>>(), None => Err(report!(errors::ConnectorError::MissingRequiredField { field_name: "order_details", })), }?; let auth_type = AffirmAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let public_api_key = auth_type.public_key; let merchant = Merchant { public_api_key, user_confirmation_url: request.get_complete_authorize_url()?, user_cancel_url: request.get_router_return_url()?, user_confirmation_url_action: None, use_vcn: None, name: None, }; Ok(Self { merchant, items, shipping, billing, total: item.amount, currency: request.currency, order_id: Some(item.router_data.connector_request_reference_id.clone()), }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } pub struct AffirmAuthType { pub public_key: Secret<String>, pub private_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for AffirmAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { public_key: api_key.to_owned(), private_key: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } impl From<AffirmTransactionStatus> for common_enums::AttemptStatus { fn from(item: AffirmTransactionStatus) -> Self { match item { AffirmTransactionStatus::Authorized => Self::Authorized, AffirmTransactionStatus::AuthExpired => Self::Failure, AffirmTransactionStatus::Canceled => Self::Voided, AffirmTransactionStatus::Captured => Self::Charged, AffirmTransactionStatus::ConfirmationExpired => Self::Failure, AffirmTransactionStatus::Confirmed => Self::Authorized, AffirmTransactionStatus::Created => Self::Pending, AffirmTransactionStatus::Declined => Self::Failure, AffirmTransactionStatus::Disputed => Self::Unresolved, AffirmTransactionStatus::DisputeRefunded => Self::Unresolved, AffirmTransactionStatus::ExpiredAuthorization => Self::Failure, AffirmTransactionStatus::ExpiredConfirmation => Self::Failure, AffirmTransactionStatus::PartiallyCaptured => Self::Charged, AffirmTransactionStatus::Voided => Self::Voided, AffirmTransactionStatus::PartiallyVoided => Self::Voided, } } } impl From<AffirmRefundStatus> for common_enums::RefundStatus { fn from(item: AffirmRefundStatus) -> Self { match item { AffirmRefundStatus::PartiallyRefunded => Self::Success, AffirmRefundStatus::Refunded => Self::Success, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct AffirmPaymentsResponse { checkout_id: String, redirect_url: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AffirmCompleteAuthorizeResponse { pub id: String, pub status: AffirmTransactionStatus, pub amount: MinorUnit, pub amount_refunded: MinorUnit, pub authorization_expiration: String, pub checkout_id: String, pub created: String, pub currency: Currency, pub events: Vec<TransactionEvent>, pub settlement_transaction_id: Option<String>, pub transaction_id: String, pub order_id: String, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub agent_alias: Option<String>, pub merchant_transaction_id: Option<String>, pub provider_id: Option<i64>, pub remove_tax: Option<bool>, pub checkout: Option<Value>, pub refund_expires: Option<String>, pub remaining_capturable_amount: Option<i64>, pub loan_information: Option<LoanInformation>, pub user_id: Option<String>, pub platform: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct TransactionEvent { pub id: String, pub amount: MinorUnit, pub created: String, pub currency: Currency, pub fee: Option<i64>, pub fee_refunded: Option<MinorUnit>, pub reference_id: Option<String>, #[serde(rename = "type")] pub event_type: AffirmEventType, pub settlement_transaction_id: Option<String>, pub transaction_id: String, pub order_id: String, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub agent_alias: Option<String>, pub merchant_transaction_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct LoanInformation { pub fees: Option<LoanFees>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct LoanFees { pub amount: Option<MinorUnit>, pub description: Option<String>, } #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AffirmTransactionStatus { Authorized, AuthExpired, Canceled, Captured, ConfirmationExpired, Confirmed, Created, Declined, Disputed, DisputeRefunded, ExpiredAuthorization, ExpiredConfirmation, PartiallyCaptured, Voided, PartiallyVoided, } #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AffirmRefundStatus { PartiallyRefunded, Refunded, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AffirmPSyncResponse { pub amount: MinorUnit, pub amount_refunded: MinorUnit, pub authorization_expiration: Option<String>, pub checkout_id: String, pub created: String, pub currency: Currency, pub events: Vec<TransactionEvent>, pub id: String, pub order_id: String, pub provider_id: Option<i64>, pub remove_tax: Option<bool>, pub status: AffirmTransactionStatus, pub checkout: Option<Value>, pub refund_expires: Option<String>, pub remaining_capturable_amount: Option<MinorUnit>, pub loan_information: Option<LoanInformation>, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub merchant_transaction_id: Option<String>, pub settlement_transaction_id: Option<String>, pub transaction_id: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AffirmRsyncResponse { pub amount: MinorUnit, pub amount_refunded: MinorUnit, pub authorization_expiration: String, pub checkout_id: String, pub created: String, pub currency: Currency, pub events: Vec<TransactionEvent>, pub id: String, pub order_id: String, pub status: AffirmRefundStatus, pub refund_expires: Option<String>, pub remaining_capturable_amount: Option<MinorUnit>, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub merchant_transaction_id: Option<String>, pub settlement_transaction_id: Option<String>, pub transaction_id: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum AffirmResponseWrapper { Authorize(AffirmPaymentsResponse), Psync(Box<AffirmPSyncResponse>), } impl<F, T> TryFrom<ResponseRouterData<F, AffirmResponseWrapper, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AffirmResponseWrapper, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match &item.response { AffirmResponseWrapper::Authorize(resp) => { let redirection_data = url::Url::parse(&resp.redirect_url) .ok() .map(|url| RedirectForm::from((url, Method::Get))); Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(resp.checkout_id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, charges: None, incremental_authorization_allowed: None, }), ..item.data }) } AffirmResponseWrapper::Psync(resp) => { let status = enums::AttemptStatus::from(resp.status); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(resp.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, charges: None, incremental_authorization_allowed: None, }), ..item.data }) } } } } impl<F, T> TryFrom<ResponseRouterData<F, AffirmCompleteAuthorizeResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AffirmCompleteAuthorizeResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Default, Debug, Serialize)] pub struct AffirmRefundRequest { pub amount: MinorUnit, #[serde(skip_serializing_if = "Option::is_none")] pub reference_id: Option<String>, } impl<F> TryFrom<&AffirmRouterData<&RefundsRouterData<F>>> for AffirmRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &AffirmRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let reference_id = item.router_data.request.connector_transaction_id.clone(); Ok(Self { amount: item.amount.to_owned(), reference_id: Some(reference_id), }) } } #[allow(dead_code)] #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AffirmRefundResponse { pub id: String, pub amount: MinorUnit, pub created: String, pub currency: Currency, pub fee: Option<MinorUnit>, pub fee_refunded: Option<MinorUnit>, pub reference_id: Option<String>, #[serde(rename = "type")] pub event_type: AffirmEventType, pub settlement_transaction_id: Option<String>, pub transaction_id: String, pub order_id: String, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub agent_alias: Option<String>, pub merchant_transaction_id: Option<String>, } impl From<AffirmEventType> for enums::RefundStatus { fn from(event_type: AffirmEventType) -> Self { match event_type { AffirmEventType::Refund => Self::Success, _ => Self::Pending, } } } impl TryFrom<RefundsResponseRouterData<Execute, AffirmRefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, AffirmRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.event_type), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, AffirmRsyncResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, AffirmRsyncResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct AffirmErrorResponse { pub status_code: u16, pub code: String, pub message: String, #[serde(rename = "type")] pub error_type: String, } #[derive(Debug, Serialize)] pub struct AffirmCaptureRequest { pub order_id: Option<String>, pub reference_id: Option<String>, pub amount: MinorUnit, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, } impl TryFrom<&AffirmRouterData<&PaymentsCaptureRouterData>> for AffirmCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &AffirmRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { let reference_id = match item.router_data.connector_request_reference_id.clone() { ref_id if ref_id.is_empty() => None, ref_id => Some(ref_id), }; let amount = item.amount; Ok(Self { reference_id, amount, order_id: None, shipping_carrier: None, shipping_confirmation: None, }) } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AffirmCaptureResponse { pub id: String, pub amount: MinorUnit, pub created: String, pub currency: Currency, pub fee: Option<MinorUnit>, pub fee_refunded: Option<MinorUnit>, pub reference_id: Option<String>, #[serde(rename = "type")] pub event_type: AffirmEventType, pub settlement_transaction_id: Option<String>, pub transaction_id: String, pub order_id: String, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub agent_alias: Option<String>, pub merchant_transaction_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum AffirmEventType { Auth, AuthExpired, Capture, ChargeOff, Confirm, ConfirmationExpired, ExpireAuthorization, ExpireConfirmation, Refund, SplitCapture, Update, Void, PartialVoid, RefundVoided, } impl From<AffirmEventType> for enums::AttemptStatus { fn from(event_type: AffirmEventType) -> Self { match event_type { AffirmEventType::Auth => Self::Authorized, AffirmEventType::Capture | AffirmEventType::SplitCapture | AffirmEventType::Confirm => { Self::Charged } AffirmEventType::AuthExpired | AffirmEventType::ChargeOff | AffirmEventType::ConfirmationExpired | AffirmEventType::ExpireAuthorization | AffirmEventType::ExpireConfirmation => Self::Failure, AffirmEventType::Refund | AffirmEventType::RefundVoided => Self::AutoRefunded, AffirmEventType::Update => Self::Pending, AffirmEventType::Void | AffirmEventType::PartialVoid => Self::Voided, } } } impl<F> TryFrom<ResponseRouterData<F, AffirmCaptureResponse, PaymentsCaptureData, PaymentsResponseData>> for RouterData<F, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, AffirmCaptureResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.event_type.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl TryFrom<&PaymentsCancelRouterData> for AffirmCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let request = &item.request; let reference_id = request.connector_transaction_id.clone(); let amount = item .request .amount .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "amount", })?; Ok(Self { reference_id: Some(reference_id), amount, merchant_transaction_id: None, }) } } #[derive(Debug, Serialize)] pub struct AffirmCancelRequest { pub reference_id: Option<String>, pub amount: i64, pub merchant_transaction_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AffirmCancelResponse { pub id: String, pub amount: MinorUnit, pub created: String, pub currency: Currency, pub fee: Option<MinorUnit>, pub fee_refunded: Option<MinorUnit>, pub reference_id: Option<String>, #[serde(rename = "type")] pub event_type: AffirmEventType, pub settlement_transaction_id: Option<String>, pub transaction_id: String, pub order_id: String, pub shipping_carrier: Option<String>, pub shipping_confirmation: Option<String>, pub shipping: Option<Shipping>, pub agent_alias: Option<String>, pub merchant_transaction_id: Option<String>, } impl<F> TryFrom<ResponseRouterData<F, AffirmCancelResponse, PaymentsCancelData, PaymentsResponseData>> for RouterData<F, PaymentsCancelData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AffirmCancelResponse, PaymentsCancelData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.event_type.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } }
crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
hyperswitch_connectors::src::connectors::affirm::transformers
6,113
true
// File: crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs // Module: hyperswitch_connectors::src::connectors::trustpayments::transformers use cards; use common_enums::enums; use common_utils::types::StringMinorUnit; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{self, CardData, RefundsRequestData, RouterData as RouterDataExt}, }; const TRUSTPAYMENTS_API_VERSION: &str = "1.00"; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub enum TrustpaymentsSettleStatus { #[serde(rename = "0")] PendingSettlement, #[serde(rename = "1")] Settled, #[serde(rename = "2")] ManualCapture, #[serde(rename = "3")] Voided, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub enum TrustpaymentsCredentialsOnFile { #[serde(rename = "0")] NoStoredCredentials, #[serde(rename = "1")] CardholderInitiatedTransaction, #[serde(rename = "2")] MerchantInitiatedTransaction, } impl TrustpaymentsCredentialsOnFile { pub fn as_str(&self) -> &'static str { match self { Self::NoStoredCredentials => "0", Self::CardholderInitiatedTransaction => "1", Self::MerchantInitiatedTransaction => "2", } } } impl std::fmt::Display for TrustpaymentsCredentialsOnFile { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_str()) } } impl TrustpaymentsSettleStatus { pub fn as_str(&self) -> &'static str { match self { Self::PendingSettlement => "0", Self::Settled => "1", Self::ManualCapture => "2", Self::Voided => "3", } } } impl std::fmt::Display for TrustpaymentsSettleStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_str()) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub enum TrustpaymentsErrorCode { #[serde(rename = "0")] Success, #[serde(rename = "30000")] InvalidCredentials, #[serde(rename = "30001")] AuthenticationFailed, #[serde(rename = "30002")] InvalidSiteReference, #[serde(rename = "30003")] AccessDenied, #[serde(rename = "30004")] InvalidUsernameOrPassword, #[serde(rename = "30005")] AccountSuspended, #[serde(rename = "50000")] MissingRequiredField, #[serde(rename = "50001")] InvalidFieldFormat, #[serde(rename = "50002")] InvalidFieldValue, #[serde(rename = "50003")] FieldTooLong, #[serde(rename = "50004")] FieldTooShort, #[serde(rename = "50005")] InvalidCurrency, #[serde(rename = "50006")] InvalidAmount, #[serde(rename = "60000")] GeneralProcessingError, #[serde(rename = "60001")] SystemError, #[serde(rename = "60002")] CommunicationError, #[serde(rename = "60003")] Timeout, #[serde(rename = "60004")] Processing, #[serde(rename = "60005")] InvalidRequest, #[serde(rename = "60019")] NoSearchableFilter, #[serde(rename = "70000")] InvalidCardNumber, #[serde(rename = "70001")] InvalidExpiryDate, #[serde(rename = "70002")] InvalidSecurityCode, #[serde(rename = "70003")] InvalidCardType, #[serde(rename = "70004")] CardExpired, #[serde(rename = "70005")] InsufficientFunds, #[serde(rename = "70006")] CardDeclined, #[serde(rename = "70007")] CardRestricted, #[serde(rename = "70008")] InvalidMerchant, #[serde(rename = "70009")] TransactionNotPermitted, #[serde(rename = "70010")] ExceedsWithdrawalLimit, #[serde(rename = "70011")] SecurityViolation, #[serde(rename = "70012")] LostOrStolenCard, #[serde(rename = "70013")] SuspectedFraud, #[serde(rename = "70014")] ContactCardIssuer, #[serde(rename = "70015")] InvalidAmountValue, #[serde(untagged)] Unknown(String), } impl TrustpaymentsErrorCode { pub fn as_str(&self) -> &str { match self { Self::Success => "0", Self::InvalidCredentials => "30000", Self::AuthenticationFailed => "30001", Self::InvalidSiteReference => "30002", Self::AccessDenied => "30003", Self::InvalidUsernameOrPassword => "30004", Self::AccountSuspended => "30005", Self::MissingRequiredField => "50000", Self::InvalidFieldFormat => "50001", Self::InvalidFieldValue => "50002", Self::FieldTooLong => "50003", Self::FieldTooShort => "50004", Self::InvalidCurrency => "50005", Self::InvalidAmount => "50006", Self::GeneralProcessingError => "60000", Self::SystemError => "60001", Self::CommunicationError => "60002", Self::Timeout => "60003", Self::Processing => "60004", Self::InvalidRequest => "60005", Self::NoSearchableFilter => "60019", Self::InvalidCardNumber => "70000", Self::InvalidExpiryDate => "70001", Self::InvalidSecurityCode => "70002", Self::InvalidCardType => "70003", Self::CardExpired => "70004", Self::InsufficientFunds => "70005", Self::CardDeclined => "70006", Self::CardRestricted => "70007", Self::InvalidMerchant => "70008", Self::TransactionNotPermitted => "70009", Self::ExceedsWithdrawalLimit => "70010", Self::SecurityViolation => "70011", Self::LostOrStolenCard => "70012", Self::SuspectedFraud => "70013", Self::ContactCardIssuer => "70014", Self::InvalidAmountValue => "70015", Self::Unknown(code) => code, } } pub fn is_success(&self) -> bool { matches!(self, Self::Success) } pub fn get_attempt_status(&self) -> common_enums::AttemptStatus { match self { // Success cases should be handled by get_payment_status() with settlestatus logic Self::Success => common_enums::AttemptStatus::Authorized, // Authentication and configuration errors Self::InvalidCredentials | Self::AuthenticationFailed | Self::InvalidSiteReference | Self::AccessDenied | Self::InvalidUsernameOrPassword | Self::AccountSuspended => common_enums::AttemptStatus::Failure, // Card-related and payment errors that should be treated as failures Self::InvalidCardNumber | Self::InvalidExpiryDate | Self::InvalidSecurityCode | Self::InvalidCardType | Self::CardExpired | Self::InsufficientFunds | Self::CardDeclined | Self::CardRestricted | Self::TransactionNotPermitted | Self::ExceedsWithdrawalLimit | Self::InvalidAmountValue => common_enums::AttemptStatus::Failure, // Processing states that should remain pending Self::Processing => common_enums::AttemptStatus::Pending, // Default fallback for unknown errors _ => common_enums::AttemptStatus::Pending, } } pub fn get_description(&self) -> &'static str { match self { Self::Success => "Success", Self::InvalidCredentials => "Invalid credentials", Self::AuthenticationFailed => "Authentication failed", Self::InvalidSiteReference => "Invalid site reference", Self::AccessDenied => "Access denied", Self::InvalidUsernameOrPassword => "Invalid username or password", Self::AccountSuspended => "Account suspended", Self::MissingRequiredField => "Missing required field", Self::InvalidFieldFormat => "Invalid field format", Self::InvalidFieldValue => "Invalid field value", Self::FieldTooLong => "Field value too long", Self::FieldTooShort => "Field value too short", Self::InvalidCurrency => "Invalid currency code", Self::InvalidAmount => "Invalid amount format", Self::GeneralProcessingError => "General processing error", Self::SystemError => "System error", Self::CommunicationError => "Communication error", Self::Timeout => "Request timeout", Self::Processing => "Transaction processing", Self::InvalidRequest => "Invalid request format", Self::NoSearchableFilter => "No searchable filter specified", Self::InvalidCardNumber => "Invalid card number", Self::InvalidExpiryDate => "Invalid expiry date", Self::InvalidSecurityCode => "Invalid security code", Self::InvalidCardType => "Invalid card type", Self::CardExpired => "Card expired", Self::InsufficientFunds => "Insufficient funds", Self::CardDeclined => "Card declined by issuer", Self::CardRestricted => "Card restricted", Self::InvalidMerchant => "Invalid merchant", Self::TransactionNotPermitted => "Transaction not permitted", Self::ExceedsWithdrawalLimit => "Exceeds withdrawal limit", Self::SecurityViolation => "Security violation", Self::LostOrStolenCard => "Lost or stolen card", Self::SuspectedFraud => "Suspected fraud", Self::ContactCardIssuer => "Contact card issuer", Self::InvalidAmountValue => "Invalid amount", Self::Unknown(_) => "Unknown error", } } } impl std::fmt::Display for TrustpaymentsErrorCode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_str()) } } pub struct TrustpaymentsRouterData<T> { pub amount: StringMinorUnit, pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for TrustpaymentsRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsPaymentsRequest { pub alias: String, pub version: String, pub request: Vec<TrustpaymentsPaymentRequestData>, } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsPaymentRequestData { pub accounttypedescription: String, pub baseamount: StringMinorUnit, pub billingfirstname: Option<String>, pub billinglastname: Option<String>, pub currencyiso3a: String, pub expirydate: Secret<String>, pub orderreference: String, pub pan: cards::CardNumber, pub requesttypedescriptions: Vec<String>, pub securitycode: Secret<String>, pub sitereference: String, pub credentialsonfile: String, pub settlestatus: String, } impl TryFrom<&TrustpaymentsRouterData<&PaymentsAuthorizeRouterData>> for TrustpaymentsPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &TrustpaymentsRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let auth = TrustpaymentsAuthType::try_from(&item.router_data.connector_auth_type)?; if matches!( item.router_data.auth_type, enums::AuthenticationType::ThreeDs ) { return Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("trustpayments"), ) .into()); } match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let card = req_card.clone(); let request_types = match item.router_data.request.capture_method { Some(common_enums::CaptureMethod::Automatic) | None => vec!["AUTH".to_string()], Some(common_enums::CaptureMethod::Manual) => vec!["AUTH".to_string()], Some(common_enums::CaptureMethod::ManualMultiple) | Some(common_enums::CaptureMethod::Scheduled) | Some(common_enums::CaptureMethod::SequentialAutomatic) => { return Err(errors::ConnectorError::NotSupported { message: "Capture method not supported by TrustPayments".to_string(), connector: "TrustPayments", } .into()); } }; Ok(Self { alias: auth.username.expose(), version: TRUSTPAYMENTS_API_VERSION.to_string(), request: vec![TrustpaymentsPaymentRequestData { accounttypedescription: "ECOM".to_string(), baseamount: item.amount.clone(), billingfirstname: item .router_data .get_optional_billing_first_name() .map(|name| name.expose()), billinglastname: item .router_data .get_optional_billing_last_name() .map(|name| name.expose()), currencyiso3a: item.router_data.request.currency.to_string(), expirydate: card .get_card_expiry_month_year_2_digit_with_delimiter("/".to_string())?, orderreference: item.router_data.connector_request_reference_id.clone(), pan: card.card_number.clone(), requesttypedescriptions: request_types, securitycode: card.card_cvc.clone(), sitereference: auth.site_reference.expose(), credentialsonfile: TrustpaymentsCredentialsOnFile::CardholderInitiatedTransaction .to_string(), settlestatus: match item.router_data.request.capture_method { Some(common_enums::CaptureMethod::Manual) => { TrustpaymentsSettleStatus::ManualCapture .as_str() .to_string() } Some(common_enums::CaptureMethod::Automatic) | None => { TrustpaymentsSettleStatus::PendingSettlement .as_str() .to_string() } _ => TrustpaymentsSettleStatus::PendingSettlement .as_str() .to_string(), }, }], }) } _ => Err(errors::ConnectorError::NotImplemented( "Payment method not supported".to_string(), ) .into()), } } } pub struct TrustpaymentsAuthType { pub(super) username: Secret<String>, pub(super) password: Secret<String>, pub(super) site_reference: Secret<String>, } impl TrustpaymentsAuthType { pub fn get_basic_auth_header(&self) -> String { use base64::Engine; let credentials = format!( "{}:{}", self.username.clone().expose(), self.password.clone().expose() ); let encoded = base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes()); format!("Basic {encoded}") } } impl TryFrom<&ConnectorAuthType> for TrustpaymentsAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { username: api_key.to_owned(), password: key1.to_owned(), site_reference: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct TrustpaymentsPaymentsResponse { #[serde(alias = "response")] pub responses: Vec<TrustpaymentsPaymentResponseData>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct TrustpaymentsPaymentResponseData { pub errorcode: TrustpaymentsErrorCode, pub errormessage: String, pub authcode: Option<String>, pub baseamount: Option<StringMinorUnit>, pub currencyiso3a: Option<String>, pub transactionreference: Option<String>, pub settlestatus: Option<TrustpaymentsSettleStatus>, pub requesttypedescription: String, pub securityresponsesecuritycode: Option<String>, } impl TrustpaymentsPaymentResponseData { pub fn get_payment_status(&self) -> common_enums::AttemptStatus { match self.errorcode { TrustpaymentsErrorCode::Success => { if self.authcode.is_some() { match &self.settlestatus { Some(TrustpaymentsSettleStatus::PendingSettlement) => { // settlestatus "0" = automatic capture, scheduled to settle common_enums::AttemptStatus::Charged } Some(TrustpaymentsSettleStatus::Settled) => { // settlestatus "1" or "100" = transaction has been settled common_enums::AttemptStatus::Charged } Some(TrustpaymentsSettleStatus::ManualCapture) => { // settlestatus "2" = suspended, manual capture needed common_enums::AttemptStatus::Authorized } Some(TrustpaymentsSettleStatus::Voided) => { // settlestatus "3" = transaction has been cancelled common_enums::AttemptStatus::Voided } None => common_enums::AttemptStatus::Authorized, } } else { common_enums::AttemptStatus::Failure } } _ => self.errorcode.get_attempt_status(), } } pub fn get_payment_status_for_sync(&self) -> common_enums::AttemptStatus { match self.errorcode { TrustpaymentsErrorCode::Success => { if self.requesttypedescription == "TRANSACTIONQUERY" && self.authcode.is_none() && self.settlestatus.is_none() && self.transactionreference.is_none() { common_enums::AttemptStatus::Authorized } else if self.authcode.is_some() { match &self.settlestatus { Some(TrustpaymentsSettleStatus::PendingSettlement) => { common_enums::AttemptStatus::Authorized } Some(TrustpaymentsSettleStatus::Settled) => { common_enums::AttemptStatus::Charged } Some(TrustpaymentsSettleStatus::ManualCapture) => { common_enums::AttemptStatus::Authorized } Some(TrustpaymentsSettleStatus::Voided) => { common_enums::AttemptStatus::Voided } None => common_enums::AttemptStatus::Authorized, } } else { common_enums::AttemptStatus::Pending } } _ => self.errorcode.get_attempt_status(), } } pub fn get_error_message(&self) -> String { if self.errorcode.is_success() { "Success".to_string() } else { format!("Error {}: {}", self.errorcode, self.errormessage) } } pub fn get_error_reason(&self) -> Option<String> { if !self.errorcode.is_success() { Some(self.errorcode.get_description().to_string()) } else { None } } } impl TryFrom< ResponseRouterData< hyperswitch_domain_models::router_flow_types::payments::Authorize, TrustpaymentsPaymentsResponse, hyperswitch_domain_models::router_request_types::PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData< hyperswitch_domain_models::router_flow_types::payments::Authorize, hyperswitch_domain_models::router_request_types::PaymentsAuthorizeData, PaymentsResponseData, > { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< hyperswitch_domain_models::router_flow_types::payments::Authorize, TrustpaymentsPaymentsResponse, hyperswitch_domain_models::router_request_types::PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_data = item .response .responses .first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; let status = response_data.get_payment_status(); let transaction_id = response_data .transactionreference .clone() .unwrap_or_else(|| "unknown".to_string()); if !response_data.errorcode.is_success() { let _error_response = TrustpaymentsErrorResponse::from(response_data.clone()); return Ok(Self { status, response: Err(hyperswitch_domain_models::router_data::ErrorResponse { code: response_data.errorcode.to_string(), message: response_data.errormessage.clone(), reason: response_data.get_error_reason(), status_code: item.http_code, attempt_status: Some(status), connector_transaction_id: response_data.transactionreference.clone(), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }); } Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(transaction_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl TryFrom< ResponseRouterData< hyperswitch_domain_models::router_flow_types::payments::PSync, TrustpaymentsPaymentsResponse, hyperswitch_domain_models::router_request_types::PaymentsSyncData, PaymentsResponseData, >, > for RouterData< hyperswitch_domain_models::router_flow_types::payments::PSync, hyperswitch_domain_models::router_request_types::PaymentsSyncData, PaymentsResponseData, > { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< hyperswitch_domain_models::router_flow_types::payments::PSync, TrustpaymentsPaymentsResponse, hyperswitch_domain_models::router_request_types::PaymentsSyncData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_data = item .response .responses .first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; let status = response_data.get_payment_status_for_sync(); let transaction_id = item .data .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; if !response_data.errorcode.is_success() { return Ok(Self { status, response: Err(hyperswitch_domain_models::router_data::ErrorResponse { code: response_data.errorcode.to_string(), message: response_data.errormessage.clone(), reason: response_data.get_error_reason(), status_code: item.http_code, attempt_status: Some(status), connector_transaction_id: Some(transaction_id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }); } Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(transaction_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl TryFrom< ResponseRouterData< hyperswitch_domain_models::router_flow_types::payments::Capture, TrustpaymentsPaymentsResponse, hyperswitch_domain_models::router_request_types::PaymentsCaptureData, PaymentsResponseData, >, > for RouterData< hyperswitch_domain_models::router_flow_types::payments::Capture, hyperswitch_domain_models::router_request_types::PaymentsCaptureData, PaymentsResponseData, > { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< hyperswitch_domain_models::router_flow_types::payments::Capture, TrustpaymentsPaymentsResponse, hyperswitch_domain_models::router_request_types::PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_data = item .response .responses .first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; let transaction_id = item.data.request.connector_transaction_id.clone(); let status = if response_data.errorcode.is_success() { common_enums::AttemptStatus::Charged } else { response_data.get_payment_status() }; if !response_data.errorcode.is_success() { return Ok(Self { status, response: Err(hyperswitch_domain_models::router_data::ErrorResponse { code: response_data.errorcode.to_string(), message: response_data.errormessage.clone(), reason: response_data.get_error_reason(), status_code: item.http_code, attempt_status: Some(status), connector_transaction_id: Some(transaction_id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }); } Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(transaction_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl TryFrom< ResponseRouterData< hyperswitch_domain_models::router_flow_types::payments::Void, TrustpaymentsPaymentsResponse, hyperswitch_domain_models::router_request_types::PaymentsCancelData, PaymentsResponseData, >, > for RouterData< hyperswitch_domain_models::router_flow_types::payments::Void, hyperswitch_domain_models::router_request_types::PaymentsCancelData, PaymentsResponseData, > { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< hyperswitch_domain_models::router_flow_types::payments::Void, TrustpaymentsPaymentsResponse, hyperswitch_domain_models::router_request_types::PaymentsCancelData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_data = item .response .responses .first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; let transaction_id = item.data.request.connector_transaction_id.clone(); let status = if response_data.errorcode.is_success() { common_enums::AttemptStatus::Voided } else { response_data.get_payment_status() }; if !response_data.errorcode.is_success() { return Ok(Self { status, response: Err(hyperswitch_domain_models::router_data::ErrorResponse { code: response_data.errorcode.to_string(), message: response_data.errormessage.clone(), reason: response_data.get_error_reason(), status_code: item.http_code, attempt_status: Some(status), connector_transaction_id: Some(transaction_id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }); } Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(transaction_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsCaptureRequest { pub alias: String, pub version: String, pub request: Vec<TrustpaymentsCaptureRequestData>, } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsCaptureRequestData { pub requesttypedescriptions: Vec<String>, pub filter: TrustpaymentsFilter, pub updates: TrustpaymentsCaptureUpdates, } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsCaptureUpdates { pub settlestatus: TrustpaymentsSettleStatus, } impl TryFrom<&TrustpaymentsRouterData<&PaymentsCaptureRouterData>> for TrustpaymentsCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &TrustpaymentsRouterData<&PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { let auth = TrustpaymentsAuthType::try_from(&item.router_data.connector_auth_type)?; let transaction_reference = item.router_data.request.connector_transaction_id.clone(); Ok(Self { alias: auth.username.expose(), version: TRUSTPAYMENTS_API_VERSION.to_string(), request: vec![TrustpaymentsCaptureRequestData { requesttypedescriptions: vec!["TRANSACTIONUPDATE".to_string()], filter: TrustpaymentsFilter { sitereference: vec![TrustpaymentsFilterValue { value: auth.site_reference.expose(), }], transactionreference: vec![TrustpaymentsFilterValue { value: transaction_reference, }], }, updates: TrustpaymentsCaptureUpdates { settlestatus: TrustpaymentsSettleStatus::PendingSettlement, }, }], }) } } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsVoidRequest { pub alias: String, pub version: String, pub request: Vec<TrustpaymentsVoidRequestData>, } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsVoidRequestData { pub requesttypedescriptions: Vec<String>, pub filter: TrustpaymentsFilter, pub updates: TrustpaymentsVoidUpdates, } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsVoidUpdates { pub settlestatus: TrustpaymentsSettleStatus, } impl TryFrom<&PaymentsCancelRouterData> for TrustpaymentsVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth = TrustpaymentsAuthType::try_from(&item.connector_auth_type)?; let transaction_reference = item.request.connector_transaction_id.clone(); Ok(Self { alias: auth.username.expose(), version: TRUSTPAYMENTS_API_VERSION.to_string(), request: vec![TrustpaymentsVoidRequestData { requesttypedescriptions: vec!["TRANSACTIONUPDATE".to_string()], filter: TrustpaymentsFilter { sitereference: vec![TrustpaymentsFilterValue { value: auth.site_reference.expose(), }], transactionreference: vec![TrustpaymentsFilterValue { value: transaction_reference, }], }, updates: TrustpaymentsVoidUpdates { settlestatus: TrustpaymentsSettleStatus::Voided, }, }], }) } } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsRefundRequest { pub alias: String, pub version: String, pub request: Vec<TrustpaymentsRefundRequestData>, } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsRefundRequestData { pub requesttypedescriptions: Vec<String>, pub sitereference: String, pub parenttransactionreference: String, pub baseamount: StringMinorUnit, pub currencyiso3a: String, } impl<F> TryFrom<&TrustpaymentsRouterData<&RefundsRouterData<F>>> for TrustpaymentsRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &TrustpaymentsRouterData<&RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { let auth = TrustpaymentsAuthType::try_from(&item.router_data.connector_auth_type)?; let parent_transaction_reference = item.router_data.request.connector_transaction_id.clone(); Ok(Self { alias: auth.username.expose(), version: TRUSTPAYMENTS_API_VERSION.to_string(), request: vec![TrustpaymentsRefundRequestData { requesttypedescriptions: vec!["REFUND".to_string()], sitereference: auth.site_reference.expose(), parenttransactionreference: parent_transaction_reference, baseamount: item.amount.clone(), currencyiso3a: item.router_data.request.currency.to_string(), }], }) } } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsSyncRequest { pub alias: String, pub version: String, pub request: Vec<TrustpaymentsSyncRequestData>, } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsSyncRequestData { pub requesttypedescriptions: Vec<String>, pub filter: TrustpaymentsFilter, } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsFilter { pub sitereference: Vec<TrustpaymentsFilterValue>, pub transactionreference: Vec<TrustpaymentsFilterValue>, } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsFilterValue { pub value: String, } impl TryFrom<&PaymentsSyncRouterData> for TrustpaymentsSyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> { let auth = TrustpaymentsAuthType::try_from(&item.connector_auth_type)?; let transaction_reference = item .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; Ok(Self { alias: auth.username.expose(), version: TRUSTPAYMENTS_API_VERSION.to_string(), request: vec![TrustpaymentsSyncRequestData { requesttypedescriptions: vec!["TRANSACTIONQUERY".to_string()], filter: TrustpaymentsFilter { sitereference: vec![TrustpaymentsFilterValue { value: auth.site_reference.expose(), }], transactionreference: vec![TrustpaymentsFilterValue { value: transaction_reference, }], }, }], }) } } pub type TrustpaymentsRefundSyncRequest = TrustpaymentsSyncRequest; impl TryFrom<&RefundSyncRouterData> for TrustpaymentsRefundSyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> { let auth = TrustpaymentsAuthType::try_from(&item.connector_auth_type)?; let refund_transaction_reference = item .request .get_connector_refund_id() .change_context(errors::ConnectorError::MissingConnectorRefundID)?; Ok(Self { alias: auth.username.expose(), version: TRUSTPAYMENTS_API_VERSION.to_string(), request: vec![TrustpaymentsSyncRequestData { requesttypedescriptions: vec!["TRANSACTIONQUERY".to_string()], filter: TrustpaymentsFilter { sitereference: vec![TrustpaymentsFilterValue { value: auth.site_reference.expose(), }], transactionreference: vec![TrustpaymentsFilterValue { value: refund_transaction_reference, }], }, }], }) } } pub type RefundResponse = TrustpaymentsPaymentsResponse; impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let response_data = item .response .responses .first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; let refund_id = response_data .transactionreference .clone() .unwrap_or_else(|| "unknown".to_string()); let refund_status = response_data.get_refund_status(); Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: refund_id, refund_status, }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let response_data = item .response .responses .first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; let refund_id = response_data .transactionreference .clone() .unwrap_or_else(|| "unknown".to_string()); let refund_status = response_data.get_refund_status(); Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: refund_id, refund_status, }), ..item.data }) } } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsTokenizationRequest { pub alias: String, pub version: String, pub request: Vec<TrustpaymentsTokenizationRequestData>, } #[derive(Debug, Serialize, PartialEq)] pub struct TrustpaymentsTokenizationRequestData { pub accounttypedescription: String, pub requesttypedescriptions: Vec<String>, pub sitereference: String, pub pan: cards::CardNumber, pub expirydate: Secret<String>, pub securitycode: Secret<String>, pub credentialsonfile: String, } impl TryFrom< &RouterData< hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken, hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData, PaymentsResponseData, >, > for TrustpaymentsTokenizationRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &RouterData< hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken, hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let auth = TrustpaymentsAuthType::try_from(&item.connector_auth_type)?; match &item.request.payment_method_data { PaymentMethodData::Card(card_data) => Ok(Self { alias: auth.username.expose(), version: TRUSTPAYMENTS_API_VERSION.to_string(), request: vec![TrustpaymentsTokenizationRequestData { accounttypedescription: "ECOM".to_string(), requesttypedescriptions: vec!["ACCOUNTCHECK".to_string()], sitereference: auth.site_reference.expose(), pan: card_data.card_number.clone(), expirydate: card_data .get_card_expiry_month_year_2_digit_with_delimiter("/".to_string())?, securitycode: card_data.card_cvc.clone(), credentialsonfile: TrustpaymentsCredentialsOnFile::CardholderInitiatedTransaction.to_string(), }], }), _ => Err(errors::ConnectorError::NotImplemented( "Payment method not supported for tokenization".to_string(), ) .into()), } } } pub type TrustpaymentsTokenizationResponse = TrustpaymentsPaymentsResponse; impl TryFrom< ResponseRouterData< hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken, TrustpaymentsTokenizationResponse, hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData, PaymentsResponseData, >, > for RouterData< hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken, hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData, PaymentsResponseData, > { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< hyperswitch_domain_models::router_flow_types::payments::PaymentMethodToken, TrustpaymentsTokenizationResponse, hyperswitch_domain_models::router_request_types::PaymentMethodTokenizationData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_data = item .response .responses .first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; let status = response_data.get_payment_status(); let token = response_data .transactionreference .clone() .unwrap_or_else(|| "unknown".to_string()); Ok(Self { status, response: Ok(PaymentsResponseData::TokenizationResponse { token }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct TrustpaymentsErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, pub network_advice_code: Option<String>, pub network_decline_code: Option<String>, pub network_error_message: Option<String>, } impl TrustpaymentsErrorResponse { pub fn get_connector_error_type(&self) -> errors::ConnectorError { let error_code: TrustpaymentsErrorCode = serde_json::from_str(&format!("\"{}\"", self.code)) .unwrap_or(TrustpaymentsErrorCode::Unknown(self.code.clone())); match error_code { TrustpaymentsErrorCode::InvalidCredentials | TrustpaymentsErrorCode::AuthenticationFailed | TrustpaymentsErrorCode::InvalidSiteReference | TrustpaymentsErrorCode::AccessDenied | TrustpaymentsErrorCode::InvalidUsernameOrPassword | TrustpaymentsErrorCode::AccountSuspended => { errors::ConnectorError::InvalidConnectorConfig { config: "authentication", } } TrustpaymentsErrorCode::InvalidCardNumber | TrustpaymentsErrorCode::InvalidExpiryDate | TrustpaymentsErrorCode::InvalidSecurityCode | TrustpaymentsErrorCode::InvalidCardType | TrustpaymentsErrorCode::CardExpired | TrustpaymentsErrorCode::InvalidAmountValue => { errors::ConnectorError::InvalidDataFormat { field_name: "payment_method_data", } } TrustpaymentsErrorCode::InsufficientFunds | TrustpaymentsErrorCode::CardDeclined | TrustpaymentsErrorCode::CardRestricted | TrustpaymentsErrorCode::InvalidMerchant | TrustpaymentsErrorCode::TransactionNotPermitted | TrustpaymentsErrorCode::ExceedsWithdrawalLimit | TrustpaymentsErrorCode::SecurityViolation | TrustpaymentsErrorCode::LostOrStolenCard | TrustpaymentsErrorCode::SuspectedFraud | TrustpaymentsErrorCode::ContactCardIssuer => { errors::ConnectorError::FailedAtConnector { message: self.message.clone(), code: self.code.clone(), } } TrustpaymentsErrorCode::GeneralProcessingError | TrustpaymentsErrorCode::SystemError | TrustpaymentsErrorCode::CommunicationError | TrustpaymentsErrorCode::Timeout | TrustpaymentsErrorCode::InvalidRequest => { errors::ConnectorError::ProcessingStepFailed(None) } TrustpaymentsErrorCode::Processing => errors::ConnectorError::ProcessingStepFailed( Some(bytes::Bytes::from("Transaction is being processed")), ), TrustpaymentsErrorCode::MissingRequiredField | TrustpaymentsErrorCode::InvalidFieldFormat | TrustpaymentsErrorCode::InvalidFieldValue | TrustpaymentsErrorCode::FieldTooLong | TrustpaymentsErrorCode::FieldTooShort | TrustpaymentsErrorCode::InvalidCurrency | TrustpaymentsErrorCode::InvalidAmount | TrustpaymentsErrorCode::NoSearchableFilter => { errors::ConnectorError::MissingRequiredField { field_name: "request_data", } } TrustpaymentsErrorCode::Success => errors::ConnectorError::ProcessingStepFailed(Some( bytes::Bytes::from("Unexpected success code in error response"), )), TrustpaymentsErrorCode::Unknown(_) => errors::ConnectorError::ProcessingStepFailed( Some(bytes::Bytes::from(self.message.clone())), ), } } } impl From<TrustpaymentsPaymentResponseData> for TrustpaymentsErrorResponse { fn from(response: TrustpaymentsPaymentResponseData) -> Self { let error_reason = response.get_error_reason(); Self { status_code: if response.errorcode.is_success() { 200 } else { 400 }, code: response.errorcode.to_string(), message: response.errormessage, reason: error_reason, network_advice_code: None, network_decline_code: None, network_error_message: None, } } } impl TrustpaymentsPaymentResponseData { pub fn get_refund_status(&self) -> enums::RefundStatus { match self.errorcode { TrustpaymentsErrorCode::Success => match &self.settlestatus { Some(TrustpaymentsSettleStatus::Settled) => enums::RefundStatus::Success, Some(TrustpaymentsSettleStatus::PendingSettlement) => enums::RefundStatus::Pending, Some(TrustpaymentsSettleStatus::ManualCapture) => enums::RefundStatus::Failure, Some(TrustpaymentsSettleStatus::Voided) => enums::RefundStatus::Failure, None => enums::RefundStatus::Success, }, TrustpaymentsErrorCode::Processing => enums::RefundStatus::Pending, _ => enums::RefundStatus::Failure, } } }
crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
hyperswitch_connectors::src::connectors::trustpayments::transformers
10,214
true
// File: crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs // Module: hyperswitch_connectors::src::connectors::nuvei::transformers use common_enums::{enums, CaptureMethod, FutureUsage, GooglePayCardFundingSource, PaymentChannel}; use common_types::{ payments::{ ApplePayPaymentData, ApplePayPredecryptData, GPayPredecryptData, GpayTokenizationData, }, primitive_wrappers, }; use common_utils::{ crypto::{self, GenerateDigest}, date_time, ext_traits::Encode, fp_utils, id_type::CustomerId, pii::{self, Email, IpAddress}, request::Method, types::{FloatMajorUnit, MinorUnit, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ address::{Address, AddressDetails}, payment_method_data::{ self, ApplePayWalletData, BankRedirectData, CardDetailsForNetworkTransactionId, GooglePayWalletData, PayLaterData, PaymentMethodData, WalletData, }, router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, ErrorResponse, L2L3Data, PaymentMethodToken, RouterData, }, router_flow_types::{ refunds::{Execute, RSync}, Authorize, Capture, CompleteAuthorize, PSync, PostCaptureVoid, SetupMandate, Void, }, router_request_types::{ authentication::MessageExtensionAttribute, AuthenticationData, BrowserInformation, PaymentsAuthorizeData, PaymentsPreProcessingData, ResponseId, SetupMandateRequestData, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types, }; #[cfg(feature = "payouts")] use hyperswitch_domain_models::{ router_flow_types::payouts::PoFulfill, router_response_types::PayoutsResponseData, }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors::{self}, }; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; #[cfg(feature = "payouts")] use crate::{types::PayoutsResponseRouterData, utils::PayoutsData as _}; use crate::{ types::{ PaymentsPreprocessingResponseRouterData, RefundsResponseRouterData, ResponseRouterData, }, utils::{ self, convert_amount, missing_field_err, AddressData, AddressDetailsData, BrowserInformationData, CardData, ForeignTryFrom, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, PaymentsPreProcessingRequestData, PaymentsSetupMandateRequestData, RouterData as _, }, }; pub static NUVEI_AMOUNT_CONVERTOR: &StringMajorUnitForConnector = &StringMajorUnitForConnector; fn to_boolean(string: String) -> bool { let str = string.as_str(); match str { "true" => true, "false" => false, "yes" => true, "no" => false, _ => false, } } // The dimensions of the challenge window for full screen. const CHALLENGE_WINDOW_SIZE: &str = "05"; // The challenge preference for the challenge flow. const CHALLENGE_PREFERENCE: &str = "01"; trait NuveiAuthorizePreprocessingCommon { fn get_browser_info(&self) -> Option<BrowserInformation>; fn get_related_transaction_id(&self) -> Option<String>; fn get_complete_authorize_url(&self) -> Option<String>; fn get_is_moto(&self) -> Option<bool>; fn get_ntid(&self) -> Option<String>; fn get_connector_mandate_id(&self) -> Option<String>; fn get_return_url_required( &self, ) -> Result<String, error_stack::Report<errors::ConnectorError>>; fn get_capture_method(&self) -> Option<CaptureMethod>; fn get_minor_amount_required( &self, ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>>; fn get_customer_id_optional(&self) -> Option<CustomerId>; fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>>; fn get_currency_required( &self, ) -> Result<enums::Currency, error_stack::Report<errors::ConnectorError>>; fn get_payment_method_data_required( &self, ) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>>; fn get_is_partial_approval(&self) -> Option<PartialApprovalFlag>; fn is_customer_initiated_mandate_payment(&self) -> bool; fn get_auth_data( &self, ) -> Result<Option<AuthenticationData>, error_stack::Report<errors::ConnectorError>> { Ok(None) } fn get_is_stored_credential(&self) -> Option<StoredCredentialMode>; } impl NuveiAuthorizePreprocessingCommon for SetupMandateRequestData { fn get_browser_info(&self) -> Option<BrowserInformation> { self.browser_info.clone() } fn get_related_transaction_id(&self) -> Option<String> { self.related_transaction_id.clone() } fn get_is_moto(&self) -> Option<bool> { match self.payment_channel { Some(PaymentChannel::MailOrder) | Some(PaymentChannel::TelephoneOrder) => Some(true), _ => None, } } fn get_customer_id_optional(&self) -> Option<CustomerId> { self.customer_id.clone() } fn get_complete_authorize_url(&self) -> Option<String> { self.complete_authorize_url.clone() } fn get_connector_mandate_id(&self) -> Option<String> { self.mandate_id.as_ref().and_then(|mandate_ids| { mandate_ids.mandate_reference_id.as_ref().and_then( |mandate_ref_id| match mandate_ref_id { api_models::payments::MandateReferenceId::ConnectorMandateId(id) => { id.get_connector_mandate_id() } _ => None, }, ) }) } fn get_return_url_required( &self, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { self.get_router_return_url() } fn get_capture_method(&self) -> Option<CaptureMethod> { self.capture_method } fn get_currency_required( &self, ) -> Result<enums::Currency, error_stack::Report<errors::ConnectorError>> { Ok(self.currency) } fn get_payment_method_data_required( &self, ) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> { Ok(self.payment_method_data.clone()) } fn get_minor_amount_required( &self, ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> { self.minor_amount .ok_or_else(missing_field_err("minor_amount")) } fn get_is_partial_approval(&self) -> Option<PartialApprovalFlag> { self.enable_partial_authorization .map(PartialApprovalFlag::from) } fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>> { self.email.clone().ok_or_else(missing_field_err("email")) } 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_ntid(&self) -> Option<String> { None } fn get_is_stored_credential(&self) -> Option<StoredCredentialMode> { StoredCredentialMode::get_optional_stored_credential(self.is_stored_credential) } } impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { fn get_browser_info(&self) -> Option<BrowserInformation> { self.browser_info.clone() } fn get_ntid(&self) -> Option<String> { self.get_optional_network_transaction_id() } fn get_related_transaction_id(&self) -> Option<String> { self.related_transaction_id.clone() } fn get_is_moto(&self) -> Option<bool> { match self.payment_channel { Some(PaymentChannel::MailOrder) | Some(PaymentChannel::TelephoneOrder) => Some(true), _ => None, } } fn get_auth_data( &self, ) -> Result<Option<AuthenticationData>, error_stack::Report<errors::ConnectorError>> { Ok(self.authentication_data.clone()) } fn get_customer_id_optional(&self) -> Option<CustomerId> { self.customer_id.clone() } fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id().clone() } fn get_return_url_required( &self, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { self.get_router_return_url() } fn get_capture_method(&self) -> Option<CaptureMethod> { self.capture_method } fn get_complete_authorize_url(&self) -> Option<String> { self.complete_authorize_url.clone() } fn get_minor_amount_required( &self, ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> { Ok(self.minor_amount) } fn get_currency_required( &self, ) -> Result<enums::Currency, error_stack::Report<errors::ConnectorError>> { Ok(self.currency) } fn get_payment_method_data_required( &self, ) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> { Ok(self.payment_method_data.clone()) } fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>> { self.get_email() } 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_is_partial_approval(&self) -> Option<PartialApprovalFlag> { self.enable_partial_authorization .map(PartialApprovalFlag::from) } fn get_is_stored_credential(&self) -> Option<StoredCredentialMode> { StoredCredentialMode::get_optional_stored_credential(self.is_stored_credential) } } impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { fn get_browser_info(&self) -> Option<BrowserInformation> { self.browser_info.clone() } fn get_related_transaction_id(&self) -> Option<String> { self.related_transaction_id.clone() } fn get_is_moto(&self) -> Option<bool> { None } fn get_customer_id_optional(&self) -> Option<CustomerId> { None } fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>> { self.get_email() } 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_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id() } fn get_return_url_required( &self, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { self.get_router_return_url() } fn get_capture_method(&self) -> Option<CaptureMethod> { self.capture_method } fn get_complete_authorize_url(&self) -> Option<String> { self.complete_authorize_url.clone() } fn get_minor_amount_required( &self, ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> { self.get_minor_amount() } fn get_currency_required( &self, ) -> Result<enums::Currency, error_stack::Report<errors::ConnectorError>> { self.get_currency() } fn get_payment_method_data_required( &self, ) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> { self.payment_method_data.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "payment_method_data", } .into(), ) } fn get_is_partial_approval(&self) -> Option<PartialApprovalFlag> { None } fn get_ntid(&self) -> Option<String> { None } fn get_is_stored_credential(&self) -> Option<StoredCredentialMode> { StoredCredentialMode::get_optional_stored_credential(self.is_stored_credential) } } #[derive(Debug, Serialize, Default, Deserialize)] pub struct NuveiMeta { pub session_token: Secret<String>, } #[derive(Debug, Serialize, Default, Deserialize)] pub struct NuveiMandateMeta { pub frequency: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiSessionRequest { pub merchant_id: Secret<String>, pub merchant_site_id: Secret<String>, pub client_request_id: String, pub time_stamp: date_time::DateTime<date_time::YYYYMMDDHHmmss>, pub checksum: Secret<String>, } #[derive(Debug, Serialize, Default, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiSessionResponse { pub session_token: Secret<String>, pub internal_request_id: i64, pub status: String, pub err_code: i64, pub reason: String, pub merchant_id: Secret<String>, pub merchant_site_id: Secret<String>, pub version: String, pub client_request_id: String, } #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct NuveiAmountDetails { pub total_tax: Option<StringMajorUnit>, pub total_shipping: Option<StringMajorUnit>, pub total_handling: Option<StringMajorUnit>, pub total_discount: Option<StringMajorUnit>, } #[derive(Debug, Serialize, Deserialize, Clone, Default)] #[serde(rename_all = "snake_case")] pub enum NuveiItemType { #[default] Physical, Discount, #[serde(rename = "Shipping_fee")] ShippingFee, Digital, #[serde(rename = "Gift_card")] GiftCard, #[serde(rename = "Store_credit")] StoreCredit, Surcharge, #[serde(rename = "Sales_tax")] SalesTax, } impl From<Option<enums::ProductType>> for NuveiItemType { fn from(value: Option<enums::ProductType>) -> Self { match value { Some(enums::ProductType::Digital) => Self::Digital, Some(enums::ProductType::Physical) => Self::Physical, Some(enums::ProductType::Ride) | Some(enums::ProductType::Travel) | Some(enums::ProductType::Accommodation) => Self::ShippingFee, _ => Self::Physical, } } } #[serde_with::skip_serializing_none] #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct NuveiItem { pub name: String, #[serde(rename = "type")] pub item_type: NuveiItemType, pub price: StringMajorUnit, pub quantity: String, pub group_id: Option<String>, pub discount: Option<StringMajorUnit>, pub discount_rate: Option<String>, pub shipping: Option<StringMajorUnit>, pub shipping_tax: Option<StringMajorUnit>, pub shipping_tax_rate: Option<String>, pub tax: Option<StringMajorUnit>, pub tax_rate: Option<String>, pub image_url: Option<String>, pub product_url: Option<String>, } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub enum IsRebilling { #[serde(rename = "1")] True, #[serde(rename = "0")] False, } #[serde_with::skip_serializing_none] #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct NuveiPaymentsRequest { pub time_stamp: String, pub session_token: Secret<String>, pub merchant_id: Secret<String>, pub merchant_site_id: Secret<String>, pub client_request_id: Secret<String>, pub amount: StringMajorUnit, pub currency: enums::Currency, /// This ID uniquely identifies your consumer/user in your system. pub user_token_id: Option<CustomerId>, //unique transaction id pub client_unique_id: String, pub transaction_type: TransactionType, pub is_rebilling: Option<IsRebilling>, pub payment_option: PaymentOption, pub is_moto: Option<bool>, pub device_details: DeviceDetails, pub checksum: Secret<String>, pub billing_address: Option<BillingAddress>, pub shipping_address: Option<ShippingAddress>, pub related_transaction_id: Option<String>, pub url_details: Option<UrlDetails>, pub amount_details: Option<NuveiAmountDetails>, pub items: Option<Vec<NuveiItem>>, pub is_partial_approval: Option<PartialApprovalFlag>, pub external_scheme_details: Option<ExternalSchemeDetails>, } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum PartialApprovalFlag { #[serde(rename = "1")] Enabled, #[serde(rename = "0")] Disabled, } impl From<primitive_wrappers::EnablePartialAuthorizationBool> for PartialApprovalFlag { fn from(value: primitive_wrappers::EnablePartialAuthorizationBool) -> Self { if value.is_true() { Self::Enabled } else { Self::Disabled } } } #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct UrlDetails { pub success_url: String, pub failure_url: String, pub pending_url: String, } #[derive(Debug, Serialize, Default)] pub struct NuveiInitPaymentRequest { pub session_token: Secret<String>, pub merchant_id: Secret<String>, pub merchant_site_id: Secret<String>, pub client_request_id: String, pub amount: StringMajorUnit, pub currency: String, pub payment_option: PaymentOption, pub checksum: Secret<String>, } /// Handles payment request for capture, void and refund flows #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct NuveiPaymentFlowRequest { pub time_stamp: String, pub merchant_id: Secret<String>, pub merchant_site_id: Secret<String>, pub client_request_id: String, pub amount: StringMajorUnit, pub currency: enums::Currency, pub related_transaction_id: Option<String>, pub checksum: Secret<String>, } #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct NuveiPaymentSyncRequest { pub merchant_id: Secret<String>, pub merchant_site_id: Secret<String>, pub time_stamp: String, pub checksum: Secret<String>, pub transaction_id: String, } #[derive(Debug, Default, Serialize, Deserialize)] pub enum TransactionType { Auth, #[default] Sale, } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentOption { pub card: Option<Card>, pub redirect_url: Option<Url>, pub user_payment_option_id: Option<String>, pub alternative_payment_method: Option<AlternativePaymentMethod>, pub billing_address: Option<BillingAddress>, pub shipping_address: Option<BillingAddress>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum NuveiBIC { #[serde(rename = "ABNANL2A")] Abnamro, #[serde(rename = "ASNBNL21")] ASNBank, #[serde(rename = "BUNQNL2A")] Bunq, #[serde(rename = "INGBNL2A")] Ing, #[serde(rename = "KNABNL2H")] Knab, #[serde(rename = "RABONL2U")] Rabobank, #[serde(rename = "RBRBNL21")] RegioBank, #[serde(rename = "SNSBNL2A")] SNSBank, #[serde(rename = "TRIONL2U")] TriodosBank, #[serde(rename = "FVLBNL22")] VanLanschotBankiers, #[serde(rename = "MOYONL21")] Moneyou, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum NuveiCardType { Visa, MasterCard, AmericanExpress, Discover, DinersClub, Interac, JCB, UnionPay, CartesBancaires, } impl TryFrom<common_enums::CardNetwork> for NuveiCardType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(card_network: common_enums::CardNetwork) -> Result<Self, Self::Error> { match card_network { common_enums::CardNetwork::Visa => Ok(Self::Visa), common_enums::CardNetwork::Mastercard => Ok(Self::MasterCard), common_enums::CardNetwork::AmericanExpress => Ok(Self::AmericanExpress), common_enums::CardNetwork::Discover => Ok(Self::Discover), common_enums::CardNetwork::DinersClub => Ok(Self::DinersClub), common_enums::CardNetwork::JCB => Ok(Self::JCB), common_enums::CardNetwork::UnionPay => Ok(Self::UnionPay), common_enums::CardNetwork::CartesBancaires => Ok(Self::CartesBancaires), common_enums::CardNetwork::Interac => Ok(Self::Interac), _ => Err(errors::ConnectorError::NotSupported { message: "Card network".to_string(), connector: "nuvei", } .into()), } } } impl TryFrom<&utils::CardIssuer> for NuveiCardType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(card_issuer: &utils::CardIssuer) -> Result<Self, Self::Error> { match card_issuer { utils::CardIssuer::Visa => Ok(Self::Visa), utils::CardIssuer::Master => Ok(Self::MasterCard), utils::CardIssuer::AmericanExpress => Ok(Self::AmericanExpress), utils::CardIssuer::Discover => Ok(Self::Discover), utils::CardIssuer::DinersClub => Ok(Self::DinersClub), utils::CardIssuer::JCB => Ok(Self::JCB), utils::CardIssuer::CartesBancaires => Ok(Self::CartesBancaires), &utils::CardIssuer::UnionPay => Ok(Self::UnionPay), _ => Err(errors::ConnectorError::NotSupported { message: "Card network".to_string(), connector: "nuvei", } .into()), } } } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AlternativePaymentMethod { pub payment_method: AlternativePaymentMethodType, #[serde(rename = "BIC")] pub bank_id: Option<NuveiBIC>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AlternativePaymentMethodType { #[default] #[serde(rename = "apmgw_expresscheckout")] Expresscheckout, #[serde(rename = "apmgw_Giropay")] Giropay, #[serde(rename = "apmgw_Sofort")] Sofort, #[serde(rename = "apmgw_iDeal")] Ideal, #[serde(rename = "apmgw_EPS")] Eps, #[serde(rename = "apmgw_Afterpay")] AfterPay, #[serde(rename = "apmgw_Klarna")] Klarna, } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BillingAddress { pub email: Email, pub first_name: Option<Secret<String>>, pub last_name: Option<Secret<String>>, pub country: api_models::enums::CountryAlpha2, pub phone: Option<Secret<String>>, pub city: Option<Secret<String>>, pub address: Option<Secret<String>>, pub street_number: Option<Secret<String>>, pub zip: Option<Secret<String>>, pub state: Option<Secret<String>>, pub cell: Option<Secret<String>>, pub address_match: Option<Secret<String>>, pub address_line2: Option<Secret<String>>, pub address_line3: Option<Secret<String>>, pub home_phone: Option<Secret<String>>, pub work_phone: Option<Secret<String>>, } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ShippingAddress { pub salutation: Option<Secret<String>>, pub first_name: Option<Secret<String>>, pub last_name: Option<Secret<String>>, pub address: Option<Secret<String>>, pub cell: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub zip: Option<Secret<String>>, pub city: Option<Secret<String>>, pub country: api_models::enums::CountryAlpha2, pub state: Option<Secret<String>>, pub email: Email, pub county: Option<Secret<String>>, pub address_line2: Option<Secret<String>>, pub address_line3: Option<Secret<String>>, pub street_number: Option<Secret<String>>, pub company_name: Option<Secret<String>>, pub care_of: Option<Secret<String>>, } impl From<&Address> for BillingAddress { fn from(address: &Address) -> Self { let address_details = address.address.as_ref(); Self { email: address.email.clone().unwrap_or_default(), first_name: address.get_optional_first_name(), last_name: address_details.and_then(|address| address.get_optional_last_name()), country: address_details .and_then(|address| address.get_optional_country()) .unwrap_or_default(), phone: address .phone .as_ref() .and_then(|phone| phone.number.clone()), city: address_details .and_then(|address| address.get_optional_city().map(|city| city.into())), address: address_details.and_then(|address| address.get_optional_line1()), street_number: None, zip: address_details.and_then(|details| details.get_optional_zip()), state: address_details.and_then(|details| details.to_state_code_as_optional().ok()?), cell: None, address_match: None, address_line2: address_details.and_then(|address| address.get_optional_line2()), address_line3: address_details.and_then(|address| address.get_optional_line3()), home_phone: None, work_phone: None, } } } impl From<&Address> for ShippingAddress { fn from(address: &Address) -> Self { let address_details = address.address.as_ref(); Self { email: address.email.clone().unwrap_or_default(), first_name: address_details.and_then(|details| details.get_optional_first_name()), last_name: address_details.and_then(|details| details.get_optional_last_name()), country: address_details .and_then(|details| details.get_optional_country()) .unwrap_or_default(), phone: address .phone .as_ref() .and_then(|phone| phone.number.clone()), city: address_details .and_then(|details| details.get_optional_city().map(|city| city.into())), address: address_details.and_then(|details| details.get_optional_line1()), street_number: None, zip: address_details.and_then(|details| details.get_optional_zip()), state: None, cell: None, address_line2: address_details.and_then(|details| details.get_optional_line2()), address_line3: address_details.and_then(|details| details.get_optional_line3()), county: None, company_name: None, care_of: None, salutation: None, } } } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Card { pub card_number: Option<cards::CardNumber>, pub card_holder_name: Option<Secret<String>>, pub expiration_month: Option<Secret<String>>, pub expiration_year: Option<Secret<String>>, #[serde(rename = "CVV")] pub cvv: Option<Secret<String>>, pub three_d: Option<ThreeD>, pub cc_card_number: Option<Secret<String>>, pub bin: Option<Secret<String>>, pub last4_digits: Option<Secret<String>>, pub cc_exp_month: Option<Secret<String>>, pub cc_exp_year: Option<Secret<String>>, pub acquirer_id: Option<Secret<String>>, pub cvv2_reply: Option<String>, pub avs_code: Option<String>, pub card_type: Option<String>, pub brand: Option<String>, pub issuer_bank_name: Option<String>, pub issuer_country: Option<String>, pub is_prepaid: Option<String>, pub external_token: Option<ExternalToken>, pub stored_credentials: Option<StoredCredentialMode>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct StoredCredentialMode { pub stored_credentials_mode: Option<StoredCredentialModeType>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum StoredCredentialModeType { #[serde(rename = "0")] First, #[serde(rename = "1")] Used, } impl StoredCredentialMode { pub fn get_optional_stored_credential(is_stored_credential: Option<bool>) -> Option<Self> { is_stored_credential.and_then(|is_stored_credential| { if is_stored_credential { Some(Self { stored_credentials_mode: Some(StoredCredentialModeType::Used), }) } else { None } }) } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ExternalToken { pub external_token_provider: ExternalTokenProvider, pub mobile_token: Option<Secret<String>>, pub cryptogram: Option<Secret<String>>, pub eci_provider: Option<String>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub enum ExternalTokenProvider { #[default] GooglePay, ApplePay, } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ExternalMpi { pub eci: Option<String>, pub cavv: Secret<String>, #[serde(rename = "dsTransID")] pub ds_trans_id: Option<String>, pub challenge_preference: Option<String>, pub exemption_request_reason: Option<String>, } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeD { pub method_completion_ind: Option<MethodCompletion>, pub browser_details: Option<BrowserDetails>, pub version: Option<String>, #[serde(rename = "notificationURL")] pub notification_url: Option<String>, #[serde(rename = "merchantURL")] pub merchant_url: Option<String>, pub acs_url: Option<String>, pub acs_challenge_mandate: Option<String>, pub c_req: Option<Secret<String>>, pub three_d_flow: Option<String>, pub external_mpi: Option<ExternalMpi>, pub external_transaction_id: Option<String>, pub transaction_id: Option<String>, pub three_d_reason_id: Option<String>, pub three_d_reason: Option<String>, pub challenge_preference_reason: Option<String>, pub challenge_cancel_reason_id: Option<String>, pub challenge_cancel_reason: Option<String>, pub is_liability_on_issuer: Option<String>, pub is_exemption_request_in_authentication: Option<String>, pub flow: Option<String>, pub acquirer_decision: Option<String>, pub decision_reason: Option<String>, pub platform_type: Option<PlatformType>, pub v2supported: Option<String>, pub v2_additional_params: Option<V2AdditionalParams>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub enum MethodCompletion { #[serde(rename = "Y")] Success, #[serde(rename = "N")] Failure, #[serde(rename = "U")] #[default] Unavailable, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub enum PlatformType { #[serde(rename = "01")] App, #[serde(rename = "02")] #[default] Browser, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BrowserDetails { pub accept_header: String, pub ip: Secret<String, IpAddress>, pub java_enabled: String, pub java_script_enabled: String, pub language: String, pub color_depth: u8, pub screen_height: u32, pub screen_width: u32, pub time_zone: i32, pub user_agent: String, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct V2AdditionalParams { pub challenge_window_size: Option<String>, /// Recurring Expiry in format YYYYMMDD. REQUIRED if isRebilling = 0, We recommend setting rebillExpiry to a value of no more than 5 years from the date of the initial transaction processing date. pub rebill_expiry: Option<String>, /// Recurring Frequency in days pub rebill_frequency: Option<String>, pub challenge_preference: Option<String>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DeviceDetails { pub ip_address: Secret<String, IpAddress>, } impl TransactionType { fn get_from_capture_method_and_amount_string( capture_method: CaptureMethod, amount: &str, ) -> Self { let amount_value = amount.parse::<f64>(); if capture_method == CaptureMethod::Manual || amount_value == Ok(0.0) { Self::Auth } else { Self::Sale } } } #[derive(Debug, Serialize, Deserialize)] pub struct NuveiRedirectionResponse { pub cres: Secret<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiACSResponse { #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: Secret<String>, #[serde(rename = "acsTransID")] pub acs_trans_id: Secret<String>, pub message_type: String, pub message_version: String, pub trans_status: Option<LiabilityShift>, pub message_extension: Option<Vec<MessageExtensionAttribute>>, pub acs_signed_content: Option<serde_json::Value>, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum LiabilityShift { #[serde(rename = "Y", alias = "1", alias = "y")] Success, #[serde(rename = "N", alias = "0", alias = "n")] Failed, } pub fn encode_payload( payload: &[&str], ) -> Result<String, error_stack::Report<errors::ConnectorError>> { let data = payload.join(""); let digest = crypto::Sha256 .generate_digest(data.as_bytes()) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("error encoding nuvie payload")?; Ok(hex::encode(digest)) } impl From<NuveiPaymentSyncResponse> for NuveiTransactionSyncResponse { fn from(value: NuveiPaymentSyncResponse) -> Self { match value { NuveiPaymentSyncResponse::NuveiDmn(payment_dmn_notification) => { Self::from(*payment_dmn_notification) } NuveiPaymentSyncResponse::NuveiApi(nuvei_transaction_sync_response) => { *nuvei_transaction_sync_response } } } } impl TryFrom<&types::PaymentsAuthorizeSessionTokenRouterData> for NuveiSessionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &types::PaymentsAuthorizeSessionTokenRouterData, ) -> Result<Self, Self::Error> { let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?; let merchant_id = connector_meta.merchant_id; let merchant_site_id = connector_meta.merchant_site_id; let client_request_id = item.connector_request_reference_id.clone(); let time_stamp = date_time::DateTime::<date_time::YYYYMMDDHHmmss>::from(date_time::now()); let merchant_secret = connector_meta.merchant_secret; Ok(Self { merchant_id: merchant_id.clone(), merchant_site_id: merchant_site_id.clone(), client_request_id: client_request_id.clone(), time_stamp: time_stamp.clone(), checksum: Secret::new(encode_payload(&[ merchant_id.peek(), merchant_site_id.peek(), &client_request_id, &time_stamp.to_string(), merchant_secret.peek(), ])?), }) } } impl<F, T> TryFrom<ResponseRouterData<F, NuveiSessionResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, NuveiSessionResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::Pending, session_token: Some(item.response.session_token.clone().expose()), response: Ok(PaymentsResponseData::SessionTokenResponse { session_token: item.response.session_token.expose(), }), ..item.data }) } } #[derive(Debug)] pub struct NuveiCardDetails { card: payment_method_data::Card, three_d: Option<ThreeD>, card_holder_name: Option<Secret<String>>, stored_credentials: Option<StoredCredentialMode>, } // Define new structs with camelCase serialization #[derive(Serialize, Debug)] #[serde(rename_all = "camelCase")] struct GooglePayCamelCase { pm_type: Secret<String>, description: Secret<String>, info: GooglePayInfoCamelCase, tokenization_data: GooglePayTokenizationDataCamelCase, } #[derive(Serialize, Debug)] #[serde(rename_all = "camelCase")] struct GooglePayInfoCamelCase { card_network: Secret<String>, card_details: Secret<String>, assurance_details: Option<GooglePayAssuranceDetailsCamelCase>, card_funding_source: Option<GooglePayCardFundingSource>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ExternalSchemeDetails { transaction_id: Secret<String>, // This is sensitive information brand: Option<NuveiCardType>, } #[derive(Serialize, Debug)] #[serde(rename_all = "camelCase")] struct GooglePayAssuranceDetailsCamelCase { card_holder_authenticated: bool, account_verified: bool, } #[derive(Serialize, Debug)] #[serde(rename_all = "camelCase")] struct GooglePayTokenizationDataCamelCase { #[serde(rename = "type")] token_type: Secret<String>, token: Secret<String>, } // Define ApplePay structs with camelCase serialization #[derive(Serialize, Debug)] #[serde(rename_all = "camelCase")] struct ApplePayCamelCase { payment_data: Secret<String>, payment_method: ApplePayPaymentMethodCamelCase, transaction_identifier: Secret<String>, } #[derive(Serialize, Debug)] #[serde(rename_all = "camelCase")] struct ApplePayPaymentMethodCamelCase { display_name: Secret<String>, network: Secret<String>, #[serde(rename = "type")] pm_type: Secret<String>, } fn get_google_pay_decrypt_data( predecrypt_data: &GPayPredecryptData, is_rebilling: Option<IsRebilling>, brand: Option<String>, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> { Ok(NuveiPaymentsRequest { is_rebilling, payment_option: PaymentOption { card: Some(Card { brand, card_number: Some(predecrypt_data.application_primary_account_number.clone()), last4_digits: Some(Secret::new( predecrypt_data .application_primary_account_number .clone() .get_last4(), )), expiration_month: Some(predecrypt_data.card_exp_month.clone()), expiration_year: Some(predecrypt_data.card_exp_year.clone()), external_token: Some(ExternalToken { external_token_provider: ExternalTokenProvider::GooglePay, mobile_token: None, cryptogram: predecrypt_data.cryptogram.clone(), eci_provider: predecrypt_data.eci_indicator.clone(), }), ..Default::default() }), ..Default::default() }, ..Default::default() }) } fn get_googlepay_info<F, Req>( item: &RouterData<F, Req, PaymentsResponseData>, gpay_data: &GooglePayWalletData, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> where Req: NuveiAuthorizePreprocessingCommon, { let is_rebilling = if item.request.is_customer_initiated_mandate_payment() { Some(IsRebilling::False) } else { None }; if let Ok(PaymentMethodToken::GooglePayDecrypt(ref token)) = item.get_payment_method_token() { return get_google_pay_decrypt_data( token, is_rebilling, Some(gpay_data.info.card_network.clone()), ); } match &gpay_data.tokenization_data { GpayTokenizationData::Decrypted(gpay_predecrypt_data) => get_google_pay_decrypt_data( gpay_predecrypt_data, is_rebilling, Some(gpay_data.info.card_network.clone()), ), GpayTokenizationData::Encrypted(ref encrypted_data) => Ok(NuveiPaymentsRequest { is_rebilling, payment_option: PaymentOption { card: Some(Card { external_token: Some(ExternalToken { external_token_provider: ExternalTokenProvider::GooglePay, mobile_token: { let (token_type, token) = ( encrypted_data.token_type.clone(), encrypted_data.token.clone(), ); let google_pay: GooglePayCamelCase = GooglePayCamelCase { pm_type: Secret::new(gpay_data.pm_type.clone()), description: Secret::new(gpay_data.description.clone()), info: GooglePayInfoCamelCase { card_network: Secret::new(gpay_data.info.card_network.clone()), card_details: Secret::new(gpay_data.info.card_details.clone()), assurance_details: gpay_data .info .assurance_details .as_ref() .map(|details| GooglePayAssuranceDetailsCamelCase { card_holder_authenticated: details .card_holder_authenticated, account_verified: details.account_verified, }), card_funding_source: gpay_data.info.card_funding_source.clone(), }, tokenization_data: GooglePayTokenizationDataCamelCase { token_type: token_type.into(), token: token.into(), }, }; Some(Secret::new( google_pay.encode_to_string_of_json().change_context( errors::ConnectorError::RequestEncodingFailed, )?, )) }, cryptogram: None, eci_provider: None, }), ..Default::default() }), ..Default::default() }, ..Default::default() }), } } fn get_apple_pay_decrypt_data( apple_pay_predecrypt_data: &ApplePayPredecryptData, is_rebilling: Option<IsRebilling>, network: String, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> { Ok(NuveiPaymentsRequest { is_rebilling, payment_option: PaymentOption { card: Some(Card { brand: Some(network), card_number: Some( apple_pay_predecrypt_data .application_primary_account_number .clone(), ), last4_digits: Some(Secret::new( apple_pay_predecrypt_data .application_primary_account_number .get_last4(), )), expiration_month: Some( apple_pay_predecrypt_data .application_expiration_month .clone(), ), expiration_year: Some( apple_pay_predecrypt_data .application_expiration_year .clone(), ), external_token: Some(ExternalToken { external_token_provider: ExternalTokenProvider::ApplePay, mobile_token: None, cryptogram: Some( apple_pay_predecrypt_data .payment_data .online_payment_cryptogram .clone(), ), eci_provider: apple_pay_predecrypt_data.payment_data.eci_indicator.clone(), }), ..Default::default() }), ..Default::default() }, ..Default::default() }) } fn get_applepay_info<F, Req>( item: &RouterData<F, Req, PaymentsResponseData>, apple_pay_data: &ApplePayWalletData, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> where Req: NuveiAuthorizePreprocessingCommon, { let is_rebilling = if item.request.is_customer_initiated_mandate_payment() { Some(IsRebilling::False) } else { None }; if let Ok(PaymentMethodToken::ApplePayDecrypt(ref token)) = item.get_payment_method_token() { return get_apple_pay_decrypt_data( token, is_rebilling, apple_pay_data.payment_method.network.clone(), ); } match apple_pay_data.payment_data { ApplePayPaymentData::Decrypted(ref apple_pay_predecrypt_data) => { get_apple_pay_decrypt_data( apple_pay_predecrypt_data, is_rebilling, apple_pay_data.payment_method.network.clone(), ) } ApplePayPaymentData::Encrypted(ref encrypted_data) => Ok(NuveiPaymentsRequest { is_rebilling, payment_option: PaymentOption { card: Some(Card { external_token: Some(ExternalToken { external_token_provider: ExternalTokenProvider::ApplePay, mobile_token: { let apple_pay: ApplePayCamelCase = ApplePayCamelCase { payment_data: encrypted_data.to_string().into(), payment_method: ApplePayPaymentMethodCamelCase { display_name: Secret::new( apple_pay_data.payment_method.display_name.clone(), ), network: Secret::new( apple_pay_data.payment_method.network.clone(), ), pm_type: Secret::new( apple_pay_data.payment_method.pm_type.clone(), ), }, transaction_identifier: Secret::new( apple_pay_data.transaction_identifier.clone(), ), }; Some(Secret::new( apple_pay.encode_to_string_of_json().change_context( errors::ConnectorError::RequestEncodingFailed, )?, )) }, cryptogram: None, eci_provider: None, }), ..Default::default() }), ..Default::default() }, ..Default::default() }), } } impl TryFrom<enums::BankNames> for NuveiBIC { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(bank: enums::BankNames) -> Result<Self, Self::Error> { match bank { enums::BankNames::AbnAmro => Ok(Self::Abnamro), enums::BankNames::AsnBank => Ok(Self::ASNBank), enums::BankNames::Bunq => Ok(Self::Bunq), enums::BankNames::Ing => Ok(Self::Ing), enums::BankNames::Knab => Ok(Self::Knab), enums::BankNames::Rabobank => Ok(Self::Rabobank), enums::BankNames::SnsBank => Ok(Self::SNSBank), enums::BankNames::TriodosBank => Ok(Self::TriodosBank), enums::BankNames::VanLanschot => Ok(Self::VanLanschotBankiers), enums::BankNames::Moneyou => Ok(Self::Moneyou), enums::BankNames::AmericanExpress | enums::BankNames::AffinBank | enums::BankNames::AgroBank | enums::BankNames::AllianceBank | enums::BankNames::AmBank | enums::BankNames::BankOfAmerica | enums::BankNames::BankOfChina | enums::BankNames::BankIslam | enums::BankNames::BankMuamalat | enums::BankNames::BankRakyat | enums::BankNames::BankSimpananNasional | enums::BankNames::Barclays | enums::BankNames::BlikPSP | enums::BankNames::CapitalOne | enums::BankNames::Chase | enums::BankNames::Citi | enums::BankNames::CimbBank | enums::BankNames::Discover | enums::BankNames::NavyFederalCreditUnion | enums::BankNames::PentagonFederalCreditUnion | enums::BankNames::SynchronyBank | enums::BankNames::WellsFargo | enums::BankNames::Handelsbanken | enums::BankNames::HongLeongBank | enums::BankNames::HsbcBank | enums::BankNames::KuwaitFinanceHouse | enums::BankNames::Regiobank | enums::BankNames::Revolut | enums::BankNames::ArzteUndApothekerBank | enums::BankNames::AustrianAnadiBankAg | enums::BankNames::BankAustria | enums::BankNames::Bank99Ag | enums::BankNames::BankhausCarlSpangler | enums::BankNames::BankhausSchelhammerUndSchatteraAg | enums::BankNames::BankMillennium | enums::BankNames::BankPEKAOSA | enums::BankNames::BawagPskAg | enums::BankNames::BksBankAg | enums::BankNames::BrullKallmusBankAg | enums::BankNames::BtvVierLanderBank | enums::BankNames::CapitalBankGraweGruppeAg | enums::BankNames::CeskaSporitelna | enums::BankNames::Dolomitenbank | enums::BankNames::EasybankAg | enums::BankNames::EPlatbyVUB | enums::BankNames::ErsteBankUndSparkassen | enums::BankNames::FrieslandBank | enums::BankNames::HypoAlpeadriabankInternationalAg | enums::BankNames::HypoNoeLbFurNiederosterreichUWien | enums::BankNames::HypoOberosterreichSalzburgSteiermark | enums::BankNames::HypoTirolBankAg | enums::BankNames::HypoVorarlbergBankAg | enums::BankNames::HypoBankBurgenlandAktiengesellschaft | enums::BankNames::KomercniBanka | enums::BankNames::MBank | enums::BankNames::MarchfelderBank | enums::BankNames::Maybank | enums::BankNames::OberbankAg | enums::BankNames::OsterreichischeArzteUndApothekerbank | enums::BankNames::OcbcBank | enums::BankNames::PayWithING | enums::BankNames::PlaceZIPKO | enums::BankNames::PlatnoscOnlineKartaPlatnicza | enums::BankNames::PosojilnicaBankEGen | enums::BankNames::PostovaBanka | enums::BankNames::PublicBank | enums::BankNames::RaiffeisenBankengruppeOsterreich | enums::BankNames::RhbBank | enums::BankNames::SchelhammerCapitalBankAg | enums::BankNames::StandardCharteredBank | enums::BankNames::SchoellerbankAg | enums::BankNames::SpardaBankWien | enums::BankNames::SporoPay | enums::BankNames::SantanderPrzelew24 | enums::BankNames::TatraPay | enums::BankNames::Viamo | enums::BankNames::VolksbankGruppe | enums::BankNames::VolkskreditbankAg | enums::BankNames::VrBankBraunau | enums::BankNames::UobBank | enums::BankNames::PayWithAliorBank | enums::BankNames::BankiSpoldzielcze | enums::BankNames::PayWithInteligo | enums::BankNames::BNPParibasPoland | enums::BankNames::BankNowySA | enums::BankNames::CreditAgricole | enums::BankNames::PayWithBOS | enums::BankNames::PayWithCitiHandlowy | enums::BankNames::PayWithPlusBank | enums::BankNames::ToyotaBank | enums::BankNames::VeloBank | enums::BankNames::ETransferPocztowy24 | enums::BankNames::PlusBank | enums::BankNames::EtransferPocztowy24 | enums::BankNames::BankiSpbdzielcze | enums::BankNames::BankNowyBfgSa | enums::BankNames::GetinBank | enums::BankNames::Blik | enums::BankNames::NoblePay | enums::BankNames::IdeaBank | enums::BankNames::EnveloBank | enums::BankNames::NestPrzelew | enums::BankNames::MbankMtransfer | enums::BankNames::Inteligo | enums::BankNames::PbacZIpko | enums::BankNames::BnpParibas | enums::BankNames::BankPekaoSa | enums::BankNames::VolkswagenBank | enums::BankNames::AliorBank | enums::BankNames::Boz | enums::BankNames::BangkokBank | enums::BankNames::KrungsriBank | enums::BankNames::KrungThaiBank | enums::BankNames::TheSiamCommercialBank | enums::BankNames::KasikornBank | enums::BankNames::OpenBankSuccess | enums::BankNames::OpenBankFailure | enums::BankNames::OpenBankCancelled | enums::BankNames::Aib | enums::BankNames::BankOfScotland | enums::BankNames::DanskeBank | enums::BankNames::FirstDirect | enums::BankNames::FirstTrust | enums::BankNames::Halifax | enums::BankNames::Lloyds | enums::BankNames::Monzo | enums::BankNames::NatWest | enums::BankNames::NationwideBank | enums::BankNames::RoyalBankOfScotland | enums::BankNames::Starling | enums::BankNames::TsbBank | enums::BankNames::TescoBank | enums::BankNames::Yoursafe | enums::BankNames::N26 | enums::BankNames::NationaleNederlanden | enums::BankNames::UlsterBank => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Nuvei"), ))?, } } } impl<F, Req> ForeignTryFrom<( AlternativePaymentMethodType, Option<BankRedirectData>, &RouterData<F, Req, PaymentsResponseData>, )> for NuveiPaymentsRequest where Req: NuveiAuthorizePreprocessingCommon, { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from( data: ( AlternativePaymentMethodType, Option<BankRedirectData>, &RouterData<F, Req, PaymentsResponseData>, ), ) -> Result<Self, Self::Error> { let (payment_method, redirect, item) = data; let bank_id = match (&payment_method, redirect) { (AlternativePaymentMethodType::Expresscheckout, _) => None, (AlternativePaymentMethodType::Giropay, _) => None, (AlternativePaymentMethodType::Sofort, _) | (AlternativePaymentMethodType::Eps, _) => { let address = item.get_billing_address()?; address.get_first_name()?; item.request.get_email_required()?; item.get_billing_country()?; None } ( AlternativePaymentMethodType::Ideal, Some(BankRedirectData::Ideal { bank_name, .. }), ) => { let address = item.get_billing_address()?; address.get_first_name()?; item.request.get_email_required()?; item.get_billing_country()?; bank_name.map(NuveiBIC::try_from).transpose()? } _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Nuvei"), ))?, }; let billing_address: Option<BillingAddress> = item.get_billing().ok().map(|billing| billing.into()); Ok(Self { payment_option: PaymentOption { alternative_payment_method: Some(AlternativePaymentMethod { payment_method, bank_id, }), ..Default::default() }, billing_address, ..Default::default() }) } } fn get_pay_later_info<F, Req>( payment_method_type: AlternativePaymentMethodType, item: &RouterData<F, Req, PaymentsResponseData>, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> where Req: NuveiAuthorizePreprocessingCommon, { let address = item .get_billing()? .address .as_ref() .ok_or_else(missing_field_err("billing.address"))?; address.get_first_name()?; let payment_method = payment_method_type; address.get_country()?; //country is necessary check item.request.get_email_required()?; Ok(NuveiPaymentsRequest { payment_option: PaymentOption { alternative_payment_method: Some(AlternativePaymentMethod { payment_method, ..Default::default() }), billing_address: item.get_billing().ok().map(|billing| billing.into()), ..Default::default() }, ..Default::default() }) } fn get_ntid_card_info<F, Req>( router_data: &RouterData<F, Req, PaymentsResponseData>, data: CardDetailsForNetworkTransactionId, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> where Req: NuveiAuthorizePreprocessingCommon, { let card_type = match data.card_network.clone() { Some(card_type) => NuveiCardType::try_from(card_type)?, None => NuveiCardType::try_from(&data.get_card_issuer()?)?, }; let external_scheme_details = Some(ExternalSchemeDetails { transaction_id: router_data .request .get_ntid() .ok_or_else(missing_field_err("network_transaction_id")) .attach_printable("Nuvei unable to find NTID for MIT")? .into(), brand: Some(card_type), }); let payment_option: PaymentOption = PaymentOption { card: Some(Card { card_number: Some(data.card_number), card_holder_name: data.card_holder_name, expiration_month: Some(data.card_exp_month), expiration_year: Some(data.card_exp_year), ..Default::default() // CVV should be disabled by nuvei }), redirect_url: None, user_payment_option_id: None, alternative_payment_method: None, billing_address: None, shipping_address: None, }; let is_rebilling = Some(IsRebilling::True); Ok(NuveiPaymentsRequest { external_scheme_details, payment_option, user_token_id: Some( router_data .request .get_customer_id_optional() .ok_or_else(missing_field_err("customer_id"))?, ), is_rebilling, ..Default::default() }) } fn get_l2_l3_items( l2_l3_data: &Option<Box<L2L3Data>>, currency: enums::Currency, ) -> Result<Option<Vec<NuveiItem>>, error_stack::Report<errors::ConnectorError>> { l2_l3_data.as_ref().map_or(Ok(None), |data| { data.order_details .as_ref() .map_or(Ok(None), |order_details_list| { // Map each order to a Result<NuveiItem> let results: Vec<Result<NuveiItem, error_stack::Report<errors::ConnectorError>>> = order_details_list .iter() .map(|order| { let discount = order .unit_discount_amount .map(|amount| { convert_amount(NUVEI_AMOUNT_CONVERTOR, amount, currency) }) .transpose()?; let tax = order .total_tax_amount .map(|amount| { convert_amount(NUVEI_AMOUNT_CONVERTOR, amount, currency) }) .transpose()?; Ok(NuveiItem { name: order.product_name.clone(), item_type: order.product_type.clone().into(), price: convert_amount( NUVEI_AMOUNT_CONVERTOR, order.amount, currency, )?, quantity: order.quantity.to_string(), group_id: order.product_id.clone(), discount, discount_rate: None, shipping: None, shipping_tax: None, shipping_tax_rate: None, tax, tax_rate: order.tax_rate.map(|rate| rate.to_string()), image_url: order.product_img_link.clone(), product_url: None, }) }) .collect(); let mut items = Vec::with_capacity(results.len()); for result in results { match result { Ok(item) => items.push(item), Err(err) => return Err(err), } } Ok(Some(items)) }) }) } fn get_amount_details( l2_l3_data: &Option<Box<L2L3Data>>, currency: enums::Currency, ) -> Result<Option<NuveiAmountDetails>, error_stack::Report<errors::ConnectorError>> { l2_l3_data.as_ref().map_or(Ok(None), |data| { let total_tax = data .order_tax_amount .map(|amount| convert_amount(NUVEI_AMOUNT_CONVERTOR, amount, currency)) .transpose()?; let total_shipping = data .shipping_cost .map(|amount| convert_amount(NUVEI_AMOUNT_CONVERTOR, amount, currency)) .transpose()?; let total_discount = data .discount_amount .map(|amount| convert_amount(NUVEI_AMOUNT_CONVERTOR, amount, currency)) .transpose()?; let total_handling = data .duty_amount .map(|amount| convert_amount(NUVEI_AMOUNT_CONVERTOR, amount, currency)) .transpose()?; Ok(Some(NuveiAmountDetails { total_tax, total_shipping, total_handling, total_discount, })) }) } impl<F, Req> TryFrom<(&RouterData<F, Req, PaymentsResponseData>, String)> for NuveiPaymentsRequest where Req: NuveiAuthorizePreprocessingCommon + std::fmt::Debug, F: std::fmt::Debug, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( data: (&RouterData<F, Req, PaymentsResponseData>, String), ) -> Result<Self, Self::Error> { let item = data.0; let request_data = match item.request.get_payment_method_data_required()?.clone() { PaymentMethodData::Card(card) => get_card_info(item, &card), PaymentMethodData::MandatePayment => Self::try_from(item), PaymentMethodData::CardDetailsForNetworkTransactionId(data) => { get_ntid_card_info(item, data) } PaymentMethodData::Wallet(wallet) => match wallet { WalletData::GooglePay(gpay_data) => get_googlepay_info(item, &gpay_data), WalletData::ApplePay(apple_pay_data) => get_applepay_info(item, &apple_pay_data), WalletData::PaypalRedirect(_) => Self::foreign_try_from(( AlternativePaymentMethodType::Expresscheckout, None, item, )), WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::WeChatPayQr(_) | WalletData::RevolutPay(_) | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), ) .into()), }, PaymentMethodData::BankRedirect(redirect) => match redirect { BankRedirectData::Eps { .. } => Self::foreign_try_from(( AlternativePaymentMethodType::Eps, Some(redirect), item, )), BankRedirectData::Giropay { .. } => Self::foreign_try_from(( AlternativePaymentMethodType::Giropay, Some(redirect), item, )), BankRedirectData::Ideal { .. } => Self::foreign_try_from(( AlternativePaymentMethodType::Ideal, Some(redirect), item, )), BankRedirectData::Sofort { .. } => Self::foreign_try_from(( AlternativePaymentMethodType::Sofort, Some(redirect), item, )), BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::Trustly { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::LocalBankRedirect {} => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), ) .into()) } }, PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { PayLaterData::KlarnaRedirect { .. } => { get_pay_later_info(AlternativePaymentMethodType::Klarna, item) } PayLaterData::AfterpayClearpayRedirect { .. } => { get_pay_later_info(AlternativePaymentMethodType::AfterPay, item) } PayLaterData::KlarnaSdk { .. } | PayLaterData::FlexitiRedirect {} | PayLaterData::AffirmRedirect {} | PayLaterData::PayBrightRedirect {} | PayLaterData::WalleyRedirect {} | PayLaterData::AlmaRedirect {} | PayLaterData::AtomeRedirect {} | PayLaterData::BreadpayRedirect {} => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), ) .into()), }, PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), ) .into()), }?; let currency = item.request.get_currency_required()?; let request = Self::try_from(NuveiPaymentRequestData { amount: convert_amount( NUVEI_AMOUNT_CONVERTOR, item.request.get_minor_amount_required()?, currency, )?, currency, connector_auth_type: item.connector_auth_type.clone(), client_request_id: item.connector_request_reference_id.clone(), session_token: Secret::new(data.1), capture_method: item.request.get_capture_method(), ..Default::default() })?; let return_url = item.request.get_return_url_required()?; let amount_details = get_amount_details(&item.l2_l3_data, currency)?; let l2_l3_items: Option<Vec<NuveiItem>> = get_l2_l3_items(&item.l2_l3_data, currency)?; let address = { let mut billing_address = item.get_billing()?.clone(); item.get_billing_first_name()?; billing_address.email = match item.get_billing_email() { Ok(email) => Some(email), Err(_) => Some(item.request.get_email_required()?), }; item.get_billing_country()?; Some(billing_address) }; let shipping_address: Option<ShippingAddress> = item.get_optional_shipping().map(|address| address.into()); let billing_address: Option<BillingAddress> = address.clone().map(|ref address| address.into()); let device_details = if request_data .device_details .ip_address .clone() .expose() .is_empty() { DeviceDetails::foreign_try_from(&item.request.get_browser_info())? } else { request_data.device_details.clone() }; Ok(Self { is_rebilling: request_data.is_rebilling, user_token_id: request_data.user_token_id, related_transaction_id: request_data.related_transaction_id, payment_option: request_data.payment_option, billing_address, shipping_address, device_details, url_details: Some(UrlDetails { success_url: return_url.clone(), failure_url: return_url.clone(), pending_url: return_url.clone(), }), amount_details, items: l2_l3_items, is_partial_approval: item.request.get_is_partial_approval(), external_scheme_details: request_data.external_scheme_details, ..request }) } } fn get_card_info<F, Req>( item: &RouterData<F, Req, PaymentsResponseData>, card_details: &payment_method_data::Card, ) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> where Req: NuveiAuthorizePreprocessingCommon, { let browser_information = item.request.get_browser_info().clone(); let related_transaction_id = if item.is_three_ds() { item.request.get_related_transaction_id().clone() } else { None }; let address: Option<&AddressDetails> = item .get_optional_billing() .and_then(|billing_details| billing_details.address.as_ref()); if let Some(address) = address { // mandatory fields check address.get_first_name()?; item.request.get_email_required()?; item.get_billing_country()?; } let (is_rebilling, additional_params, user_token_id) = match item.request.is_customer_initiated_mandate_payment() { true => { ( Some(IsRebilling::False), // In case of first installment, rebilling should be 0 Some(V2AdditionalParams { rebill_expiry: Some( time::OffsetDateTime::now_utc() .replace_year(time::OffsetDateTime::now_utc().year() + 5) .map_err(|_| errors::ConnectorError::DateFormattingFailed)? .date() .format(&time::macros::format_description!("[year][month][day]")) .map_err(|_| errors::ConnectorError::DateFormattingFailed)?, ), rebill_frequency: Some("0".to_string()), challenge_window_size: Some(CHALLENGE_WINDOW_SIZE.to_string()), challenge_preference: Some(CHALLENGE_PREFERENCE.to_string()), }), item.request.get_customer_id_optional(), ) } // non mandate transactions false => ( None, Some(V2AdditionalParams { rebill_expiry: None, rebill_frequency: None, challenge_window_size: Some(CHALLENGE_WINDOW_SIZE.to_string()), challenge_preference: Some(CHALLENGE_PREFERENCE.to_string()), }), None, ), }; let three_d = if let Some(auth_data) = item.request.get_auth_data()? { Some(ThreeD { external_mpi: Some(ExternalMpi { eci: auth_data.eci, cavv: auth_data.cavv, ds_trans_id: auth_data.ds_trans_id, challenge_preference: None, exemption_request_reason: None, }), ..Default::default() }) } else if item.is_three_ds() { let browser_details = match &browser_information { Some(browser_info) => Some(BrowserDetails { accept_header: browser_info.get_accept_header()?, ip: browser_info.get_ip_address()?, java_enabled: browser_info.get_java_enabled()?.to_string().to_uppercase(), java_script_enabled: browser_info .get_java_script_enabled()? .to_string() .to_uppercase(), language: browser_info.get_language()?, screen_height: browser_info.get_screen_height()?, screen_width: browser_info.get_screen_width()?, color_depth: browser_info.get_color_depth()?, user_agent: browser_info.get_user_agent()?, time_zone: browser_info.get_time_zone()?, }), None => None, }; Some(ThreeD { browser_details, v2_additional_params: additional_params, notification_url: item.request.get_complete_authorize_url().clone(), merchant_url: Some(item.request.get_return_url_required()?), platform_type: Some(PlatformType::Browser), method_completion_ind: Some(MethodCompletion::Unavailable), ..Default::default() }) } else { None }; let is_moto = item.request.get_is_moto(); Ok(NuveiPaymentsRequest { related_transaction_id, is_rebilling, user_token_id, device_details: DeviceDetails::foreign_try_from(&item.request.get_browser_info().clone())?, payment_option: PaymentOption::from(NuveiCardDetails { card: card_details.clone(), three_d, card_holder_name: item.get_optional_billing_full_name(), stored_credentials: item.request.get_is_stored_credential(), }), is_moto, ..Default::default() }) } impl From<NuveiCardDetails> for PaymentOption { fn from(card_details: NuveiCardDetails) -> Self { let card = card_details.card; Self { card: Some(Card { card_number: Some(card.card_number), card_holder_name: card_details.card_holder_name, expiration_month: Some(card.card_exp_month), expiration_year: Some(card.card_exp_year), three_d: card_details.three_d, cvv: Some(card.card_cvc), stored_credentials: card_details.stored_credentials, ..Default::default() }), ..Default::default() } } } impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)> for NuveiPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( data: (&types::PaymentsCompleteAuthorizeRouterData, Secret<String>), ) -> Result<Self, Self::Error> { let item = data.0; let request_data = match item.request.payment_method_data.clone() { Some(PaymentMethodData::Card(card)) => { let device_details = DeviceDetails::foreign_try_from(&item.request.browser_info)?; Ok(Self { payment_option: PaymentOption::from(NuveiCardDetails { card, three_d: None, card_holder_name: item.get_optional_billing_full_name(), stored_credentials: StoredCredentialMode::get_optional_stored_credential( item.request.is_stored_credential, ), }), device_details, ..Default::default() }) } _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), )), }?; let request = Self::try_from(NuveiPaymentRequestData { amount: convert_amount( NUVEI_AMOUNT_CONVERTOR, item.request.minor_amount, item.request.currency, )?, currency: item.request.currency, connector_auth_type: item.connector_auth_type.clone(), client_request_id: item.connector_request_reference_id.clone(), session_token: data.1, capture_method: item.request.capture_method, ..Default::default() })?; Ok(Self { related_transaction_id: item.request.connector_transaction_id.clone(), payment_option: request_data.payment_option, device_details: request_data.device_details, ..request }) } } impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(request: NuveiPaymentRequestData) -> Result<Self, Self::Error> { let session_token = request.session_token; fp_utils::when(session_token.clone().expose().is_empty(), || { Err(errors::ConnectorError::FailedToObtainAuthType) })?; let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&request.connector_auth_type)?; let merchant_id = connector_meta.merchant_id; let merchant_site_id = connector_meta.merchant_site_id; let client_request_id = request.client_request_id; let time_stamp = date_time::format_date(date_time::now(), date_time::DateFormat::YYYYMMDDHHmmss) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let merchant_secret = connector_meta.merchant_secret; let transaction_type = TransactionType::get_from_capture_method_and_amount_string( request.capture_method.unwrap_or_default(), &request.amount.get_amount_as_string(), ); Ok(Self { merchant_id: merchant_id.clone(), merchant_site_id: merchant_site_id.clone(), client_request_id: Secret::new(client_request_id.clone()), time_stamp: time_stamp.clone(), session_token, transaction_type, checksum: Secret::new(encode_payload(&[ merchant_id.peek(), merchant_site_id.peek(), &client_request_id, &request.amount.get_amount_as_string(), &request.currency.to_string(), &time_stamp, merchant_secret.peek(), ])?), amount: request.amount, user_token_id: None, currency: request.currency, ..Default::default() }) } } impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentFlowRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(request: NuveiPaymentRequestData) -> Result<Self, Self::Error> { let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&request.connector_auth_type)?; let merchant_id = connector_meta.merchant_id; let merchant_site_id = connector_meta.merchant_site_id; let client_request_id = request.client_request_id; let time_stamp = date_time::format_date(date_time::now(), date_time::DateFormat::YYYYMMDDHHmmss) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let merchant_secret = connector_meta.merchant_secret; Ok(Self { merchant_id: merchant_id.to_owned(), merchant_site_id: merchant_site_id.to_owned(), client_request_id: client_request_id.clone(), time_stamp: time_stamp.clone(), checksum: Secret::new(encode_payload(&[ merchant_id.peek(), merchant_site_id.peek(), &client_request_id, &request.amount.get_amount_as_string(), &request.currency.to_string(), &request.related_transaction_id.clone().unwrap_or_default(), &time_stamp, merchant_secret.peek(), ])?), amount: request.amount, currency: request.currency, related_transaction_id: request.related_transaction_id, }) } } #[derive(Debug, Clone, Default)] pub struct NuveiPaymentRequestData { pub amount: StringMajorUnit, pub currency: enums::Currency, pub related_transaction_id: Option<String>, pub client_request_id: String, pub connector_auth_type: ConnectorAuthType, pub session_token: Secret<String>, pub capture_method: Option<CaptureMethod>, } impl TryFrom<&types::PaymentsCaptureRouterData> for NuveiPaymentFlowRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { Self::try_from(NuveiPaymentRequestData { client_request_id: item.connector_request_reference_id.clone(), connector_auth_type: item.connector_auth_type.clone(), amount: convert_amount( NUVEI_AMOUNT_CONVERTOR, item.request.minor_amount_to_capture, item.request.currency, )?, currency: item.request.currency, related_transaction_id: Some(item.request.connector_transaction_id.clone()), ..Default::default() }) } } impl TryFrom<&types::RefundExecuteRouterData> for NuveiPaymentFlowRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundExecuteRouterData) -> Result<Self, Self::Error> { Self::try_from(NuveiPaymentRequestData { client_request_id: item.connector_request_reference_id.clone(), connector_auth_type: item.connector_auth_type.clone(), amount: convert_amount( NUVEI_AMOUNT_CONVERTOR, item.request.minor_refund_amount, item.request.currency, )?, currency: item.request.currency, related_transaction_id: Some(item.request.connector_transaction_id.clone()), ..Default::default() }) } } impl TryFrom<&types::PaymentsSyncRouterData> for NuveiPaymentSyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&value.connector_auth_type)?; let merchant_id = connector_meta.merchant_id.clone(); let merchant_site_id = connector_meta.merchant_site_id.clone(); let merchant_secret = connector_meta.merchant_secret.clone(); let time_stamp = date_time::format_date(date_time::now(), date_time::DateFormat::YYYYMMDDHHmmss) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let transaction_id = value .request .connector_transaction_id .clone() .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; let checksum = Secret::new(encode_payload(&[ merchant_id.peek(), merchant_site_id.peek(), &transaction_id, &time_stamp, merchant_secret.peek(), ])?); Ok(Self { merchant_id, merchant_site_id, time_stamp, checksum, transaction_id, }) } } #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct NuveiVoidRequest { pub merchant_id: Secret<String>, pub merchant_site_id: Secret<String>, pub client_unique_id: String, pub related_transaction_id: String, pub time_stamp: String, pub checksum: Secret<String>, pub client_request_id: String, } impl TryFrom<&types::PaymentsCancelPostCaptureRouterData> for NuveiVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelPostCaptureRouterData) -> Result<Self, Self::Error> { let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?; let merchant_id = connector_meta.merchant_id.clone(); let merchant_site_id = connector_meta.merchant_site_id.clone(); let merchant_secret = connector_meta.merchant_secret.clone(); let client_unique_id = item.connector_request_reference_id.clone(); let related_transaction_id = item.request.connector_transaction_id.clone(); let client_request_id = item.connector_request_reference_id.clone(); let time_stamp = date_time::format_date(date_time::now(), date_time::DateFormat::YYYYMMDDHHmmss) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let checksum = Secret::new(encode_payload(&[ merchant_id.peek(), merchant_site_id.peek(), &client_request_id, &client_unique_id, "", // amount (empty for void) "", // currency (empty for void) &related_transaction_id, "", // authCode (empty) "", // comment (empty) &time_stamp, merchant_secret.peek(), ])?); Ok(Self { merchant_id, merchant_site_id, client_unique_id, related_transaction_id, time_stamp, checksum, client_request_id, }) } } impl TryFrom<&types::PaymentsCancelRouterData> for NuveiPaymentFlowRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { Self::try_from(NuveiPaymentRequestData { client_request_id: item.connector_request_reference_id.clone(), connector_auth_type: item.connector_auth_type.clone(), amount: convert_amount( NUVEI_AMOUNT_CONVERTOR, item.request .minor_amount .ok_or_else(missing_field_err("amount"))?, item.request.get_currency()?, )?, currency: item.request.get_currency()?, related_transaction_id: Some(item.request.connector_transaction_id.clone()), ..Default::default() }) } } // Auth Struct pub struct NuveiAuthType { pub(super) merchant_id: Secret<String>, pub(super) merchant_site_id: Secret<String>, pub(super) merchant_secret: Secret<String>, } impl TryFrom<&ConnectorAuthType> for NuveiAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } = auth_type { Ok(Self { merchant_id: api_key.to_owned(), merchant_site_id: key1.to_owned(), merchant_secret: api_secret.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NuveiPayoutRequest { pub merchant_id: Secret<String>, pub merchant_site_id: Secret<String>, pub client_request_id: String, pub client_unique_id: String, pub amount: StringMajorUnit, pub currency: String, pub user_token_id: CustomerId, pub time_stamp: String, pub checksum: Secret<String>, pub card_data: NuveiPayoutCardData, pub url_details: NuveiPayoutUrlDetails, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NuveiPayoutUrlDetails { pub notification_url: String, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NuveiPayoutCardData { pub card_number: cards::CardNumber, pub card_holder_name: Secret<String>, pub expiration_month: Secret<String>, pub expiration_year: Secret<String>, } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum NuveiPayoutResponse { NuveiPayoutSuccessResponse(NuveiPayoutSuccessResponse), NuveiPayoutErrorResponse(NuveiPayoutErrorResponse), } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiPayoutSuccessResponse { pub transaction_id: String, pub user_token_id: CustomerId, pub transaction_status: NuveiTransactionStatus, pub client_unique_id: String, } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiPayoutErrorResponse { pub status: NuveiPaymentStatus, pub err_code: i64, pub reason: Option<String>, } #[cfg(feature = "payouts")] impl TryFrom<api_models::payouts::PayoutMethodData> for NuveiPayoutCardData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( payout_method_data: api_models::payouts::PayoutMethodData, ) -> Result<Self, Self::Error> { match payout_method_data { api_models::payouts::PayoutMethodData::Card(card_data) => Ok(Self { card_number: card_data.card_number, card_holder_name: card_data.card_holder_name.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "customer_id", }, )?, expiration_month: card_data.expiry_month, expiration_year: card_data.expiry_year, }), api_models::payouts::PayoutMethodData::Bank(_) | api_models::payouts::PayoutMethodData::Wallet(_) | api_models::payouts::PayoutMethodData::BankRedirect(_) => { Err(errors::ConnectorError::NotImplemented( "Selected Payout Method is not implemented for Nuvei".to_string(), ) .into()) } } } } #[cfg(feature = "payouts")] impl<F> TryFrom<&types::PayoutsRouterData<F>> for NuveiPayoutRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { let connector_auth: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?; let amount = convert_amount( NUVEI_AMOUNT_CONVERTOR, item.request.minor_amount, item.request.destination_currency, )?; let time_stamp = date_time::format_date(date_time::now(), date_time::DateFormat::YYYYMMDDHHmmss) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let checksum = encode_payload(&[ connector_auth.merchant_id.peek(), connector_auth.merchant_site_id.peek(), &item.connector_request_reference_id, &amount.get_amount_as_string(), &item.request.destination_currency.to_string(), &time_stamp, connector_auth.merchant_secret.peek(), ])?; let payout_method_data = item.get_payout_method_data()?; let card_data = NuveiPayoutCardData::try_from(payout_method_data)?; let customer_details = item.request.get_customer_details()?; let url_details = NuveiPayoutUrlDetails { notification_url: item.request.get_webhook_url()?, }; Ok(Self { merchant_id: connector_auth.merchant_id, merchant_site_id: connector_auth.merchant_site_id, client_request_id: item.connector_request_reference_id.clone(), client_unique_id: item.connector_request_reference_id.clone(), amount, currency: item.request.destination_currency.to_string(), user_token_id: customer_details.customer_id.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "customer_id", }, )?, time_stamp, checksum: Secret::new(checksum), card_data, url_details, }) } } #[cfg(feature = "payouts")] impl TryFrom<PayoutsResponseRouterData<PoFulfill, NuveiPayoutResponse>> for types::PayoutsRouterData<PoFulfill> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PayoutsResponseRouterData<PoFulfill, NuveiPayoutResponse>, ) -> Result<Self, Self::Error> { let response = &item.response; match response { NuveiPayoutResponse::NuveiPayoutSuccessResponse(response_data) => Ok(Self { response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::from( response_data.transaction_status.clone(), )), connector_payout_id: Some(response_data.transaction_id.clone()), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }), NuveiPayoutResponse::NuveiPayoutErrorResponse(error_response_data) => Ok(Self { response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::from( error_response_data.status.clone(), )), connector_payout_id: None, payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: Some(error_response_data.err_code.to_string()), error_message: error_response_data.reason.clone(), payout_connector_metadata: None, }), ..item.data }), } } } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum NuveiPaymentStatus { Success, Failed, Error, #[default] Processing, } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum NuveiTransactionStatus { #[serde(alias = "Approved", alias = "APPROVED")] Approved, #[serde(alias = "Declined", alias = "DECLINED")] Declined, #[serde(alias = "Filter Error", alias = "ERROR", alias = "Error")] Error, #[serde(alias = "Redirect", alias = "REDIRECT")] Redirect, #[serde(alias = "Pending", alias = "PENDING")] Pending, #[serde(alias = "Processing", alias = "PROCESSING")] #[default] Processing, } impl From<NuveiTransactionStatus> for enums::AttemptStatus { fn from(item: NuveiTransactionStatus) -> Self { match item { NuveiTransactionStatus::Approved => Self::Charged, NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => Self::Failure, _ => Self::Pending, } } } #[cfg(feature = "payouts")] impl From<NuveiTransactionStatus> for enums::PayoutStatus { fn from(item: NuveiTransactionStatus) -> Self { match item { NuveiTransactionStatus::Approved => Self::Success, NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => Self::Failed, NuveiTransactionStatus::Processing | NuveiTransactionStatus::Pending => Self::Pending, NuveiTransactionStatus::Redirect => Self::Ineligible, } } } #[cfg(feature = "payouts")] impl From<NuveiPaymentStatus> for enums::PayoutStatus { fn from(item: NuveiPaymentStatus) -> Self { match item { NuveiPaymentStatus::Success => Self::Success, NuveiPaymentStatus::Failed | NuveiPaymentStatus::Error => Self::Failed, NuveiPaymentStatus::Processing => Self::Pending, } } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiPartialApproval { pub requested_amount: StringMajorUnit, pub requested_currency: enums::Currency, pub processed_amount: StringMajorUnit, pub processed_currency: enums::Currency, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiPaymentsResponse { pub order_id: Option<String>, pub user_token_id: Option<Secret<String>>, pub payment_option: Option<PaymentOption>, pub transaction_status: Option<NuveiTransactionStatus>, pub gw_error_code: Option<i64>, pub gw_error_reason: Option<String>, pub gw_extended_error_code: Option<i64>, pub issuer_decline_code: Option<String>, pub issuer_decline_reason: Option<String>, pub transaction_type: Option<NuveiTransactionType>, pub transaction_id: Option<String>, pub external_transaction_id: Option<String>, pub auth_code: Option<String>, pub custom_data: Option<String>, pub fraud_details: Option<FraudDetails>, // NTID pub external_scheme_transaction_id: Option<Secret<String>>, pub session_token: Option<Secret<String>>, pub partial_approval: Option<NuveiPartialApproval>, //The ID of the transaction in the merchant’s system. pub client_unique_id: Option<String>, pub internal_request_id: Option<i64>, pub status: NuveiPaymentStatus, pub err_code: Option<i64>, pub reason: Option<String>, pub merchant_id: Option<Secret<String>>, pub merchant_site_id: Option<Secret<String>>, pub version: Option<String>, pub client_request_id: Option<String>, pub merchant_advice_code: Option<String>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiTxnPartialApproval { requested_amount: Option<StringMajorUnit>, requested_currency: Option<enums::Currency>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiTransactionSyncResponseDetails { gw_error_code: Option<i64>, gw_error_reason: Option<String>, gw_extended_error_code: Option<i64>, transaction_id: Option<String>, // Status of the payment transaction_status: Option<NuveiTransactionStatus>, transaction_type: Option<NuveiTransactionType>, auth_code: Option<String>, processed_amount: Option<StringMajorUnit>, processed_currency: Option<enums::Currency>, acquiring_bank_name: Option<String>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiTransactionSyncResponse { pub payment_option: Option<PaymentOption>, pub partial_approval: Option<NuveiTxnPartialApproval>, pub is_currency_converted: Option<bool>, pub transaction_details: Option<NuveiTransactionSyncResponseDetails>, pub fraud_details: Option<FraudDetails>, pub client_unique_id: Option<String>, pub internal_request_id: Option<i64>, // API response status pub status: NuveiPaymentStatus, pub err_code: Option<i64>, pub reason: Option<String>, pub merchant_id: Option<Secret<String>>, pub merchant_site_id: Option<Secret<String>>, pub version: Option<String>, pub client_request_id: Option<String>, pub merchant_advice_code: Option<String>, } impl NuveiTransactionSyncResponse { pub fn get_partial_approval(&self) -> Option<NuveiPartialApproval> { match &self.partial_approval { Some(partial_approval) => match ( partial_approval.requested_amount.clone(), partial_approval.requested_currency, self.transaction_details .as_ref() .and_then(|txn| txn.processed_amount.clone()), self.transaction_details .as_ref() .and_then(|txn| txn.processed_currency), ) { ( Some(requested_amount), Some(requested_currency), Some(processed_amount), Some(processed_currency), ) => Some(NuveiPartialApproval { requested_amount, requested_currency, processed_amount, processed_currency, }), _ => None, }, None => None, } } } pub fn get_amount_captured( partial_approval_data: Option<NuveiPartialApproval>, transaction_type: Option<NuveiTransactionType>, ) -> Result<(Option<i64>, Option<MinorUnit>), error_stack::Report<errors::ConnectorError>> { match partial_approval_data { Some(partial_approval) => { let amount = utils::convert_back_amount_to_minor_units( NUVEI_AMOUNT_CONVERTOR, partial_approval.processed_amount.clone(), partial_approval.processed_currency, )?; match transaction_type { None => Ok((None, None)), Some(NuveiTransactionType::Sale) => { Ok((Some(MinorUnit::get_amount_as_i64(amount)), None)) } Some(NuveiTransactionType::Auth) => Ok((None, Some(amount))), Some(NuveiTransactionType::Auth3D) => { Ok((Some(MinorUnit::get_amount_as_i64(amount)), None)) } Some(NuveiTransactionType::InitAuth3D) => Ok((None, Some(amount))), Some(NuveiTransactionType::Credit) => Ok((None, None)), Some(NuveiTransactionType::Void) => Ok((None, None)), Some(NuveiTransactionType::Settle) => Ok((None, None)), } } None => Ok((None, None)), } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum NuveiTransactionType { Auth, Sale, Credit, Auth3D, InitAuth3D, Settle, Void, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FraudDetails { pub final_decision: String, } fn get_payment_status( amount: Option<i64>, is_post_capture_void: bool, transaction_type: Option<NuveiTransactionType>, transaction_status: Option<NuveiTransactionStatus>, status: NuveiPaymentStatus, ) -> enums::AttemptStatus { // ZERO dollar authorization if amount == Some(0) && transaction_type == Some(NuveiTransactionType::Auth) { return match transaction_status { Some(NuveiTransactionStatus::Approved) => enums::AttemptStatus::Charged, Some(NuveiTransactionStatus::Declined) | Some(NuveiTransactionStatus::Error) => { enums::AttemptStatus::AuthorizationFailed } Some(NuveiTransactionStatus::Pending) | Some(NuveiTransactionStatus::Processing) => { enums::AttemptStatus::Pending } Some(NuveiTransactionStatus::Redirect) => enums::AttemptStatus::AuthenticationPending, None => match status { NuveiPaymentStatus::Failed | NuveiPaymentStatus::Error => { enums::AttemptStatus::Failure } _ => enums::AttemptStatus::Pending, }, }; } match transaction_status { Some(status) => match status { NuveiTransactionStatus::Approved => match transaction_type { Some(NuveiTransactionType::InitAuth3D) | Some(NuveiTransactionType::Auth) => { enums::AttemptStatus::Authorized } Some(NuveiTransactionType::Sale) | Some(NuveiTransactionType::Settle) => { enums::AttemptStatus::Charged } Some(NuveiTransactionType::Void) if is_post_capture_void => { enums::AttemptStatus::VoidedPostCharge } Some(NuveiTransactionType::Void) => enums::AttemptStatus::Voided, Some(NuveiTransactionType::Auth3D) => enums::AttemptStatus::AuthenticationPending, _ => enums::AttemptStatus::Pending, }, NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => { match transaction_type { Some(NuveiTransactionType::Auth) => enums::AttemptStatus::AuthorizationFailed, Some(NuveiTransactionType::Void) => enums::AttemptStatus::VoidFailed, Some(NuveiTransactionType::Auth3D) | Some(NuveiTransactionType::InitAuth3D) => { enums::AttemptStatus::AuthenticationFailed } _ => enums::AttemptStatus::Failure, } } NuveiTransactionStatus::Processing | NuveiTransactionStatus::Pending => { enums::AttemptStatus::Pending } NuveiTransactionStatus::Redirect => enums::AttemptStatus::AuthenticationPending, }, None => match status { NuveiPaymentStatus::Failed | NuveiPaymentStatus::Error => enums::AttemptStatus::Failure, _ => enums::AttemptStatus::Pending, }, } } #[derive(Debug)] struct ErrorResponseParams { http_code: u16, status: NuveiPaymentStatus, err_code: Option<i64>, err_msg: Option<String>, merchant_advice_code: Option<String>, gw_error_code: Option<i64>, gw_error_reason: Option<String>, transaction_status: Option<NuveiTransactionStatus>, transaction_id: Option<String>, } fn build_error_response(params: ErrorResponseParams) -> Option<ErrorResponse> { match params.status { NuveiPaymentStatus::Error => Some(get_error_response( params.err_code, params.err_msg.clone(), params.http_code, params.merchant_advice_code.clone(), params.gw_error_code.map(|code| code.to_string()), params.gw_error_reason.clone(), params.transaction_id.clone(), )), _ => { let err = Some(get_error_response( params.gw_error_code, params.gw_error_reason.clone(), params.http_code, params.merchant_advice_code, params.gw_error_code.map(|e| e.to_string()), params.gw_error_reason.clone(), params.transaction_id.clone(), )); match params.transaction_status { Some(NuveiTransactionStatus::Error) | Some(NuveiTransactionStatus::Declined) => err, _ => match params .gw_error_reason .as_ref() .map(|r| r.eq("Missing argument")) { Some(true) => err, _ => None, }, } } } } pub trait NuveiPaymentsGenericResponse { fn is_post_capture_void() -> bool { false } } impl NuveiPaymentsGenericResponse for CompleteAuthorize {} impl NuveiPaymentsGenericResponse for Void {} impl NuveiPaymentsGenericResponse for PSync {} impl NuveiPaymentsGenericResponse for Capture {} impl NuveiPaymentsGenericResponse for PostCaptureVoid { fn is_post_capture_void() -> bool { true } } impl TryFrom< ResponseRouterData< SetupMandate, NuveiPaymentsResponse, SetupMandateRequestData, PaymentsResponseData, >, > for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< SetupMandate, NuveiPaymentsResponse, SetupMandateRequestData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let amount = item.data.request.amount; let response = &item.response; let (status, redirection_data, connector_response_data) = process_nuvei_payment_response( NuveiPaymentResponseData::new(amount, false, item.data.payment_method, response), )?; let (amount_captured, minor_amount_capturable) = get_amount_captured( response.partial_approval.clone(), response.transaction_type.clone(), )?; let ip_address = item .data .request .browser_info .as_ref() .ok_or_else(|| errors::ConnectorError::MissingRequiredField { field_name: "browser_info", })? .ip_address .as_ref() .ok_or_else(|| errors::ConnectorError::MissingRequiredField { field_name: "browser_info.ip_address", })? .to_string(); let response = &item.response; Ok(Self { status, response: if let Some(err) = build_error_response(ErrorResponseParams { http_code: item.http_code, status: response.status.clone(), err_code: response.err_code, err_msg: response.reason.clone(), merchant_advice_code: response.merchant_advice_code.clone(), gw_error_code: response.gw_error_code, gw_error_reason: response.gw_error_reason.clone(), transaction_status: response.transaction_status.clone(), transaction_id: response.transaction_id.clone(), }) { Err(err) } else { let response = &item.response; Ok(create_transaction_response( redirection_data, Some(ip_address), response.transaction_id.clone(), response.order_id.clone(), response.session_token.clone(), response.external_scheme_transaction_id.clone(), response.payment_option.clone(), )?) }, amount_captured, minor_amount_capturable, connector_response: connector_response_data, ..item.data }) } } // Helper function to process Nuvei payment response /// Struct to encapsulate parameters for processing Nuvei payment responses #[derive(Debug)] pub struct NuveiPaymentResponseData { pub amount: Option<i64>, pub is_post_capture_void: bool, pub payment_method: enums::PaymentMethod, pub payment_option: Option<PaymentOption>, pub transaction_type: Option<NuveiTransactionType>, pub transaction_status: Option<NuveiTransactionStatus>, pub status: NuveiPaymentStatus, pub merchant_advice_code: Option<String>, } impl NuveiPaymentResponseData { pub fn new( amount: Option<i64>, is_post_capture_void: bool, payment_method: enums::PaymentMethod, response: &NuveiPaymentsResponse, ) -> Self { Self { amount, is_post_capture_void, payment_method, payment_option: response.payment_option.clone(), transaction_type: response.transaction_type.clone(), transaction_status: response.transaction_status.clone(), status: response.status.clone(), merchant_advice_code: response.merchant_advice_code.clone(), } } pub fn new_from_sync_response( amount: Option<i64>, is_post_capture_void: bool, payment_method: enums::PaymentMethod, response: &NuveiTransactionSyncResponse, ) -> Self { let transaction_details = &response.transaction_details; Self { amount, is_post_capture_void, payment_method, payment_option: response.payment_option.clone(), transaction_type: transaction_details .as_ref() .and_then(|details| details.transaction_type.clone()), transaction_status: transaction_details .as_ref() .and_then(|details| details.transaction_status.clone()), status: response.status.clone(), merchant_advice_code: None, } } } fn process_nuvei_payment_response( data: NuveiPaymentResponseData, ) -> Result< ( enums::AttemptStatus, Option<RedirectForm>, Option<ConnectorResponseData>, ), error_stack::Report<errors::ConnectorError>, > { let redirection_data = match data.payment_method { enums::PaymentMethod::Wallet | enums::PaymentMethod::BankRedirect => data .payment_option .as_ref() .and_then(|po| po.redirect_url.clone()) .map(|base_url| RedirectForm::from((base_url, Method::Get))), _ => data .payment_option .as_ref() .and_then(|o| o.card.clone()) .and_then(|card| card.three_d) .and_then(|three_ds| three_ds.acs_url.zip(three_ds.c_req)) .map(|(base_url, creq)| RedirectForm::Form { endpoint: base_url, method: Method::Post, form_fields: std::collections::HashMap::from([("creq".to_string(), creq.expose())]), }), }; let connector_response_data = convert_to_additional_payment_method_connector_response(data.payment_option.clone()) .map(ConnectorResponseData::with_additional_payment_method_data); let status = get_payment_status( data.amount, data.is_post_capture_void, data.transaction_type, data.transaction_status, data.status, ); Ok((status, redirection_data, connector_response_data)) } // Helper function to create transaction response fn create_transaction_response( redirection_data: Option<RedirectForm>, ip_address: Option<String>, transaction_id: Option<String>, order_id: Option<String>, session_token: Option<Secret<String>>, external_scheme_transaction_id: Option<Secret<String>>, payment_option: Option<PaymentOption>, ) -> Result<PaymentsResponseData, error_stack::Report<errors::ConnectorError>> { Ok(PaymentsResponseData::TransactionResponse { resource_id: transaction_id .clone() .map_or(order_id.clone(), Some) // For paypal there will be no transaction_id, only order_id will be present .map(ResponseId::ConnectorTransactionId) .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, redirection_data: Box::new(redirection_data), mandate_reference: Box::new( payment_option .as_ref() .and_then(|po| po.user_payment_option_id.clone()) .map(|id| MandateReference { connector_mandate_id: Some(id), payment_method_id: None, mandate_metadata: ip_address .map(|ip| pii::SecretSerdeValue::new(serde_json::Value::String(ip))), connector_mandate_request_reference_id: None, }), ), // we don't need to save session token for capture, void flow so ignoring if it is not present connector_metadata: if let Some(token) = session_token { Some( serde_json::to_value(NuveiMeta { session_token: token, }) .change_context(errors::ConnectorError::ResponseHandlingFailed)?, ) } else { None }, network_txn_id: external_scheme_transaction_id .as_ref() .map(|ntid| ntid.clone().expose()), connector_response_reference_id: order_id.clone(), incremental_authorization_allowed: None, charges: None, }) } // Specialized implementation for Authorize impl TryFrom< ResponseRouterData< Authorize, NuveiPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Authorize, NuveiPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { // Get amount directly from the authorize data let amount = Some(item.data.request.amount); let response = &item.response; let (status, redirection_data, connector_response_data) = process_nuvei_payment_response( NuveiPaymentResponseData::new(amount, false, item.data.payment_method, response), )?; let (amount_captured, minor_amount_capturable) = get_amount_captured( response.partial_approval.clone(), response.transaction_type.clone(), )?; let ip_address = item .data .request .browser_info .clone() .and_then(|browser_info| browser_info.ip_address.map(|ip| ip.to_string())); Ok(Self { status, response: if let Some(err) = build_error_response(ErrorResponseParams { http_code: item.http_code, status: response.status.clone(), err_code: response.err_code, err_msg: response.reason.clone(), merchant_advice_code: response.merchant_advice_code.clone(), gw_error_code: response.gw_error_code, gw_error_reason: response.gw_error_reason.clone(), transaction_status: response.transaction_status.clone(), transaction_id: response.transaction_id.clone(), }) { Err(err) } else { let response = &item.response; Ok(create_transaction_response( redirection_data, ip_address, response.transaction_id.clone(), response.order_id.clone(), response.session_token.clone(), response.external_scheme_transaction_id.clone(), response.payment_option.clone(), )?) }, amount_captured, minor_amount_capturable, connector_response: connector_response_data, ..item.data }) } } // Generic implementation for other flow types impl<F, T> TryFrom<ResponseRouterData<F, NuveiPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> where F: NuveiPaymentsGenericResponse + std::fmt::Debug, T: std::fmt::Debug, F: std::any::Any, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, NuveiPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let amount = item .data .minor_amount_capturable .map(|amount| amount.get_amount_as_i64()); let response = &item.response; let (status, redirection_data, connector_response_data) = process_nuvei_payment_response(NuveiPaymentResponseData::new( amount, F::is_post_capture_void(), item.data.payment_method, response, ))?; let (amount_captured, minor_amount_capturable) = get_amount_captured( response.partial_approval.clone(), response.transaction_type.clone(), )?; Ok(Self { status, response: if let Some(err) = build_error_response(ErrorResponseParams { http_code: item.http_code, status: response.status.clone(), err_code: response.err_code, err_msg: response.reason.clone(), merchant_advice_code: response.merchant_advice_code.clone(), gw_error_code: response.gw_error_code, gw_error_reason: response.gw_error_reason.clone(), transaction_status: response.transaction_status.clone(), transaction_id: response.transaction_id.clone(), }) { Err(err) } else { let response = &item.response; Ok(create_transaction_response( redirection_data, None, response.transaction_id.clone(), response.order_id.clone(), response.session_token.clone(), response.external_scheme_transaction_id.clone(), response.payment_option.clone(), )?) }, amount_captured, minor_amount_capturable, connector_response: connector_response_data, ..item.data }) } } // Generic implementation for other flow types impl<F, T> TryFrom<ResponseRouterData<F, NuveiTransactionSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> where F: NuveiPaymentsGenericResponse + std::fmt::Debug, T: std::fmt::Debug, F: std::any::Any, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, NuveiTransactionSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let amount = item .data .minor_amount_capturable .map(|amount| amount.get_amount_as_i64()); let response = &item.response; let transaction_details = &response.transaction_details; let transaction_type = transaction_details .as_ref() .and_then(|details| details.transaction_type.clone()); let (status, redirection_data, connector_response_data) = process_nuvei_payment_response(NuveiPaymentResponseData::new_from_sync_response( amount, F::is_post_capture_void(), item.data.payment_method, response, ))?; let (amount_captured, minor_amount_capturable) = get_amount_captured(response.get_partial_approval(), transaction_type.clone())?; Ok(Self { status, response: if let Some(err) = build_error_response(ErrorResponseParams { http_code: item.http_code, status: response.status.clone(), err_code: response.err_code, err_msg: response.reason.clone(), merchant_advice_code: None, gw_error_code: transaction_details .as_ref() .and_then(|details| details.gw_error_code), gw_error_reason: transaction_details .as_ref() .and_then(|details| details.gw_error_reason.clone()), transaction_status: transaction_details .as_ref() .and_then(|details| details.transaction_status.clone()), transaction_id: transaction_details .as_ref() .and_then(|details| details.transaction_id.clone()), }) { Err(err) } else { Ok(create_transaction_response( redirection_data, None, transaction_details .as_ref() .and_then(|data| data.transaction_id.clone()), None, None, None, response.payment_option.clone(), )?) }, amount_captured, minor_amount_capturable, connector_response: connector_response_data, ..item.data }) } } impl TryFrom<PaymentsPreprocessingResponseRouterData<NuveiPaymentsResponse>> for types::PaymentsPreProcessingRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: PaymentsPreprocessingResponseRouterData<NuveiPaymentsResponse>, ) -> Result<Self, Self::Error> { let response = item.response; let is_enrolled_for_3ds = response .clone() .payment_option .and_then(|po| po.card) .and_then(|c| c.three_d) .and_then(|t| t.v2supported) .map(to_boolean) .unwrap_or_default(); Ok(Self { status: get_payment_status( item.data.request.amount, false, response.transaction_type, response.transaction_status, response.status, ), response: Ok(PaymentsResponseData::ThreeDSEnrollmentResponse { enrolled_v2: is_enrolled_for_3ds, related_transaction_id: response.transaction_id, }), ..item.data }) } } impl From<NuveiTransactionStatus> for enums::RefundStatus { fn from(item: NuveiTransactionStatus) -> Self { match item { NuveiTransactionStatus::Approved => Self::Success, NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => Self::Failure, NuveiTransactionStatus::Processing | NuveiTransactionStatus::Pending | NuveiTransactionStatus::Redirect => Self::Pending, } } } impl TryFrom<RefundsResponseRouterData<Execute, NuveiPaymentsResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, NuveiPaymentsResponse>, ) -> Result<Self, Self::Error> { let transaction_id = item .response .transaction_id .clone() .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?; let refund_response = get_refund_response(item.response.clone(), item.http_code, transaction_id); Ok(Self { response: refund_response.map_err(|err| *err), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, NuveiTransactionSyncResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, NuveiTransactionSyncResponse>, ) -> Result<Self, Self::Error> { let txn_id = item .response .transaction_details .as_ref() .and_then(|details| details.transaction_id.clone()) .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?; let refund_status = item .response .transaction_details .as_ref() .and_then(|details| details.transaction_status.clone()) .map(enums::RefundStatus::from) .unwrap_or(enums::RefundStatus::Failure); let network_decline_code = item .response .transaction_details .as_ref() .and_then(|details| details.gw_error_code.map(|e| e.to_string())); let network_error_msg = item .response .transaction_details .as_ref() .and_then(|details| details.gw_error_reason.clone()); let refund_response = match item.response.status { NuveiPaymentStatus::Error => Err(Box::new(get_error_response( item.response.err_code, item.response.reason.clone(), item.http_code, item.response.merchant_advice_code, network_decline_code, network_error_msg, Some(txn_id.clone()), ))), _ => match item .response .transaction_details .and_then(|nuvei_response| nuvei_response.transaction_status) { Some(NuveiTransactionStatus::Error) => Err(Box::new(get_error_response( item.response.err_code, item.response.reason, item.http_code, item.response.merchant_advice_code, network_decline_code, network_error_msg, Some(txn_id.clone()), ))), _ => Ok(RefundsResponseData { connector_refund_id: txn_id, refund_status, }), }, }; Ok(Self { response: refund_response.map_err(|err| *err), ..item.data }) } } impl<F, Req> TryFrom<&RouterData<F, Req, PaymentsResponseData>> for NuveiPaymentsRequest where Req: NuveiAuthorizePreprocessingCommon, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(data: &RouterData<F, Req, PaymentsResponseData>) -> Result<Self, Self::Error> { { let item = data; let connector_mandate_id = &item.request.get_connector_mandate_id(); let customer_id = item .request .get_customer_id_optional() .ok_or(missing_field_err("customer_id")())?; let related_transaction_id = item.request.get_related_transaction_id().clone(); let ip_address = data .recurring_mandate_payment_data .as_ref() .and_then(|r| r.mandate_metadata.as_ref()) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "browser_info.ip_address", })? .clone() .expose() .as_str() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "browser_info.ip_address", })? .to_owned(); Ok(Self { related_transaction_id, device_details: DeviceDetails { ip_address: Secret::new(ip_address), }, is_rebilling: Some(IsRebilling::True), // In case of second installment, rebilling should be 1 user_token_id: Some(customer_id), payment_option: PaymentOption { user_payment_option_id: connector_mandate_id.clone(), ..Default::default() }, ..Default::default() }) } } } impl ForeignTryFrom<&Option<BrowserInformation>> for DeviceDetails { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(browser_info: &Option<BrowserInformation>) -> Result<Self, Self::Error> { let browser_info = browser_info .as_ref() .ok_or_else(missing_field_err("browser_info"))?; Ok(Self { ip_address: browser_info.get_ip_address()?, }) } } fn get_refund_response( response: NuveiPaymentsResponse, http_code: u16, txn_id: String, ) -> Result<RefundsResponseData, Box<ErrorResponse>> { let refund_status = response .transaction_status .clone() .map(enums::RefundStatus::from) .unwrap_or(enums::RefundStatus::Failure); match response.status { NuveiPaymentStatus::Error => Err(Box::new(get_error_response( response.err_code, response.reason.clone(), http_code, response.merchant_advice_code, response.gw_error_code.map(|e| e.to_string()), response.gw_error_reason, Some(txn_id.clone()), ))), _ => match response.transaction_status { Some(NuveiTransactionStatus::Error) => Err(Box::new(get_error_response( response.err_code, response.reason, http_code, response.merchant_advice_code, response.gw_error_code.map(|e| e.to_string()), response.gw_error_reason, Some(txn_id.clone()), ))), _ => Ok(RefundsResponseData { connector_refund_id: txn_id, refund_status, }), }, } } fn get_error_response( error_code: Option<i64>, error_msg: Option<String>, http_code: u16, network_advice_code: Option<String>, network_decline_code: Option<String>, network_error_message: Option<String>, transaction_id: Option<String>, ) -> ErrorResponse { ErrorResponse { code: error_code .map(|c| c.to_string()) .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: error_msg .clone() .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: None, status_code: http_code, attempt_status: None, connector_transaction_id: transaction_id, network_advice_code: network_advice_code.clone(), network_decline_code: network_decline_code.clone(), network_error_message: network_error_message.clone(), connector_metadata: None, } } /// Represents any possible webhook notification from Nuvei. #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum NuveiWebhook { PaymentDmn(PaymentDmnNotification), Chargeback(ChargebackNotification), } /// Represents Psync Response from Nuvei. #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum NuveiPaymentSyncResponse { NuveiDmn(Box<PaymentDmnNotification>), NuveiApi(Box<NuveiTransactionSyncResponse>), } /// Represents the status of a chargeback event. #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] pub enum ChargebackStatus { RetrievalRequest, Chargeback, Representment, SecondChargeback, Arbitration, #[serde(other)] Unknown, } /// Represents a Chargeback webhook notification from the Nuvei Control Panel. #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ChargebackNotification { pub client_id: Option<i64>, pub client_name: Option<String>, pub event_date_u_t_c: Option<String>, pub event_correlation_id: Option<String>, pub chargeback: ChargebackData, pub transaction_details: ChargebackTransactionDetails, pub event_id: Option<String>, pub event_date: Option<String>, pub processing_entity_type: Option<String>, pub processing_entity_id: Option<i64>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct ChargebackData { pub date: Option<time::PrimitiveDateTime>, pub chargeback_status_category: ChargebackStatusCategory, #[serde(rename = "Type")] pub webhook_type: ChargebackType, pub status: Option<String>, pub amount: FloatMajorUnit, pub currency: String, pub reported_amount: FloatMajorUnit, pub reported_currency: String, pub chargeback_reason: Option<String>, pub chargeback_reason_category: Option<String>, pub reason_message: Option<String>, pub dispute_id: Option<String>, pub dispute_due_date: Option<time::PrimitiveDateTime>, pub dispute_event_id: Option<i64>, pub dispute_unified_status_code: Option<DisputeUnifiedStatusCode>, } #[derive(Debug, Clone, Serialize, Deserialize, strum::Display)] pub enum DisputeUnifiedStatusCode { #[serde(rename = "FC")] FirstChargebackInitiatedByIssuer, #[serde(rename = "CC")] CreditChargebackInitiatedByIssuer, #[serde(rename = "CC-A-ACPT")] CreditChargebackAcceptedAutomatically, #[serde(rename = "FC-A-EPRD")] FirstChargebackNoResponseExpired, #[serde(rename = "FC-M-ACPT")] FirstChargebackAcceptedByMerchant, #[serde(rename = "FC-A-ACPT")] FirstChargebackAcceptedAutomatically, #[serde(rename = "FC-A-ACPT-MCOLL")] FirstChargebackAcceptedAutomaticallyMcoll, #[serde(rename = "FC-M-PART")] FirstChargebackPartiallyAcceptedByMerchant, #[serde(rename = "FC-M-PART-EXP")] FirstChargebackPartiallyAcceptedByMerchantExpired, #[serde(rename = "FC-M-RJCT")] FirstChargebackRejectedByMerchant, #[serde(rename = "FC-M-RJCT-EXP")] FirstChargebackRejectedByMerchantExpired, #[serde(rename = "FC-A-RJCT")] FirstChargebackRejectedAutomatically, #[serde(rename = "FC-A-RJCT-EXP")] FirstChargebackRejectedAutomaticallyExpired, #[serde(rename = "IPA")] PreArbitrationInitiatedByIssuer, #[serde(rename = "MPA-I-ACPT")] MerchantPreArbitrationAcceptedByIssuer, #[serde(rename = "MPA-I-RJCT")] MerchantPreArbitrationRejectedByIssuer, #[serde(rename = "MPA-I-PART")] MerchantPreArbitrationPartiallyAcceptedByIssuer, #[serde(rename = "FC-CLSD-MF")] FirstChargebackClosedMerchantFavour, #[serde(rename = "FC-CLSD-CHF")] FirstChargebackClosedCardholderFavour, #[serde(rename = "FC-CLSD-RCL")] FirstChargebackClosedRecall, #[serde(rename = "FC-I-RCL")] FirstChargebackRecalledByIssuer, #[serde(rename = "PA-CLSD-MF")] PreArbitrationClosedMerchantFavour, #[serde(rename = "PA-CLSD-CHF")] PreArbitrationClosedCardholderFavour, #[serde(rename = "RDR")] Rdr, #[serde(rename = "FC-SPCSE")] FirstChargebackDisputeResponseNotAllowed, #[serde(rename = "MCC")] McCollaborationInitiatedByIssuer, #[serde(rename = "MCC-A-RJCT")] McCollaborationPreviouslyRefundedAuto, #[serde(rename = "MCC-M-ACPT")] McCollaborationRefundedByMerchant, #[serde(rename = "MCC-EXPR")] McCollaborationExpired, #[serde(rename = "MCC-M-RJCT")] McCollaborationRejectedByMerchant, #[serde(rename = "MCC-A-ACPT")] McCollaborationAutomaticAccept, #[serde(rename = "MCC-CLSD-MF")] McCollaborationClosedMerchantFavour, #[serde(rename = "MCC-CLSD-CHF")] McCollaborationClosedCardholderFavour, #[serde(rename = "INQ")] InquiryInitiatedByIssuer, #[serde(rename = "INQ-M-RSP")] InquiryRespondedByMerchant, #[serde(rename = "INQ-EXPR")] InquiryExpired, #[serde(rename = "INQ-A-RJCT")] InquiryAutomaticallyRejected, #[serde(rename = "INQ-A-CNLD")] InquiryCancelledAfterRefund, #[serde(rename = "INQ-M-RFND")] InquiryAcceptedFullRefund, #[serde(rename = "INQ-M-P-RFND")] InquiryPartialAcceptedPartialRefund, #[serde(rename = "INQ-UPD")] InquiryUpdated, #[serde(rename = "IPA-M-ACPT")] PreArbitrationAcceptedByMerchant, #[serde(rename = "IPA-M-PART")] PreArbitrationPartiallyAcceptedByMerchant, #[serde(rename = "IPA-M-PART-EXP")] PreArbitrationPartiallyAcceptedByMerchantExpired, #[serde(rename = "IPA-M-RJCT")] PreArbitrationRejectedByMerchant, #[serde(rename = "IPA-M-RJCT-EXP")] PreArbitrationRejectedByMerchantExpired, #[serde(rename = "IPA-A-ACPT")] PreArbitrationAutomaticallyAcceptedByMerchant, #[serde(rename = "PA-CLSD-RC")] PreArbitrationClosedRecall, #[serde(rename = "IPAR-M-ACPT")] RejectedPreArbAcceptedByMerchant, #[serde(rename = "IPAR-A-ACPT")] RejectedPreArbExpiredAutoAccepted, #[serde(rename = "CC-I-RCLL")] CreditChargebackRecalledByIssuer, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct ChargebackTransactionDetails { pub transaction_id: i64, pub transaction_date: Option<String>, pub client_unique_id: Option<String>, pub acquirer_name: Option<String>, pub masked_card_number: Option<String>, pub arn: Option<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub enum ChargebackType { Chargeback, Retrieval, } #[derive(Debug, Serialize, Deserialize)] pub enum ChargebackStatusCategory { #[serde(rename = "Regular")] Regular, #[serde(rename = "cancelled")] Cancelled, #[serde(rename = "Duplicate")] Duplicate, #[serde(rename = "RDR-Refund")] RdrRefund, #[serde(rename = "Soft_CB")] SoftCb, } /// Represents the overall status of the DMN. #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "UPPERCASE")] pub enum DmnStatus { Success, Approved, Error, Pending, Declined, } /// Represents the transaction status of the DMN #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "UPPERCASE")] pub enum DmnApiTransactionStatus { Ok, Fail, Pending, } /// Represents the status of the transaction itself. #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "UPPERCASE")] pub enum TransactionStatus { Approved, Declined, Error, Cancelled, Pending, #[serde(rename = "Settle")] Settled, } /// Represents a Payment Direct Merchant Notification (DMN) webhook. #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentDmnNotification { // Status of the Api transaction #[serde(rename = "ppp_status")] pub ppp_status: DmnApiTransactionStatus, #[serde(rename = "PPP_TransactionID")] pub ppp_transaction_id: String, pub total_amount: String, pub currency: String, #[serde(rename = "TransactionID")] pub transaction_id: Option<String>, // Status of the Payment #[serde(rename = "Status")] pub status: Option<DmnStatus>, pub transaction_type: Option<NuveiTransactionType>, #[serde(rename = "ErrCode")] pub err_code: Option<String>, #[serde(rename = "Reason")] pub reason: Option<String>, #[serde(rename = "ReasonCode")] pub reason_code: Option<String>, #[serde(rename = "user_token_id")] pub user_token_id: Option<String>, #[serde(rename = "payment_method")] pub payment_method: Option<String>, #[serde(rename = "responseTimeStamp")] pub response_time_stamp: String, #[serde(rename = "invoice_id")] pub invoice_id: Option<String>, #[serde(rename = "merchant_id")] pub merchant_id: Option<Secret<String>>, #[serde(rename = "merchant_site_id")] pub merchant_site_id: Option<Secret<String>>, #[serde(rename = "responsechecksum")] pub response_checksum: Option<String>, #[serde(rename = "advanceResponseChecksum")] pub advance_response_checksum: Option<String>, pub product_id: Option<String>, pub merchant_advice_code: Option<String>, #[serde(rename = "AuthCode")] pub auth_code: Option<String>, pub acquirer_bank: Option<String>, pub client_request_id: Option<String>, } // For backward compatibility with existing code #[derive(Debug, Default, Serialize, Deserialize)] pub struct NuveiWebhookTransactionId { #[serde(rename = "ppp_TransactionID")] pub ppp_transaction_id: String, } // Convert webhook to payments response for further processing impl From<PaymentDmnNotification> for NuveiTransactionSyncResponse { fn from(notification: PaymentDmnNotification) -> Self { Self { status: match notification.ppp_status { DmnApiTransactionStatus::Ok => NuveiPaymentStatus::Success, DmnApiTransactionStatus::Fail => NuveiPaymentStatus::Failed, DmnApiTransactionStatus::Pending => NuveiPaymentStatus::Processing, }, err_code: notification .err_code .and_then(|code| code.parse::<i64>().ok()), reason: notification.reason.clone(), transaction_details: Some(NuveiTransactionSyncResponseDetails { gw_error_code: notification .reason_code .and_then(|code| code.parse::<i64>().ok()), gw_error_reason: notification.reason.clone(), gw_extended_error_code: None, transaction_id: notification.transaction_id, transaction_status: notification.status.map(|ts| match ts { DmnStatus::Success | DmnStatus::Approved => NuveiTransactionStatus::Approved, DmnStatus::Declined => NuveiTransactionStatus::Declined, DmnStatus::Pending => NuveiTransactionStatus::Pending, DmnStatus::Error => NuveiTransactionStatus::Error, }), transaction_type: notification.transaction_type, auth_code: notification.auth_code, processed_amount: None, processed_currency: None, acquiring_bank_name: notification.acquirer_bank, }), merchant_id: notification.merchant_id, merchant_site_id: notification.merchant_site_id, merchant_advice_code: notification.merchant_advice_code, ..Default::default() } } } fn get_cvv2_response_description(code: &str) -> Option<&str> { match code { "M" => Some("CVV2 Match"), "N" => Some("CVV2 No Match"), "P" => Some("Not Processed. For EU card-on-file (COF) and ecommerce (ECOM) network token transactions, Visa removes any CVV and sends P. If you have fraud or security concerns, Visa recommends using 3DS."), "U" => Some("Issuer is not certified and/or has not provided Visa the encryption keys"), "S" => Some("CVV2 processor is unavailable."), _=> None, } } fn get_avs_response_description(code: &str) -> Option<&str> { match code { "A" => Some("The street address matches, the ZIP code does not."), "W" => Some("Postal code matches, the street address does not."), "Y" => Some("Postal code and the street address match."), "X" => Some("An exact match of both the 9-digit ZIP code and the street address."), "Z" => Some("Postal code matches, the street code does not."), "U" => Some("Issuer is unavailable."), "S" => Some("AVS not supported by issuer."), "R" => Some("Retry."), "B" => Some("Not authorized (declined)."), "N" => Some("Both the street address and postal code do not match."), _ => None, } } /// Concatenates a vector of strings without any separator /// This is useful for creating verification messages for webhooks pub fn concat_strings(strings: &[String]) -> String { strings.join("") } fn convert_to_additional_payment_method_connector_response( payment_option: Option<PaymentOption>, ) -> Option<AdditionalPaymentMethodConnectorResponse> { let card = payment_option.as_ref()?.card.as_ref()?; let avs_code = card.avs_code.as_ref(); let cvv2_code = card.cvv2_reply.as_ref(); let avs_description = avs_code.and_then(|code| get_avs_response_description(code)); let cvv_description = cvv2_code.and_then(|code| get_cvv2_response_description(code)); let payment_checks = serde_json::json!({ "avs_result": avs_code, "avs_description": avs_description, "card_validation_result": cvv2_code, "card_validation_description": cvv_description, }); let card_network = card.brand.clone(); let three_ds_data = card .three_d .clone() .map(|three_d| { serde_json::to_value(three_d) .map_err(|_| errors::ConnectorError::ResponseHandlingFailed) .attach_printable("threeDs encoding failed Nuvei") }) .transpose(); match three_ds_data { Ok(authentication_data) => Some(AdditionalPaymentMethodConnectorResponse::Card { authentication_data, payment_checks: Some(payment_checks), card_network, domestic_network: None, }), Err(_) => None, } } pub fn map_notification_to_event( status: DmnStatus, transaction_type: NuveiTransactionType, ) -> Result<api_models::webhooks::IncomingWebhookEvent, error_stack::Report<errors::ConnectorError>> { match (status, transaction_type) { (DmnStatus::Success | DmnStatus::Approved, NuveiTransactionType::Auth) => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess) } (DmnStatus::Success | DmnStatus::Approved, NuveiTransactionType::Sale) => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess) } (DmnStatus::Success | DmnStatus::Approved, NuveiTransactionType::Settle) => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentCaptureSuccess) } (DmnStatus::Success | DmnStatus::Approved, NuveiTransactionType::Void) => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentCancelled) } (DmnStatus::Success | DmnStatus::Approved, NuveiTransactionType::Credit) => { Ok(api_models::webhooks::IncomingWebhookEvent::RefundSuccess) } (DmnStatus::Error | DmnStatus::Declined, NuveiTransactionType::Auth) => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationFailure) } (DmnStatus::Error | DmnStatus::Declined, NuveiTransactionType::Sale) => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure) } (DmnStatus::Error | DmnStatus::Declined, NuveiTransactionType::Settle) => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentCaptureFailure) } (DmnStatus::Error | DmnStatus::Declined, NuveiTransactionType::Void) => { Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentCancelFailure) } (DmnStatus::Error | DmnStatus::Declined, NuveiTransactionType::Credit) => { Ok(api_models::webhooks::IncomingWebhookEvent::RefundFailure) } ( DmnStatus::Pending, NuveiTransactionType::Auth | NuveiTransactionType::Sale | NuveiTransactionType::Settle, ) => Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing), _ => Err(errors::ConnectorError::WebhookEventTypeNotFound.into()), } } #[cfg(feature = "payouts")] pub fn map_notification_to_event_for_payout( status: DmnStatus, transaction_type: NuveiTransactionType, ) -> Result<api_models::webhooks::IncomingWebhookEvent, error_stack::Report<errors::ConnectorError>> { match (status, transaction_type) { (DmnStatus::Success | DmnStatus::Approved, NuveiTransactionType::Credit) => { Ok(api_models::webhooks::IncomingWebhookEvent::PayoutSuccess) } (DmnStatus::Pending, _) => Ok(api_models::webhooks::IncomingWebhookEvent::PayoutProcessing), (DmnStatus::Declined | DmnStatus::Error, _) => { Ok(api_models::webhooks::IncomingWebhookEvent::PayoutFailure) } _ => Err(errors::ConnectorError::WebhookEventTypeNotFound.into()), } } pub fn map_dispute_notification_to_event( dispute_code: DisputeUnifiedStatusCode, ) -> Result<api_models::webhooks::IncomingWebhookEvent, error_stack::Report<errors::ConnectorError>> { match dispute_code { DisputeUnifiedStatusCode::FirstChargebackInitiatedByIssuer | DisputeUnifiedStatusCode::CreditChargebackInitiatedByIssuer | DisputeUnifiedStatusCode::McCollaborationInitiatedByIssuer | DisputeUnifiedStatusCode::FirstChargebackClosedRecall | DisputeUnifiedStatusCode::InquiryInitiatedByIssuer => { Ok(api_models::webhooks::IncomingWebhookEvent::DisputeOpened) } DisputeUnifiedStatusCode::CreditChargebackAcceptedAutomatically | DisputeUnifiedStatusCode::FirstChargebackAcceptedAutomatically | DisputeUnifiedStatusCode::FirstChargebackAcceptedAutomaticallyMcoll | DisputeUnifiedStatusCode::FirstChargebackAcceptedByMerchant | DisputeUnifiedStatusCode::FirstChargebackDisputeResponseNotAllowed | DisputeUnifiedStatusCode::Rdr | DisputeUnifiedStatusCode::McCollaborationRefundedByMerchant | DisputeUnifiedStatusCode::McCollaborationAutomaticAccept | DisputeUnifiedStatusCode::InquiryAcceptedFullRefund | DisputeUnifiedStatusCode::PreArbitrationAcceptedByMerchant | DisputeUnifiedStatusCode::PreArbitrationPartiallyAcceptedByMerchant | DisputeUnifiedStatusCode::PreArbitrationAutomaticallyAcceptedByMerchant | DisputeUnifiedStatusCode::RejectedPreArbAcceptedByMerchant | DisputeUnifiedStatusCode::RejectedPreArbExpiredAutoAccepted => { Ok(api_models::webhooks::IncomingWebhookEvent::DisputeAccepted) } DisputeUnifiedStatusCode::FirstChargebackNoResponseExpired | DisputeUnifiedStatusCode::FirstChargebackPartiallyAcceptedByMerchant | DisputeUnifiedStatusCode::FirstChargebackClosedCardholderFavour | DisputeUnifiedStatusCode::PreArbitrationClosedCardholderFavour | DisputeUnifiedStatusCode::McCollaborationClosedCardholderFavour => { Ok(api_models::webhooks::IncomingWebhookEvent::DisputeLost) } DisputeUnifiedStatusCode::FirstChargebackRejectedByMerchant | DisputeUnifiedStatusCode::FirstChargebackRejectedAutomatically | DisputeUnifiedStatusCode::PreArbitrationInitiatedByIssuer | DisputeUnifiedStatusCode::MerchantPreArbitrationRejectedByIssuer | DisputeUnifiedStatusCode::InquiryRespondedByMerchant | DisputeUnifiedStatusCode::PreArbitrationRejectedByMerchant => { Ok(api_models::webhooks::IncomingWebhookEvent::DisputeChallenged) } DisputeUnifiedStatusCode::FirstChargebackRejectedAutomaticallyExpired | DisputeUnifiedStatusCode::FirstChargebackPartiallyAcceptedByMerchantExpired | DisputeUnifiedStatusCode::FirstChargebackRejectedByMerchantExpired | DisputeUnifiedStatusCode::McCollaborationExpired | DisputeUnifiedStatusCode::InquiryExpired | DisputeUnifiedStatusCode::PreArbitrationPartiallyAcceptedByMerchantExpired | DisputeUnifiedStatusCode::PreArbitrationRejectedByMerchantExpired => { Ok(api_models::webhooks::IncomingWebhookEvent::DisputeExpired) } DisputeUnifiedStatusCode::MerchantPreArbitrationAcceptedByIssuer | DisputeUnifiedStatusCode::MerchantPreArbitrationPartiallyAcceptedByIssuer | DisputeUnifiedStatusCode::FirstChargebackClosedMerchantFavour | DisputeUnifiedStatusCode::McCollaborationClosedMerchantFavour | DisputeUnifiedStatusCode::PreArbitrationClosedMerchantFavour => { Ok(api_models::webhooks::IncomingWebhookEvent::DisputeWon) } DisputeUnifiedStatusCode::FirstChargebackRecalledByIssuer | DisputeUnifiedStatusCode::InquiryCancelledAfterRefund | DisputeUnifiedStatusCode::PreArbitrationClosedRecall | DisputeUnifiedStatusCode::CreditChargebackRecalledByIssuer => { Ok(api_models::webhooks::IncomingWebhookEvent::DisputeCancelled) } DisputeUnifiedStatusCode::McCollaborationPreviouslyRefundedAuto | DisputeUnifiedStatusCode::McCollaborationRejectedByMerchant | DisputeUnifiedStatusCode::InquiryAutomaticallyRejected | DisputeUnifiedStatusCode::InquiryPartialAcceptedPartialRefund | DisputeUnifiedStatusCode::InquiryUpdated => { Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) } } } impl From<DisputeUnifiedStatusCode> for common_enums::DisputeStage { fn from(code: DisputeUnifiedStatusCode) -> Self { match code { // --- PreDispute --- DisputeUnifiedStatusCode::Rdr | DisputeUnifiedStatusCode::InquiryInitiatedByIssuer | DisputeUnifiedStatusCode::InquiryRespondedByMerchant | DisputeUnifiedStatusCode::InquiryExpired | DisputeUnifiedStatusCode::InquiryAutomaticallyRejected | DisputeUnifiedStatusCode::InquiryCancelledAfterRefund | DisputeUnifiedStatusCode::InquiryAcceptedFullRefund | DisputeUnifiedStatusCode::InquiryPartialAcceptedPartialRefund | DisputeUnifiedStatusCode::InquiryUpdated => Self::PreDispute, // --- Dispute --- DisputeUnifiedStatusCode::FirstChargebackInitiatedByIssuer | DisputeUnifiedStatusCode::CreditChargebackInitiatedByIssuer | DisputeUnifiedStatusCode::FirstChargebackNoResponseExpired | DisputeUnifiedStatusCode::FirstChargebackAcceptedByMerchant | DisputeUnifiedStatusCode::FirstChargebackAcceptedAutomatically | DisputeUnifiedStatusCode::FirstChargebackAcceptedAutomaticallyMcoll | DisputeUnifiedStatusCode::FirstChargebackPartiallyAcceptedByMerchant | DisputeUnifiedStatusCode::FirstChargebackPartiallyAcceptedByMerchantExpired | DisputeUnifiedStatusCode::FirstChargebackRejectedByMerchant | DisputeUnifiedStatusCode::FirstChargebackRejectedByMerchantExpired | DisputeUnifiedStatusCode::FirstChargebackRejectedAutomatically | DisputeUnifiedStatusCode::FirstChargebackRejectedAutomaticallyExpired | DisputeUnifiedStatusCode::FirstChargebackClosedMerchantFavour | DisputeUnifiedStatusCode::FirstChargebackClosedCardholderFavour | DisputeUnifiedStatusCode::FirstChargebackClosedRecall | DisputeUnifiedStatusCode::FirstChargebackRecalledByIssuer | DisputeUnifiedStatusCode::FirstChargebackDisputeResponseNotAllowed | DisputeUnifiedStatusCode::McCollaborationInitiatedByIssuer | DisputeUnifiedStatusCode::McCollaborationPreviouslyRefundedAuto | DisputeUnifiedStatusCode::McCollaborationRefundedByMerchant | DisputeUnifiedStatusCode::McCollaborationExpired | DisputeUnifiedStatusCode::McCollaborationRejectedByMerchant | DisputeUnifiedStatusCode::McCollaborationAutomaticAccept | DisputeUnifiedStatusCode::McCollaborationClosedMerchantFavour | DisputeUnifiedStatusCode::McCollaborationClosedCardholderFavour | DisputeUnifiedStatusCode::CreditChargebackAcceptedAutomatically => Self::Dispute, // --- PreArbitration --- DisputeUnifiedStatusCode::PreArbitrationInitiatedByIssuer | DisputeUnifiedStatusCode::MerchantPreArbitrationAcceptedByIssuer | DisputeUnifiedStatusCode::MerchantPreArbitrationRejectedByIssuer | DisputeUnifiedStatusCode::MerchantPreArbitrationPartiallyAcceptedByIssuer | DisputeUnifiedStatusCode::PreArbitrationClosedMerchantFavour | DisputeUnifiedStatusCode::PreArbitrationClosedCardholderFavour | DisputeUnifiedStatusCode::PreArbitrationAcceptedByMerchant | DisputeUnifiedStatusCode::PreArbitrationPartiallyAcceptedByMerchant | DisputeUnifiedStatusCode::PreArbitrationPartiallyAcceptedByMerchantExpired | DisputeUnifiedStatusCode::PreArbitrationRejectedByMerchant | DisputeUnifiedStatusCode::PreArbitrationRejectedByMerchantExpired | DisputeUnifiedStatusCode::PreArbitrationAutomaticallyAcceptedByMerchant | DisputeUnifiedStatusCode::PreArbitrationClosedRecall | DisputeUnifiedStatusCode::RejectedPreArbAcceptedByMerchant | DisputeUnifiedStatusCode::RejectedPreArbExpiredAutoAccepted => Self::PreArbitration, // --- DisputeReversal --- DisputeUnifiedStatusCode::CreditChargebackRecalledByIssuer => Self::DisputeReversal, } } }
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
hyperswitch_connectors::src::connectors::nuvei::transformers
34,896
true
// File: crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs // Module: hyperswitch_connectors::src::connectors::nmi::transformers use api_models::webhooks::IncomingWebhookEvent; use cards::CardNumber; use common_enums::{AttemptStatus, AuthenticationType, CountryAlpha2, Currency, RefundStatus}; use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii::Email, types::FloatMajorUnit}; use error_stack::{report, Report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::{ ApplePayWalletData, Card, GooglePayWalletData, PaymentMethodData, WalletData, }, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ Authorize, Capture, CompleteAuthorize, Execute, PreProcessing, RSync, SetupMandate, Void, }, router_request_types::{ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsPreProcessingData, ResponseId, }, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, }, }; use hyperswitch_interfaces::errors::ConnectorError; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{PaymentsResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ get_unimplemented_payment_method_error_message, to_currency_base_unit_asf64, AddressDetailsData as _, CardData as _, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData as _, RouterData as _, }, }; type Error = Report<ConnectorError>; #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] pub enum TransactionType { Auth, Capture, Refund, Sale, Validate, Void, } pub struct NmiAuthType { pub(super) api_key: Secret<String>, pub(super) public_key: Option<Secret<String>>, } impl TryFrom<&ConnectorAuthType> for NmiAuthType { type Error = Error; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), public_key: None, }), ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.to_owned(), public_key: Some(key1.to_owned()), }), _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Serialize)] pub struct NmiRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for NmiRouterData<T> { fn from((amount, router_data): (FloatMajorUnit, T)) -> Self { Self { amount, router_data, } } } #[derive(Debug, Serialize)] pub struct NmiVaultRequest { security_key: Secret<String>, ccnumber: CardNumber, ccexp: Secret<String>, cvv: Secret<String>, first_name: Secret<String>, last_name: Secret<String>, address1: Option<Secret<String>>, address2: Option<Secret<String>>, city: Option<String>, state: Option<Secret<String>>, zip: Option<Secret<String>>, country: Option<CountryAlpha2>, customer_vault: CustomerAction, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum CustomerAction { AddCustomer, UpdateCustomer, } impl TryFrom<&PaymentsPreProcessingRouterData> for NmiVaultRequest { type Error = Error; fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; let (ccnumber, ccexp, cvv) = get_card_details(item.request.payment_method_data.clone())?; let billing_details = item.get_billing_address()?; let first_name = billing_details.get_first_name()?; Ok(Self { security_key: auth_type.api_key, ccnumber, ccexp, cvv, first_name: first_name.clone(), last_name: billing_details .get_last_name() .unwrap_or(first_name) .clone(), address1: billing_details.line1.clone(), address2: billing_details.line2.clone(), city: billing_details.city.clone(), state: billing_details.state.clone(), country: billing_details.country, zip: billing_details.zip.clone(), customer_vault: CustomerAction::AddCustomer, }) } } fn get_card_details( payment_method_data: Option<PaymentMethodData>, ) -> CustomResult<(CardNumber, Secret<String>, Secret<String>), ConnectorError> { match payment_method_data { Some(PaymentMethodData::Card(ref card_details)) => Ok(( card_details.card_number.clone(), card_details.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?, card_details.card_cvc.clone(), )), _ => Err( ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message("Nmi")) .into(), ), } } #[derive(Debug, Deserialize, Serialize)] pub struct NmiVaultResponse { pub response: Response, pub responsetext: String, pub customer_vault_id: Option<Secret<String>>, pub response_code: String, pub transactionid: String, } impl TryFrom< ResponseRouterData< PreProcessing, NmiVaultResponse, PaymentsPreProcessingData, PaymentsResponseData, >, > for PaymentsPreProcessingRouterData { type Error = Error; fn try_from( item: ResponseRouterData< PreProcessing, NmiVaultResponse, PaymentsPreProcessingData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.data.connector_auth_type).try_into()?; let amount_data = item .data .request .amount .ok_or(ConnectorError::MissingRequiredField { field_name: "amount", })?; let currency_data = item.data .request .currency .ok_or(ConnectorError::MissingRequiredField { field_name: "currency", })?; let (response, status) = match item.response.response { Response::Approved => ( Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(Some(RedirectForm::Nmi { amount: to_currency_base_unit_asf64(amount_data, currency_data.to_owned())? .to_string(), currency: currency_data, customer_vault_id: item .response .customer_vault_id .ok_or(ConnectorError::MissingRequiredField { field_name: "customer_vault_id", })? .peek() .to_string(), public_key: auth_type.public_key.ok_or( ConnectorError::InvalidConnectorConfig { config: "public_key", }, )?, order_id: item.data.connector_request_reference_id.clone(), })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.transactionid), incremental_authorization_allowed: None, charges: None, }), AttemptStatus::AuthenticationPending, ), Response::Declined | Response::Error => ( Err(ErrorResponse { code: item.response.response_code, message: item.response.responsetext.to_owned(), reason: Some(item.response.responsetext), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transactionid), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), AttemptStatus::Failure, ), }; Ok(Self { status, response, ..item.data }) } } #[derive(Debug, Serialize)] pub struct NmiCompleteRequest { amount: FloatMajorUnit, #[serde(rename = "type")] transaction_type: TransactionType, security_key: Secret<String>, orderid: Option<String>, customer_vault_id: Secret<String>, email: Option<Email>, cardholder_auth: Option<String>, cavv: Option<String>, xid: Option<String>, eci: Option<String>, cvv: Secret<String>, three_ds_version: Option<String>, directory_server_id: Option<Secret<String>>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] #[serde(untagged)] pub enum NmiRedirectResponse { NmiRedirectResponseData(NmiRedirectResponseData), NmiErrorResponseData(NmiErrorResponseData), } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NmiErrorResponseData { pub code: String, pub message: String, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NmiRedirectResponseData { cavv: Option<String>, xid: Option<String>, eci: Option<String>, card_holder_auth: Option<String>, three_ds_version: Option<String>, order_id: Option<String>, directory_server_id: Option<Secret<String>>, customer_vault_id: Secret<String>, } impl TryFrom<&NmiRouterData<&PaymentsCompleteAuthorizeRouterData>> for NmiCompleteRequest { type Error = Error; fn try_from( item: &NmiRouterData<&PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let transaction_type = match item.router_data.request.is_auto_capture()? { true => TransactionType::Sale, false => TransactionType::Auth, }; let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?; let payload_data = item .router_data .request .get_redirect_response_payload()? .expose(); let three_ds_data: NmiRedirectResponseData = serde_json::from_value(payload_data) .change_context(ConnectorError::MissingConnectorRedirectionPayload { field_name: "three_ds_data", })?; let (_, _, cvv) = get_card_details(item.router_data.request.payment_method_data.clone())?; Ok(Self { amount: item.amount, transaction_type, security_key: auth_type.api_key, orderid: three_ds_data.order_id, customer_vault_id: three_ds_data.customer_vault_id, email: item.router_data.request.email.clone(), cvv, cardholder_auth: three_ds_data.card_holder_auth, cavv: three_ds_data.cavv, xid: three_ds_data.xid, eci: three_ds_data.eci, three_ds_version: three_ds_data.three_ds_version, directory_server_id: three_ds_data.directory_server_id, }) } } #[derive(Debug, Deserialize, Serialize)] pub struct NmiCompleteResponse { pub response: Response, pub responsetext: String, pub authcode: Option<String>, pub transactionid: String, pub avsresponse: Option<String>, pub cvvresponse: Option<String>, pub orderid: String, pub response_code: String, customer_vault_id: Option<Secret<String>>, } impl TryFrom< ResponseRouterData< CompleteAuthorize, NmiCompleteResponse, CompleteAuthorizeData, PaymentsResponseData, >, > for PaymentsCompleteAuthorizeRouterData { type Error = Error; fn try_from( item: ResponseRouterData< CompleteAuthorize, NmiCompleteResponse, CompleteAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.transactionid), redirection_data: Box::new(None), mandate_reference: match item.response.customer_vault_id { Some(vault_id) => Box::new(Some( hyperswitch_domain_models::router_response_types::MandateReference { connector_mandate_id: Some(vault_id.expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }, )), None => Box::new(None), }, connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, charges: None, }), if item.data.request.is_auto_capture()? { AttemptStatus::Charged } else { AttemptStatus::Authorized }, ), Response::Declined | Response::Error => ( Err(get_nmi_error_response(item.response, item.http_code)), AttemptStatus::Failure, ), }; Ok(Self { status, response, ..item.data }) } } fn get_nmi_error_response(response: NmiCompleteResponse, http_code: u16) -> ErrorResponse { ErrorResponse { code: response.response_code, message: response.responsetext.to_owned(), reason: Some(response.responsetext), status_code: http_code, attempt_status: None, connector_transaction_id: Some(response.transactionid), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, } } #[derive(Debug, Serialize)] pub struct NmiValidateRequest { #[serde(rename = "type")] transaction_type: TransactionType, security_key: Secret<String>, ccnumber: CardNumber, ccexp: Secret<String>, cvv: Secret<String>, orderid: String, customer_vault: CustomerAction, } #[derive(Debug, Serialize)] pub struct NmiPaymentsRequest { #[serde(rename = "type")] transaction_type: TransactionType, amount: FloatMajorUnit, security_key: Secret<String>, currency: Currency, #[serde(flatten)] payment_method: PaymentMethod, #[serde(flatten)] merchant_defined_field: Option<NmiMerchantDefinedField>, orderid: String, #[serde(skip_serializing_if = "Option::is_none")] customer_vault: Option<CustomerAction>, } #[derive(Debug, Serialize)] pub struct NmiMerchantDefinedField { #[serde(flatten)] inner: std::collections::BTreeMap<String, Secret<String>>, } impl NmiMerchantDefinedField { pub fn new(metadata: &serde_json::Value) -> Self { let metadata_as_string = metadata.to_string(); let hash_map: std::collections::BTreeMap<String, serde_json::Value> = serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new()); let inner = hash_map .into_iter() .enumerate() .map(|(index, (hs_key, hs_value))| { let nmi_key = format!("merchant_defined_field_{}", index + 1); let nmi_value = format!("{hs_key}={hs_value}"); (nmi_key, Secret::new(nmi_value)) }) .collect(); Self { inner } } } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaymentMethod { CardNonThreeDs(Box<CardData>), CardThreeDs(Box<CardThreeDsData>), GPay(Box<GooglePayData>), ApplePay(Box<ApplePayData>), MandatePayment(Box<MandatePayment>), } #[derive(Debug, Serialize)] pub struct MandatePayment { customer_vault_id: Secret<String>, } #[derive(Debug, Serialize)] pub struct CardData { ccnumber: CardNumber, ccexp: Secret<String>, cvv: Secret<String>, } #[derive(Debug, Serialize)] pub struct CardThreeDsData { ccnumber: CardNumber, ccexp: Secret<String>, email: Option<Email>, cardholder_auth: Option<String>, cavv: Option<Secret<String>>, eci: Option<String>, cvv: Secret<String>, three_ds_version: Option<String>, directory_server_id: Option<Secret<String>>, } #[derive(Debug, Serialize)] pub struct GooglePayData { googlepay_payment_data: Secret<String>, } #[derive(Debug, Serialize)] pub struct ApplePayData { applepay_payment_data: Secret<String>, } impl TryFrom<&NmiRouterData<&PaymentsAuthorizeRouterData>> for NmiPaymentsRequest { type Error = Error; fn try_from(item: &NmiRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { let transaction_type = match item.router_data.request.is_auto_capture()? { true => TransactionType::Sale, false => TransactionType::Auth, }; let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?; let amount = item.amount; match item .router_data .request .mandate_id .clone() .and_then(|mandate_ids| mandate_ids.mandate_reference_id) { Some(api_models::payments::MandateReferenceId::ConnectorMandateId( connector_mandate_id, )) => Ok(Self { transaction_type, security_key: auth_type.api_key, amount, currency: item.router_data.request.currency, payment_method: PaymentMethod::MandatePayment(Box::new(MandatePayment { customer_vault_id: Secret::new( connector_mandate_id .get_connector_mandate_id() .ok_or(ConnectorError::MissingConnectorMandateID)?, ), })), merchant_defined_field: item .router_data .request .metadata .as_ref() .map(NmiMerchantDefinedField::new), orderid: item.router_data.connector_request_reference_id.clone(), customer_vault: None, }), Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) | Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) => { Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("nmi"), ))? } None => { let payment_method = PaymentMethod::try_from(( &item.router_data.request.payment_method_data, Some(item.router_data), ))?; Ok(Self { transaction_type, security_key: auth_type.api_key, amount, currency: item.router_data.request.currency, payment_method, merchant_defined_field: item .router_data .request .metadata .as_ref() .map(NmiMerchantDefinedField::new), orderid: item.router_data.connector_request_reference_id.clone(), customer_vault: item .router_data .request .is_mandate_payment() .then_some(CustomerAction::AddCustomer), }) } } } } impl TryFrom<(&PaymentMethodData, Option<&PaymentsAuthorizeRouterData>)> for PaymentMethod { type Error = Error; fn try_from( item: (&PaymentMethodData, Option<&PaymentsAuthorizeRouterData>), ) -> Result<Self, Self::Error> { let (payment_method_data, router_data) = item; match payment_method_data { PaymentMethodData::Card(ref card) => match router_data { Some(data) => match data.auth_type { AuthenticationType::NoThreeDs => Ok(Self::try_from(card)?), AuthenticationType::ThreeDs => Ok(Self::try_from((card, &data.request))?), }, None => Ok(Self::try_from(card)?), }, PaymentMethodData::Wallet(ref wallet_type) => match wallet_type { WalletData::GooglePay(ref googlepay_data) => Ok(Self::try_from(googlepay_data)?), WalletData::ApplePay(ref applepay_data) => Ok(Self::try_from(applepay_data)?), WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::AmazonPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(report!(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("nmi"), ))), }, PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Err( ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( "nmi", )) .into(), ), } } } impl TryFrom<(&Card, &PaymentsAuthorizeData)> for PaymentMethod { type Error = Error; fn try_from(val: (&Card, &PaymentsAuthorizeData)) -> Result<Self, Self::Error> { let (card_data, item) = val; let auth_data = &item.get_authentication_data()?; let ccexp = card_data.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?; let card_3ds_details = CardThreeDsData { ccnumber: card_data.card_number.clone(), ccexp, cvv: card_data.card_cvc.clone(), email: item.email.clone(), cavv: Some(auth_data.cavv.clone()), eci: auth_data.eci.clone(), cardholder_auth: None, three_ds_version: auth_data .message_version .clone() .map(|version| version.to_string()), directory_server_id: auth_data .threeds_server_transaction_id .clone() .map(Secret::new), }; Ok(Self::CardThreeDs(Box::new(card_3ds_details))) } } impl TryFrom<&Card> for PaymentMethod { type Error = Error; fn try_from(card: &Card) -> Result<Self, Self::Error> { let ccexp = card.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?; let card = CardData { ccnumber: card.card_number.clone(), ccexp, cvv: card.card_cvc.clone(), }; Ok(Self::CardNonThreeDs(Box::new(card))) } } impl TryFrom<&GooglePayWalletData> for PaymentMethod { type Error = Report<ConnectorError>; fn try_from(wallet_data: &GooglePayWalletData) -> Result<Self, Self::Error> { let gpay_data = GooglePayData { googlepay_payment_data: Secret::new( wallet_data .tokenization_data .get_encrypted_google_pay_token() .change_context(ConnectorError::MissingRequiredField { field_name: "gpay wallet_token", })? .clone(), ), }; Ok(Self::GPay(Box::new(gpay_data))) } } impl TryFrom<&ApplePayWalletData> for PaymentMethod { type Error = Error; fn try_from(apple_pay_wallet_data: &ApplePayWalletData) -> Result<Self, Self::Error> { let apple_pay_encrypted_data = apple_pay_wallet_data .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context(ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", })?; let apple_pay_data = ApplePayData { applepay_payment_data: Secret::new(apple_pay_encrypted_data.clone()), }; Ok(Self::ApplePay(Box::new(apple_pay_data))) } } impl TryFrom<&SetupMandateRouterData> for NmiValidateRequest { type Error = Error; fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> { match item.request.amount { Some(amount) if amount > 0 => Err(ConnectorError::FlowNotSupported { flow: "Setup Mandate with non zero amount".to_string(), connector: "NMI".to_string(), } .into()), _ => { if let PaymentMethodData::Card(card_details) = &item.request.payment_method_data { let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; Ok(Self { transaction_type: TransactionType::Validate, security_key: auth_type.api_key, ccnumber: card_details.card_number.clone(), ccexp: card_details .get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?, cvv: card_details.card_cvc.clone(), orderid: item.connector_request_reference_id.clone(), customer_vault: CustomerAction::AddCustomer, }) } else { Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Nmi"), ) .into()) } } } } } #[derive(Debug, Serialize)] pub struct NmiSyncRequest { pub order_id: String, pub security_key: Secret<String>, } impl TryFrom<&PaymentsSyncRouterData> for NmiSyncRequest { type Error = Error; fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; Ok(Self { security_key: auth.api_key, order_id: item.attempt_id.clone(), }) } } #[derive(Debug, Serialize)] pub struct NmiCaptureRequest { #[serde(rename = "type")] pub transaction_type: TransactionType, pub security_key: Secret<String>, pub transactionid: String, pub amount: Option<FloatMajorUnit>, } impl TryFrom<&NmiRouterData<&PaymentsCaptureRouterData>> for NmiCaptureRequest { type Error = Error; fn try_from(item: &NmiRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(Self { transaction_type: TransactionType::Capture, security_key: auth.api_key, transactionid: item.router_data.request.connector_transaction_id.clone(), amount: Some(item.amount), }) } } impl TryFrom< ResponseRouterData<Capture, StandardResponse, PaymentsCaptureData, PaymentsResponseData>, > for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData> { type Error = Error; fn try_from( item: ResponseRouterData< Capture, StandardResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transactionid.to_owned(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, charges: None, }), AttemptStatus::Charged, ), Response::Declined | Response::Error => ( Err(get_standard_error_response(item.response, item.http_code)), AttemptStatus::CaptureFailed, ), }; Ok(Self { status, response, ..item.data }) } } #[derive(Debug, Serialize)] pub struct NmiCancelRequest { #[serde(rename = "type")] pub transaction_type: TransactionType, pub security_key: Secret<String>, pub transactionid: String, pub void_reason: NmiVoidReason, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum NmiVoidReason { Fraud, UserCancel, IccRejected, IccCardRemoved, IccNoConfirmation, PosTimeout, } impl TryFrom<&PaymentsCancelRouterData> for NmiCancelRequest { type Error = Error; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; match &item.request.cancellation_reason { Some(cancellation_reason) => { let void_reason: NmiVoidReason = serde_json::from_str(&format!("\"{cancellation_reason}\"", )) .map_err(|_| ConnectorError::NotSupported { message: format!("Json deserialise error: unknown variant `{cancellation_reason}` expected to be one of `fraud`, `user_cancel`, `icc_rejected`, `icc_card_removed`, `icc_no_confirmation`, `pos_timeout`. This cancellation_reason"), connector: "nmi" })?; Ok(Self { transaction_type: TransactionType::Void, security_key: auth.api_key, transactionid: item.request.connector_transaction_id.clone(), void_reason, }) } None => Err(ConnectorError::MissingRequiredField { field_name: "cancellation_reason", } .into()), } } } #[derive(Debug, Deserialize, Serialize)] pub enum Response { #[serde(alias = "1")] Approved, #[serde(alias = "2")] Declined, #[serde(alias = "3")] Error, } #[derive(Debug, Deserialize, Serialize)] pub struct StandardResponse { pub response: Response, pub responsetext: String, pub authcode: Option<String>, pub transactionid: String, pub avsresponse: Option<String>, pub cvvresponse: Option<String>, pub orderid: String, pub response_code: String, pub customer_vault_id: Option<Secret<String>>, } impl<T> TryFrom<ResponseRouterData<SetupMandate, StandardResponse, T, PaymentsResponseData>> for RouterData<SetupMandate, T, PaymentsResponseData> { type Error = Error; fn try_from( item: ResponseRouterData<SetupMandate, StandardResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), mandate_reference: match item.response.customer_vault_id { Some(vault_id) => Box::new(Some( hyperswitch_domain_models::router_response_types::MandateReference { connector_mandate_id: Some(vault_id.expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }, )), None => Box::new(None), }, connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, charges: None, }), AttemptStatus::Charged, ), Response::Declined | Response::Error => ( Err(get_standard_error_response(item.response, item.http_code)), AttemptStatus::Failure, ), }; Ok(Self { status, response, ..item.data }) } } fn get_standard_error_response(response: StandardResponse, http_code: u16) -> ErrorResponse { ErrorResponse { code: response.response_code, message: response.responsetext.to_owned(), reason: Some(response.responsetext), status_code: http_code, attempt_status: None, connector_transaction_id: Some(response.transactionid), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, } } impl TryFrom<PaymentsResponseRouterData<StandardResponse>> for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { type Error = Error; fn try_from( item: ResponseRouterData< Authorize, StandardResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), mandate_reference: match item.response.customer_vault_id { Some(vault_id) => Box::new(Some( hyperswitch_domain_models::router_response_types::MandateReference { connector_mandate_id: Some(vault_id.expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }, )), None => Box::new(None), }, connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, charges: None, }), if item.data.request.is_auto_capture()? { AttemptStatus::Charged } else { AttemptStatus::Authorized }, ), Response::Declined | Response::Error => ( Err(get_standard_error_response(item.response, item.http_code)), AttemptStatus::Failure, ), }; Ok(Self { status, response, ..item.data }) } } impl<T> TryFrom<ResponseRouterData<Void, StandardResponse, T, PaymentsResponseData>> for RouterData<Void, T, PaymentsResponseData> { type Error = Error; fn try_from( item: ResponseRouterData<Void, StandardResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, charges: None, }), AttemptStatus::VoidInitiated, ), Response::Declined | Response::Error => ( Err(get_standard_error_response(item.response, item.http_code)), AttemptStatus::VoidFailed, ), }; Ok(Self { status, response, ..item.data }) } } #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case")] pub enum NmiStatus { Abandoned, Cancelled, Pendingsettlement, Pending, Failed, Complete, InProgress, Unknown, } impl<F, T> TryFrom<ResponseRouterData<F, SyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = Error; fn try_from( item: ResponseRouterData<F, SyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response.transaction { Some(trn) => Ok(Self { status: AttemptStatus::from(NmiStatus::from(trn.condition)), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(trn.transaction_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), None => Ok(Self { ..item.data }), //when there is empty connector response i.e. response we get in psync when payment status is in authentication_pending } } } impl TryFrom<Vec<u8>> for SyncResponse { type Error = Error; fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { let query_response = String::from_utf8(bytes) .change_context(ConnectorError::ResponseDeserializationFailed)?; query_response .parse_xml::<Self>() .change_context(ConnectorError::ResponseDeserializationFailed) } } impl TryFrom<Vec<u8>> for NmiRefundSyncResponse { type Error = Error; fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { let query_response = String::from_utf8(bytes) .change_context(ConnectorError::ResponseDeserializationFailed)?; query_response .parse_xml::<Self>() .change_context(ConnectorError::ResponseDeserializationFailed) } } impl From<NmiStatus> for AttemptStatus { fn from(item: NmiStatus) -> Self { match item { NmiStatus::Abandoned => Self::AuthenticationFailed, NmiStatus::Cancelled => Self::Voided, NmiStatus::Pending => Self::Authorized, NmiStatus::Pendingsettlement | NmiStatus::Complete => Self::Charged, NmiStatus::InProgress => Self::AuthenticationPending, NmiStatus::Failed | NmiStatus::Unknown => Self::Failure, } } } // REFUND : #[derive(Debug, Serialize)] pub struct NmiRefundRequest { #[serde(rename = "type")] transaction_type: TransactionType, security_key: Secret<String>, transactionid: String, orderid: String, amount: FloatMajorUnit, } impl<F> TryFrom<&NmiRouterData<&RefundsRouterData<F>>> for NmiRefundRequest { type Error = Error; fn try_from(item: &NmiRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?; Ok(Self { transaction_type: TransactionType::Refund, security_key: auth_type.api_key, transactionid: item.router_data.request.connector_transaction_id.clone(), orderid: item.router_data.request.refund_id.clone(), amount: item.amount, }) } } impl TryFrom<RefundsResponseRouterData<Execute, StandardResponse>> for RefundsRouterData<Execute> { type Error = Error; fn try_from( item: RefundsResponseRouterData<Execute, StandardResponse>, ) -> Result<Self, Self::Error> { let refund_status = RefundStatus::from(item.response.response); Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.orderid, refund_status, }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<Capture, StandardResponse>> for RefundsRouterData<Capture> { type Error = Error; fn try_from( item: RefundsResponseRouterData<Capture, StandardResponse>, ) -> Result<Self, Self::Error> { let refund_status = RefundStatus::from(item.response.response); Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.transactionid, refund_status, }), ..item.data }) } } impl From<Response> for RefundStatus { fn from(item: Response) -> Self { match item { Response::Approved => Self::Success, Response::Declined | Response::Error => Self::Failure, } } } impl TryFrom<&RefundSyncRouterData> for NmiSyncRequest { type Error = Error; fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; Ok(Self { security_key: auth.api_key, order_id: item .request .connector_refund_id .clone() .ok_or(ConnectorError::MissingConnectorRefundID)?, }) } } impl TryFrom<RefundsResponseRouterData<RSync, NmiRefundSyncResponse>> for RefundsRouterData<RSync> { type Error = Report<ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, NmiRefundSyncResponse>, ) -> Result<Self, Self::Error> { let refund_status = RefundStatus::from(NmiStatus::from(item.response.transaction.condition)); Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction.order_id, refund_status, }), ..item.data }) } } impl From<NmiStatus> for RefundStatus { fn from(item: NmiStatus) -> Self { match item { NmiStatus::Abandoned | NmiStatus::Cancelled | NmiStatus::Failed | NmiStatus::Unknown => Self::Failure, NmiStatus::Pending | NmiStatus::InProgress => Self::Pending, NmiStatus::Pendingsettlement | NmiStatus::Complete => Self::Success, } } } impl From<String> for NmiStatus { fn from(value: String) -> Self { match value.as_str() { "abandoned" => Self::Abandoned, "canceled" => Self::Cancelled, "in_progress" => Self::InProgress, "pendingsettlement" => Self::Pendingsettlement, "complete" => Self::Complete, "failed" => Self::Failed, "unknown" => Self::Unknown, // Other than above values only pending is possible, since value is a string handling this as default _ => Self::Pending, } } } #[derive(Debug, Deserialize, Serialize)] pub struct SyncTransactionResponse { pub transaction_id: String, pub condition: String, } #[derive(Debug, Deserialize, Serialize)] pub struct SyncResponse { pub transaction: Option<SyncTransactionResponse>, } #[derive(Debug, Deserialize, Serialize)] pub struct RefundSyncBody { order_id: String, condition: String, } #[derive(Debug, Deserialize, Serialize)] pub struct NmiRefundSyncResponse { transaction: RefundSyncBody, } #[derive(Debug, Deserialize)] pub struct NmiWebhookObjectReference { pub event_body: NmiReferenceBody, } #[derive(Debug, Deserialize)] pub struct NmiReferenceBody { pub order_id: String, pub action: NmiActionBody, } #[derive(Debug, Deserialize, Serialize)] pub struct NmiActionBody { pub action_type: NmiActionType, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum NmiActionType { Auth, Capture, Credit, Refund, Sale, Void, } #[derive(Debug, Deserialize)] pub struct NmiWebhookEventBody { pub event_type: NmiWebhookEventType, } #[derive(Debug, Deserialize, Serialize)] pub enum NmiWebhookEventType { #[serde(rename = "transaction.sale.success")] SaleSuccess, #[serde(rename = "transaction.sale.failure")] SaleFailure, #[serde(rename = "transaction.sale.unknown")] SaleUnknown, #[serde(rename = "transaction.auth.success")] AuthSuccess, #[serde(rename = "transaction.auth.failure")] AuthFailure, #[serde(rename = "transaction.auth.unknown")] AuthUnknown, #[serde(rename = "transaction.refund.success")] RefundSuccess, #[serde(rename = "transaction.refund.failure")] RefundFailure, #[serde(rename = "transaction.refund.unknown")] RefundUnknown, #[serde(rename = "transaction.void.success")] VoidSuccess, #[serde(rename = "transaction.void.failure")] VoidFailure, #[serde(rename = "transaction.void.unknown")] VoidUnknown, #[serde(rename = "transaction.capture.success")] CaptureSuccess, #[serde(rename = "transaction.capture.failure")] CaptureFailure, #[serde(rename = "transaction.capture.unknown")] CaptureUnknown, } pub fn get_nmi_webhook_event(status: NmiWebhookEventType) -> IncomingWebhookEvent { match status { NmiWebhookEventType::SaleSuccess => IncomingWebhookEvent::PaymentIntentSuccess, NmiWebhookEventType::SaleFailure => IncomingWebhookEvent::PaymentIntentFailure, NmiWebhookEventType::RefundSuccess => IncomingWebhookEvent::RefundSuccess, NmiWebhookEventType::RefundFailure => IncomingWebhookEvent::RefundFailure, NmiWebhookEventType::VoidSuccess => IncomingWebhookEvent::PaymentIntentCancelled, NmiWebhookEventType::AuthSuccess => IncomingWebhookEvent::PaymentIntentAuthorizationSuccess, NmiWebhookEventType::CaptureSuccess => IncomingWebhookEvent::PaymentIntentCaptureSuccess, NmiWebhookEventType::AuthFailure => IncomingWebhookEvent::PaymentIntentAuthorizationFailure, NmiWebhookEventType::CaptureFailure => IncomingWebhookEvent::PaymentIntentCaptureFailure, NmiWebhookEventType::VoidFailure => IncomingWebhookEvent::PaymentIntentCancelFailure, NmiWebhookEventType::SaleUnknown | NmiWebhookEventType::RefundUnknown | NmiWebhookEventType::AuthUnknown | NmiWebhookEventType::VoidUnknown | NmiWebhookEventType::CaptureUnknown => IncomingWebhookEvent::EventNotSupported, } } #[derive(Debug, Deserialize, Serialize)] pub struct NmiWebhookBody { pub event_body: NmiWebhookObject, } #[derive(Debug, Deserialize, Serialize)] pub struct NmiWebhookObject { pub transaction_id: String, pub order_id: String, pub condition: String, pub action: NmiActionBody, } impl TryFrom<&NmiWebhookBody> for SyncResponse { type Error = Error; fn try_from(item: &NmiWebhookBody) -> Result<Self, Self::Error> { let transaction = Some(SyncTransactionResponse { transaction_id: item.event_body.transaction_id.to_owned(), condition: item.event_body.condition.to_owned(), }); Ok(Self { transaction }) } }
crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
hyperswitch_connectors::src::connectors::nmi::transformers
10,476
true
// File: crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs // Module: hyperswitch_connectors::src::connectors::inespay::transformers use common_enums::enums; use common_utils::{ request::Method, types::{MinorUnit, StringMinorUnit, StringMinorUnitForConnector}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankDebitData, PaymentMethodData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{self, PaymentsAuthorizeRequestData, RouterData as _}, }; pub struct InespayRouterData<T> { pub amount: StringMinorUnit, pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for InespayRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Default, Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct InespayPaymentsRequest { description: String, amount: StringMinorUnit, reference: String, debtor_account: Option<Secret<String>>, success_link_redirect: Option<String>, notif_url: Option<String>, } impl TryFrom<&InespayRouterData<&PaymentsAuthorizeRouterData>> for InespayPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &InespayRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => { let order_id = item.router_data.connector_request_reference_id.clone(); let webhook_url = item.router_data.request.get_webhook_url()?; let return_url = item.router_data.request.get_router_return_url()?; Ok(Self { description: item.router_data.get_description()?, amount: item.amount.clone(), reference: order_id, debtor_account: Some(iban), success_link_redirect: Some(return_url), notif_url: Some(webhook_url), }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } pub struct InespayAuthType { pub(super) api_key: Secret<String>, pub authorization: Secret<String>, } impl TryFrom<&ConnectorAuthType> for InespayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.to_owned(), authorization: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct InespayPaymentsResponseData { status: String, status_desc: String, single_payin_id: String, single_payin_link: String, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum InespayPaymentsResponse { InespayPaymentsData(InespayPaymentsResponseData), InespayPaymentsError(InespayErrorResponse), } impl<F, T> TryFrom<ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let (status, response) = match item.response { InespayPaymentsResponse::InespayPaymentsData(data) => { let redirection_url = Url::parse(data.single_payin_link.as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let redirection_data = RedirectForm::from((redirection_url, Method::Get)); ( common_enums::AttemptStatus::AuthenticationPending, Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( data.single_payin_id.clone(), ), redirection_data: Box::new(Some(redirection_data)), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ) } InespayPaymentsResponse::InespayPaymentsError(data) => ( common_enums::AttemptStatus::Failure, Err(ErrorResponse { code: data.status.clone(), message: data.status_desc.clone(), reason: Some(data.status_desc.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ), }; Ok(Self { status, response, ..item.data }) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum InespayPSyncStatus { Ok, Created, Opened, BankSelected, Initiated, Pending, Aborted, Unfinished, Rejected, Cancelled, PartiallyAccepted, Failed, Settled, PartRefunded, Refunded, } impl From<InespayPSyncStatus> for common_enums::AttemptStatus { fn from(item: InespayPSyncStatus) -> Self { match item { InespayPSyncStatus::Ok | InespayPSyncStatus::Settled => Self::Charged, InespayPSyncStatus::Created | InespayPSyncStatus::Opened | InespayPSyncStatus::BankSelected | InespayPSyncStatus::Initiated | InespayPSyncStatus::Pending | InespayPSyncStatus::Unfinished | InespayPSyncStatus::PartiallyAccepted => Self::AuthenticationPending, InespayPSyncStatus::Aborted | InespayPSyncStatus::Rejected | InespayPSyncStatus::Cancelled | InespayPSyncStatus::Failed => Self::Failure, InespayPSyncStatus::PartRefunded | InespayPSyncStatus::Refunded => Self::AutoRefunded, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct InespayPSyncResponseData { cod_status: InespayPSyncStatus, status_desc: String, single_payin_id: String, single_payin_link: String, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum InespayPSyncResponse { InespayPSyncData(InespayPSyncResponseData), InespayPSyncWebhook(InespayPaymentWebhookData), InespayPSyncError(InespayErrorResponse), } impl<F, T> TryFrom<ResponseRouterData<F, InespayPSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, InespayPSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response { InespayPSyncResponse::InespayPSyncData(data) => { let redirection_url = Url::parse(data.single_payin_link.as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let redirection_data = RedirectForm::from((redirection_url, Method::Get)); Ok(Self { status: common_enums::AttemptStatus::from(data.cod_status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( data.single_payin_id.clone(), ), redirection_data: Box::new(Some(redirection_data)), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } InespayPSyncResponse::InespayPSyncWebhook(data) => { let status = enums::AttemptStatus::from(data.cod_status); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( data.single_payin_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } InespayPSyncResponse::InespayPSyncError(data) => Ok(Self { response: Err(ErrorResponse { code: data.status.clone(), message: data.status_desc.clone(), reason: Some(data.status_desc.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct InespayRefundRequest { single_payin_id: String, amount: Option<MinorUnit>, } impl<F> TryFrom<&InespayRouterData<&RefundsRouterData<F>>> for InespayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &InespayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let amount = utils::convert_back_amount_to_minor_units( &StringMinorUnitForConnector, item.amount.to_owned(), item.router_data.request.currency, )?; Ok(Self { single_payin_id: item.router_data.request.connector_transaction_id.clone(), amount: Some(amount), }) } } #[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum InespayRSyncStatus { Confirmed, #[default] Pending, Rejected, Denied, Reversed, Mistake, } impl From<InespayRSyncStatus> for enums::RefundStatus { fn from(item: InespayRSyncStatus) -> Self { match item { InespayRSyncStatus::Confirmed => Self::Success, InespayRSyncStatus::Pending => Self::Pending, InespayRSyncStatus::Rejected | InespayRSyncStatus::Denied | InespayRSyncStatus::Reversed | InespayRSyncStatus::Mistake => Self::Failure, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RefundsData { status: String, status_desc: String, refund_id: String, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum InespayRefundsResponse { InespayRefundsData(RefundsData), InespayRefundsError(InespayErrorResponse), } impl TryFrom<RefundsResponseRouterData<Execute, InespayRefundsResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, InespayRefundsResponse>, ) -> Result<Self, Self::Error> { match item.response { InespayRefundsResponse::InespayRefundsData(data) => Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: data.refund_id, refund_status: enums::RefundStatus::Pending, }), ..item.data }), InespayRefundsResponse::InespayRefundsError(data) => Ok(Self { response: Err(ErrorResponse { code: data.status.clone(), message: data.status_desc.clone(), reason: Some(data.status_desc.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct InespayRSyncResponseData { cod_status: InespayRSyncStatus, status_desc: String, refund_id: String, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum InespayRSyncResponse { InespayRSyncData(InespayRSyncResponseData), InespayRSyncWebhook(InespayRefundWebhookData), InespayRSyncError(InespayErrorResponse), } impl TryFrom<RefundsResponseRouterData<RSync, InespayRSyncResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, InespayRSyncResponse>, ) -> Result<Self, Self::Error> { let response = match item.response { InespayRSyncResponse::InespayRSyncData(data) => Ok(RefundsResponseData { connector_refund_id: data.refund_id, refund_status: enums::RefundStatus::from(data.cod_status), }), InespayRSyncResponse::InespayRSyncWebhook(data) => Ok(RefundsResponseData { connector_refund_id: data.refund_id, refund_status: enums::RefundStatus::from(data.cod_status), }), InespayRSyncResponse::InespayRSyncError(data) => Err(ErrorResponse { code: data.status.clone(), message: data.status_desc.clone(), reason: Some(data.status_desc.clone()), attempt_status: None, connector_transaction_id: None, status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), }; Ok(Self { response, ..item.data }) } } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct InespayPaymentWebhookData { pub single_payin_id: String, pub cod_status: InespayPSyncStatus, pub description: String, pub amount: MinorUnit, pub reference: String, pub creditor_account: Secret<String>, pub debtor_name: Secret<String>, pub debtor_account: Secret<String>, pub custom_data: Option<String>, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct InespayRefundWebhookData { pub refund_id: String, pub simple_payin_id: String, pub cod_status: InespayRSyncStatus, pub description: String, pub amount: MinorUnit, pub reference: String, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(untagged)] pub enum InespayWebhookEventData { Payment(InespayPaymentWebhookData), Refund(InespayRefundWebhookData), } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct InespayWebhookEvent { pub data_return: String, pub signature_data_return: String, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct InespayErrorResponse { pub status: String, pub status_desc: String, } impl From<InespayWebhookEventData> for api_models::webhooks::IncomingWebhookEvent { fn from(item: InespayWebhookEventData) -> Self { match item { InespayWebhookEventData::Payment(payment_data) => match payment_data.cod_status { InespayPSyncStatus::Ok | InespayPSyncStatus::Settled => Self::PaymentIntentSuccess, InespayPSyncStatus::Failed | InespayPSyncStatus::Rejected => { Self::PaymentIntentFailure } InespayPSyncStatus::Created | InespayPSyncStatus::Opened | InespayPSyncStatus::BankSelected | InespayPSyncStatus::Initiated | InespayPSyncStatus::Pending | InespayPSyncStatus::Unfinished | InespayPSyncStatus::PartiallyAccepted => Self::PaymentIntentProcessing, InespayPSyncStatus::Aborted | InespayPSyncStatus::Cancelled | InespayPSyncStatus::PartRefunded | InespayPSyncStatus::Refunded => Self::EventNotSupported, }, InespayWebhookEventData::Refund(refund_data) => match refund_data.cod_status { InespayRSyncStatus::Confirmed => Self::RefundSuccess, InespayRSyncStatus::Rejected | InespayRSyncStatus::Denied | InespayRSyncStatus::Reversed | InespayRSyncStatus::Mistake => Self::RefundFailure, InespayRSyncStatus::Pending => Self::EventNotSupported, }, } } }
crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs
hyperswitch_connectors::src::connectors::inespay::transformers
4,068
true
// File: crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs // Module: hyperswitch_connectors::src::connectors::itaubank::transformers use api_models::payments::QrCodeInformation; use common_enums::enums; use common_utils::{errors::CustomResult, ext_traits::Encode, types::StringMajorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankTransferData, PaymentMethodData}, router_data::{AccessToken, ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{get_timestamp_in_milliseconds, QrImage, RouterData as _}, }; pub struct ItaubankRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for ItaubankRouterData<T> { fn from((amount, item): (StringMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Default, Debug, Serialize)] pub struct ItaubankPaymentsRequest { valor: PixPaymentValue, // amount chave: Secret<String>, // pix-key devedor: ItaubankDebtor, // debtor } #[derive(Default, Debug, Serialize)] pub struct PixPaymentValue { original: StringMajorUnit, } #[derive(Default, Debug, Serialize)] pub struct ItaubankDebtor { #[serde(skip_serializing_if = "Option::is_none")] cpf: Option<Secret<String>>, // CPF is a Brazilian tax identification number #[serde(skip_serializing_if = "Option::is_none")] cnpj: Option<Secret<String>>, // CNPJ is a Brazilian company tax identification number #[serde(skip_serializing_if = "Option::is_none")] nome: Option<Secret<String>>, // name of the debtor } impl TryFrom<&ItaubankRouterData<&types::PaymentsAuthorizeRouterData>> for ItaubankPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &ItaubankRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::BankTransfer(bank_transfer_data) => { match *bank_transfer_data { BankTransferData::Pix { pix_key, cpf, cnpj, .. } => { let nome = item.router_data.get_optional_billing_full_name(); // cpf and cnpj are mutually exclusive let devedor = match (cnpj, cpf) { (Some(cnpj), _) => ItaubankDebtor { cpf: None, cnpj: Some(cnpj), nome, }, (None, Some(cpf)) => ItaubankDebtor { cpf: Some(cpf), cnpj: None, nome, }, _ => Err(errors::ConnectorError::MissingRequiredField { field_name: "cpf and cnpj both missing in payment_method_data", })?, }; Ok(Self { valor: PixPaymentValue { original: item.amount.to_owned(), }, chave: pix_key.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "pix_key", })?, devedor, }) } BankTransferData::AchBankTransfer {} | BankTransferData::SepaBankTransfer {} | BankTransferData::BacsBankTransfer {} | BankTransferData::MultibancoBankTransfer {} | BankTransferData::PermataBankTransfer {} | BankTransferData::BcaBankTransfer {} | BankTransferData::BniVaBankTransfer {} | BankTransferData::BriVaBankTransfer {} | BankTransferData::CimbVaBankTransfer {} | BankTransferData::DanamonVaBankTransfer {} | BankTransferData::MandiriVaBankTransfer {} | BankTransferData::Pse {} | BankTransferData::InstantBankTransfer {} | BankTransferData::InstantBankTransferFinland {} | BankTransferData::InstantBankTransferPoland {} | BankTransferData::IndonesianBankTransfer { .. } | BankTransferData::LocalBankTransfer { .. } => { Err(errors::ConnectorError::NotImplemented( "Selected payment method through itaubank".to_string(), ) .into()) } } } PaymentMethodData::Card(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( "Selected payment method through itaubank".to_string(), ) .into()) } } } } pub struct ItaubankAuthType { pub(super) client_id: Secret<String>, pub(super) client_secret: Secret<String>, pub(super) certificate: Option<Secret<String>>, pub(super) certificate_key: Option<Secret<String>>, } impl TryFrom<&ConnectorAuthType> for ItaubankAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => Ok(Self { client_secret: api_key.to_owned(), client_id: key1.to_owned(), certificate: Some(api_secret.to_owned()), certificate_key: Some(key2.to_owned()), }), ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { client_secret: api_key.to_owned(), client_id: key1.to_owned(), certificate: None, certificate_key: None, }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Serialize)] pub struct ItaubankAuthRequest { client_id: Secret<String>, client_secret: Secret<String>, grant_type: ItaubankGrantType, } #[derive(Clone, Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum ItaubankGrantType { ClientCredentials, } impl TryFrom<&types::RefreshTokenRouterData> for ItaubankAuthRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> { let auth_details = ItaubankAuthType::try_from(&item.connector_auth_type)?; Ok(Self { client_id: auth_details.client_id, client_secret: auth_details.client_secret, grant_type: ItaubankGrantType::ClientCredentials, }) } } #[derive(Debug, Serialize, Deserialize)] pub struct ItaubankUpdateTokenResponse { access_token: Secret<String>, expires_in: i64, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ItaubankTokenErrorResponse { pub status: i64, pub title: Option<String>, pub detail: Option<String>, pub user_message: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, ItaubankUpdateTokenResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, ItaubankUpdateTokenResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(AccessToken { token: item.response.access_token, expires: item.response.expires_in, }), ..item.data }) } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum ItaubankPaymentStatus { Ativa, // Active Concluida, // Completed RemovidaPeloPsp, // Removed by PSP RemovidaPeloUsuarioRecebedor, // Removed by receiving User } impl From<ItaubankPaymentStatus> for enums::AttemptStatus { fn from(item: ItaubankPaymentStatus) -> Self { match item { ItaubankPaymentStatus::Ativa => Self::AuthenticationPending, ItaubankPaymentStatus::Concluida => Self::Charged, ItaubankPaymentStatus::RemovidaPeloPsp | ItaubankPaymentStatus::RemovidaPeloUsuarioRecebedor => Self::Failure, } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ItaubankPaymentsResponse { status: ItaubankPaymentStatus, calendario: ItaubankPixExpireTime, txid: String, #[serde(rename = "pixCopiaECola")] pix_qr_value: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ItaubankPixExpireTime { #[serde(with = "common_utils::custom_serde::iso8601")] criacao: PrimitiveDateTime, expiracao: i64, } impl<F, T> TryFrom<ResponseRouterData<F, ItaubankPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, ItaubankPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let connector_metadata = get_qr_code_data(&item.response)?; Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.txid.to_owned()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some(item.response.txid), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } fn get_qr_code_data( response: &ItaubankPaymentsResponse, ) -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> { let creation_time = get_timestamp_in_milliseconds(&response.calendario.criacao); // convert expiration to milliseconds and add to creation time let expiration_time = creation_time + (response.calendario.expiracao * 1000); let image_data = QrImage::new_from_data(response.pix_qr_value.clone()) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let image_data_url = Url::parse(image_data.data.clone().as_str()) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let qr_code_info = QrCodeInformation::QrDataUrl { image_data_url, display_to_timestamp: Some(expiration_time), }; Some(qr_code_info.encode_to_value()) .transpose() .change_context(errors::ConnectorError::ResponseHandlingFailed) } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ItaubankPaymentsSyncResponse { status: ItaubankPaymentStatus, txid: String, pix: Vec<ItaubankPixResponse>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ItaubankPixResponse { #[serde(rename = "endToEndId")] pix_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ItaubankMetaData { pub pix_id: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, ItaubankPaymentsSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, ItaubankPaymentsSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let pix_data = item .response .pix .first() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "pix_id", })? .to_owned(); let connector_metadata = Some(serde_json::json!(ItaubankMetaData { pix_id: pix_data.pix_id })); Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.txid.to_owned()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some(item.response.txid), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Default, Debug, Serialize)] pub struct ItaubankRefundRequest { pub valor: StringMajorUnit, // refund_amount } impl<F> TryFrom<&ItaubankRouterData<&types::RefundsRouterData<F>>> for ItaubankRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &ItaubankRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { valor: item.amount.to_owned(), }) } } #[allow(dead_code)] #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RefundStatus { EmProcessamento, // Processing Devolvido, // Returned NaoRealizado, // Unrealized } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Devolvido => Self::Success, RefundStatus::NaoRealizado => Self::Failure, RefundStatus::EmProcessamento => Self::Pending, } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RefundResponse { rtr_id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.rtr_id, refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.rtr_id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize)] pub struct ItaubankErrorResponse { pub error: ItaubankErrorBody, } #[derive(Debug, Serialize, Deserialize)] pub struct ItaubankErrorBody { pub status: u16, pub title: Option<String>, pub detail: Option<String>, pub violacoes: Option<Vec<Violations>>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Violations { pub razao: String, pub propriedade: String, pub valor: String, }
crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs
hyperswitch_connectors::src::connectors::itaubank::transformers
3,728
true
// File: crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs // Module: hyperswitch_connectors::src::connectors::dlocal::transformers use common_enums::enums; use common_utils::{pii::Email, request::Method, types::MinorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::{refunds::Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types, }; use hyperswitch_interfaces::errors; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as _}, }; #[derive(Debug, Default, Eq, PartialEq, Serialize)] pub struct Payer { pub name: Option<Secret<String>>, pub email: Option<Email>, pub document: Secret<String>, } #[derive(Debug, Default, Eq, Clone, PartialEq, Serialize, Deserialize)] pub struct Card { pub holder_name: Secret<String>, pub number: cards::CardNumber, pub cvv: Secret<String>, pub expiration_month: Secret<String>, pub expiration_year: Secret<String>, pub capture: String, pub installments_id: Option<String>, pub installments: Option<String>, } #[derive(Debug, Default, Eq, PartialEq, Serialize)] pub struct ThreeDSecureReqData { pub force: bool, } #[derive(Debug, Serialize, Default, Deserialize, Clone, Eq, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum PaymentMethodId { #[default] Card, } #[derive(Debug, Serialize, Default, Deserialize, Clone, Eq, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum PaymentMethodFlow { #[default] Direct, ReDirect, } #[derive(Debug, Serialize)] pub struct DlocalRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> TryFrom<(MinorUnit, T)> for DlocalRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, router_data): (MinorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data, }) } } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct DlocalPaymentsRequest { pub amount: MinorUnit, pub currency: enums::Currency, pub country: String, pub payment_method_id: PaymentMethodId, pub payment_method_flow: PaymentMethodFlow, pub payer: Payer, pub card: Option<Card>, pub order_id: String, pub three_dsecure: Option<ThreeDSecureReqData>, pub callback_url: Option<String>, pub description: Option<String>, } impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DlocalRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let email = item.router_data.request.email.clone(); let address = item.router_data.get_billing_address()?; let country = address.get_country()?; let name = get_payer_name(address); match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref ccard) => { let should_capture = matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic) ); let payment_request = Self { amount: item.amount, currency: item.router_data.request.currency, payment_method_id: PaymentMethodId::Card, payment_method_flow: PaymentMethodFlow::Direct, country: country.to_string(), payer: Payer { name, email, // [#589]: Allow securely collecting PII from customer in payments request document: get_doc_from_currency(country.to_string()), }, card: Some(Card { holder_name: item .router_data .get_optional_billing_full_name() .unwrap_or(Secret::new("".to_string())), number: ccard.card_number.clone(), cvv: ccard.card_cvc.clone(), expiration_month: ccard.card_exp_month.clone(), expiration_year: ccard.card_exp_year.clone(), capture: should_capture.to_string(), installments_id: item .router_data .request .mandate_id .as_ref() .and_then(|ids| ids.mandate_id.clone()), // [#595[FEATURE] Pass Mandate history information in payment flows/request] installments: item .router_data .request .mandate_id .clone() .map(|_| "1".to_string()), }), order_id: item.router_data.connector_request_reference_id.clone(), three_dsecure: match item.router_data.auth_type { enums::AuthenticationType::ThreeDs => { Some(ThreeDSecureReqData { force: true }) } enums::AuthenticationType::NoThreeDs => None, }, callback_url: Some(item.router_data.request.get_router_return_url()?), description: item.router_data.description.clone(), }; Ok(payment_request) } PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( crate::utils::get_unimplemented_payment_method_error_message("Dlocal"), ))? } } } } fn get_payer_name( address: &hyperswitch_domain_models::address::AddressDetails, ) -> Option<Secret<String>> { let first_name = address .first_name .clone() .map_or("".to_string(), |first_name| first_name.peek().to_string()); let last_name = address .last_name .clone() .map_or("".to_string(), |last_name| last_name.peek().to_string()); let name: String = format!("{first_name} {last_name}").trim().to_string(); if !name.is_empty() { Some(Secret::new(name)) } else { None } } pub struct DlocalPaymentsSyncRequest { pub authz_id: String, } impl TryFrom<&types::PaymentsSyncRouterData> for DlocalPaymentsSyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { Ok(Self { authz_id: (item .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?), }) } } pub struct DlocalPaymentsCancelRequest { pub cancel_id: String, } impl TryFrom<&types::PaymentsCancelRouterData> for DlocalPaymentsCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { Ok(Self { cancel_id: item.request.connector_transaction_id.clone(), }) } } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct DlocalPaymentsCaptureRequest { pub authorization_id: String, pub amount: i64, pub currency: String, pub order_id: String, } impl TryFrom<&types::PaymentsCaptureRouterData> for DlocalPaymentsCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { Ok(Self { authorization_id: item.request.connector_transaction_id.clone(), amount: item.request.amount_to_capture, currency: item.request.currency.to_string(), order_id: item.connector_request_reference_id.clone(), }) } } // Auth Struct pub struct DlocalAuthType { pub(super) x_login: Secret<String>, pub(super) x_trans_key: Secret<String>, pub(super) secret: Secret<String>, } impl TryFrom<&ConnectorAuthType> for DlocalAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } = auth_type { Ok(Self { x_login: api_key.to_owned(), x_trans_key: key1.to_owned(), secret: api_secret.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } } } #[derive(Debug, Clone, Eq, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum DlocalPaymentStatus { Authorized, Paid, Verified, Cancelled, #[default] Pending, Rejected, } impl From<DlocalPaymentStatus> for enums::AttemptStatus { fn from(item: DlocalPaymentStatus) -> Self { match item { DlocalPaymentStatus::Authorized => Self::Authorized, DlocalPaymentStatus::Verified => Self::Authorized, DlocalPaymentStatus::Paid => Self::Charged, DlocalPaymentStatus::Pending => Self::AuthenticationPending, DlocalPaymentStatus::Cancelled => Self::Voided, DlocalPaymentStatus::Rejected => Self::AuthenticationFailed, } } } #[derive(Eq, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct ThreeDSecureResData { pub redirect_url: Option<Url>, } #[derive(Debug, Default, Eq, Clone, PartialEq, Serialize, Deserialize)] pub struct DlocalPaymentsResponse { status: DlocalPaymentStatus, id: String, three_dsecure: Option<ThreeDSecureResData>, order_id: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirection_data = item .response .three_dsecure .and_then(|three_secure_data| three_secure_data.redirect_url) .map(|redirect_url| RedirectForm::from((redirect_url, Method::Get))); let response = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.order_id.clone(), incremental_authorization_allowed: None, charges: None, }; Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(response), ..item.data }) } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DlocalPaymentsSyncResponse { status: DlocalPaymentStatus, id: String, order_id: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, DlocalPaymentsSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.order_id.clone(), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DlocalPaymentsCaptureResponse { status: DlocalPaymentStatus, id: String, order_id: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.order_id.clone(), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } pub struct DlocalPaymentsCancelResponse { status: DlocalPaymentStatus, order_id: String, } impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCancelResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, DlocalPaymentsCancelResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.order_id.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } // REFUND : #[derive(Default, Debug, Serialize)] pub struct DlocalRefundRequest { pub amount: String, pub payment_id: String, pub currency: enums::Currency, pub id: String, } impl<F> TryFrom<&DlocalRouterData<&types::RefundsRouterData<F>>> for DlocalRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &DlocalRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { let amount_to_refund = item.router_data.request.refund_amount.to_string(); Ok(Self { amount: amount_to_refund, payment_id: item.router_data.request.connector_transaction_id.clone(), currency: item.router_data.request.currency, id: item.router_data.request.refund_id.clone(), }) } } #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] #[serde(rename_all = "UPPERCASE")] pub enum RefundStatus { Success, #[default] Pending, Rejected, Cancelled, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Success => Self::Success, RefundStatus::Pending => Self::Pending, RefundStatus::Rejected => Self::ManualReview, RefundStatus::Cancelled => Self::Failure, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { pub id: String, pub status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status); Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }), ..item.data }) } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct DlocalRefundsSyncRequest { pub refund_id: String, } impl TryFrom<&types::RefundSyncRouterData> for DlocalRefundsSyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> { let refund_id = match item.request.connector_refund_id.clone() { Some(val) => val, None => item.request.refund_id.clone(), }; Ok(Self { refund_id: (refund_id), }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status); Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct DlocalErrorResponse { pub code: i32, pub message: String, pub param: Option<String>, } fn get_doc_from_currency(country: String) -> Secret<String> { let doc = match country.as_str() { "BR" => "91483309223", "ZA" => "2001014800086", "BD" | "GT" | "HN" | "PK" | "SN" | "TH" => "1234567890001", "CR" | "SV" | "VN" => "123456789", "DO" | "NG" => "12345678901", "EG" => "12345678901112", "GH" | "ID" | "RW" | "UG" => "1234567890111123", "IN" => "NHSTP6374G", "CI" => "CA124356789", "JP" | "MY" | "PH" => "123456789012", "NI" => "1234567890111A", "TZ" => "12345678912345678900", _ => "12345678", }; Secret::new(doc.to_string()) }
crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
hyperswitch_connectors::src::connectors::dlocal::transformers
4,462
true
// File: crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs // Module: hyperswitch_connectors::src::connectors::rapyd::transformers use common_enums::enums; use common_utils::{ ext_traits::OptionExt, request::Method, types::{FloatMajorUnit, MinorUnit}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types, }; use hyperswitch_interfaces::{consts::NO_ERROR_CODE, errors}; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{PaymentsAuthorizeRequestData, RouterData as _}, }; #[derive(Debug, Serialize)] pub struct RapydRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for RapydRouterData<T> { fn from((amount, router_data): (FloatMajorUnit, T)) -> Self { Self { amount, router_data, } } } #[derive(Default, Debug, Serialize)] pub struct RapydPaymentsRequest { pub amount: FloatMajorUnit, pub currency: enums::Currency, pub payment_method: PaymentMethod, pub payment_method_options: Option<PaymentMethodOptions>, pub merchant_reference_id: Option<String>, pub capture: Option<bool>, pub description: Option<String>, pub complete_payment_url: Option<String>, pub error_payment_url: Option<String>, } #[derive(Default, Debug, Serialize)] pub struct PaymentMethodOptions { #[serde(rename = "3d_required")] pub three_ds: bool, } #[derive(Default, Debug, Serialize)] pub struct PaymentMethod { #[serde(rename = "type")] pub pm_type: String, pub fields: Option<PaymentFields>, pub address: Option<Address>, pub digital_wallet: Option<RapydWallet>, } #[derive(Default, Debug, Serialize)] pub struct PaymentFields { pub number: cards::CardNumber, pub expiration_month: Secret<String>, pub expiration_year: Secret<String>, pub name: Secret<String>, pub cvv: Secret<String>, } #[derive(Default, Debug, Serialize)] pub struct Address { name: Secret<String>, line_1: Secret<String>, line_2: Option<Secret<String>>, line_3: Option<Secret<String>>, city: Option<String>, state: Option<Secret<String>>, country: Option<String>, zip: Option<Secret<String>>, phone_number: Option<Secret<String>>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RapydWallet { #[serde(rename = "type")] payment_type: String, #[serde(rename = "details")] token: Option<Secret<String>>, } impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &RapydRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let (capture, payment_method_options) = match item.router_data.payment_method { enums::PaymentMethod::Card => { let three_ds_enabled = matches!( item.router_data.auth_type, enums::AuthenticationType::ThreeDs ); let payment_method_options = PaymentMethodOptions { three_ds: three_ds_enabled, }; ( Some(matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic) | None )), Some(payment_method_options), ) } _ => (None, None), }; let payment_method = match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref ccard) => { Some(PaymentMethod { pm_type: "in_amex_card".to_owned(), //[#369] Map payment method type based on country fields: Some(PaymentFields { number: ccard.card_number.to_owned(), expiration_month: ccard.card_exp_month.to_owned(), expiration_year: ccard.card_exp_year.to_owned(), name: item .router_data .get_optional_billing_full_name() .to_owned() .unwrap_or(Secret::new("".to_string())), cvv: ccard.card_cvc.to_owned(), }), address: None, digital_wallet: None, }) } PaymentMethodData::Wallet(ref wallet_data) => { let digital_wallet = match wallet_data { WalletData::GooglePay(data) => Some(RapydWallet { payment_type: "google_pay".to_string(), token: Some(Secret::new( data.tokenization_data .get_encrypted_google_pay_token() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "gpay wallet_token", })? .to_owned(), )), }), WalletData::ApplePay(data) => { let apple_pay_encrypted_data = data .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", })?; Some(RapydWallet { payment_type: "apple_pay".to_string(), token: Some(Secret::new(apple_pay_encrypted_data.to_string())), }) } _ => None, }; Some(PaymentMethod { pm_type: "by_visa_card".to_string(), //[#369] fields: None, address: None, digital_wallet, }) } _ => None, } .get_required_value("payment_method not implemented") .change_context(errors::ConnectorError::NotImplemented( "payment_method".to_owned(), ))?; let return_url = item.router_data.request.get_router_return_url()?; Ok(Self { amount: item.amount, currency: item.router_data.request.currency, payment_method, capture, payment_method_options, merchant_reference_id: Some(item.router_data.connector_request_reference_id.clone()), description: None, error_payment_url: Some(return_url.clone()), complete_payment_url: Some(return_url), }) } } #[derive(Debug, Deserialize)] pub struct RapydAuthType { pub access_key: Secret<String>, pub secret_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for RapydAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { Ok(Self { access_key: api_key.to_owned(), secret_key: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[allow(clippy::upper_case_acronyms)] pub enum RapydPaymentStatus { #[serde(rename = "ACT")] Active, #[serde(rename = "CAN")] CanceledByClientOrBank, #[serde(rename = "CLO")] Closed, #[serde(rename = "ERR")] Error, #[serde(rename = "EXP")] Expired, #[serde(rename = "REV")] ReversedByRapyd, #[default] #[serde(rename = "NEW")] New, } fn get_status(status: RapydPaymentStatus, next_action: NextAction) -> enums::AttemptStatus { match (status, next_action) { (RapydPaymentStatus::Closed, _) => enums::AttemptStatus::Charged, ( RapydPaymentStatus::Active, NextAction::ThreedsVerification | NextAction::PendingConfirmation, ) => enums::AttemptStatus::AuthenticationPending, (RapydPaymentStatus::Active, NextAction::PendingCapture | NextAction::NotApplicable) => { enums::AttemptStatus::Authorized } ( RapydPaymentStatus::CanceledByClientOrBank | RapydPaymentStatus::Expired | RapydPaymentStatus::ReversedByRapyd, _, ) => enums::AttemptStatus::Voided, (RapydPaymentStatus::Error, _) => enums::AttemptStatus::Failure, (RapydPaymentStatus::New, _) => enums::AttemptStatus::Authorizing, } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct RapydPaymentsResponse { pub status: Status, pub data: Option<ResponseData>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Status { pub error_code: String, pub status: Option<String>, pub message: Option<String>, pub response_code: Option<String>, pub operation_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum NextAction { #[serde(rename = "3d_verification")] ThreedsVerification, #[serde(rename = "pending_capture")] PendingCapture, #[serde(rename = "not_applicable")] NotApplicable, #[serde(rename = "pending_confirmation")] PendingConfirmation, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct ResponseData { pub id: String, pub amount: i64, pub status: RapydPaymentStatus, pub next_action: NextAction, pub redirect_url: Option<String>, pub original_amount: Option<i64>, pub is_partial: Option<bool>, pub currency_code: Option<enums::Currency>, pub country_code: Option<String>, pub captured: Option<bool>, pub transaction_id: String, pub merchant_reference_id: Option<String>, pub paid: Option<bool>, pub failure_code: Option<String>, pub failure_message: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DisputeResponseData { pub id: String, pub amount: MinorUnit, pub currency: api_models::enums::Currency, pub token: String, pub dispute_reason_description: String, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub due_date: Option<PrimitiveDateTime>, pub status: RapydWebhookDisputeStatus, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub created_at: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub updated_at: Option<PrimitiveDateTime>, pub original_transaction_id: String, } #[derive(Default, Debug, Serialize)] pub struct RapydRefundRequest { pub payment: String, pub amount: Option<FloatMajorUnit>, pub currency: Option<enums::Currency>, } impl<F> TryFrom<&RapydRouterData<&types::RefundsRouterData<F>>> for RapydRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &RapydRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { payment: item .router_data .request .connector_transaction_id .to_string(), amount: Some(item.amount), currency: Some(item.router_data.request.currency), }) } } #[allow(dead_code)] #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] pub enum RefundStatus { Completed, Error, Rejected, #[default] Pending, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Completed => Self::Success, RefundStatus::Error | RefundStatus::Rejected => Self::Failure, RefundStatus::Pending => Self::Pending, } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { pub status: Status, pub data: Option<RefundResponseData>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct RefundResponseData { //Some field related to foreign exchange and split payment can be added as and when implemented pub id: String, pub payment: String, pub amount: i64, pub currency: enums::Currency, pub status: RefundStatus, pub created_at: Option<i64>, pub failure_reason: Option<String>, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let (connector_refund_id, refund_status) = match item.response.data { Some(data) => (data.id, enums::RefundStatus::from(data.status)), None => ( item.response.status.error_code, enums::RefundStatus::Failure, ), }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id, refund_status, }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let (connector_refund_id, refund_status) = match item.response.data { Some(data) => (data.id, enums::RefundStatus::from(data.status)), None => ( item.response.status.error_code, enums::RefundStatus::Failure, ), }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id, refund_status, }), ..item.data }) } } #[derive(Debug, Serialize, Clone)] pub struct CaptureRequest { amount: Option<FloatMajorUnit>, receipt_email: Option<Secret<String>>, statement_descriptor: Option<String>, } impl TryFrom<&RapydRouterData<&types::PaymentsCaptureRouterData>> for CaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &RapydRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { amount: Some(item.amount), receipt_email: None, statement_descriptor: None, }) } } impl<F, T> TryFrom<ResponseRouterData<F, RapydPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, RapydPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let (status, response) = match &item.response.data { Some(data) => { let attempt_status = get_status(data.status.to_owned(), data.next_action.to_owned()); match attempt_status { enums::AttemptStatus::Failure => ( enums::AttemptStatus::Failure, Err(ErrorResponse { code: data .failure_code .to_owned() .unwrap_or(item.response.status.error_code), status_code: item.http_code, message: item.response.status.status.unwrap_or_default(), reason: data.failure_message.to_owned(), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ), _ => { let redirection_url = data .redirect_url .as_ref() .filter(|redirect_str| !redirect_str.is_empty()) .map(|url| { Url::parse(url).change_context( errors::ConnectorError::FailedToObtainIntegrationUrl, ) }) .transpose()?; let redirection_data = redirection_url.map(|url| RedirectForm::from((url, Method::Get))); ( attempt_status, Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(data.id.to_owned()), //transaction_id is also the field but this id is used to initiate a refund redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: data .merchant_reference_id .to_owned(), incremental_authorization_allowed: None, charges: None, }), ) } } } None => ( enums::AttemptStatus::Failure, Err(ErrorResponse { code: item.response.status.error_code, status_code: item.http_code, message: item.response.status.status.unwrap_or_default(), reason: item.response.status.message, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ), }; Ok(Self { status, response, ..item.data }) } } #[derive(Debug, Deserialize)] pub struct RapydIncomingWebhook { pub id: String, #[serde(rename = "type")] pub webhook_type: RapydWebhookObjectEventType, pub data: WebhookData, pub trigger_operation_id: Option<String>, pub status: String, pub created_at: i64, } #[derive(Debug, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RapydWebhookObjectEventType { PaymentCompleted, PaymentCaptured, PaymentFailed, RefundCompleted, PaymentRefundRejected, PaymentRefundFailed, PaymentDisputeCreated, PaymentDisputeUpdated, #[serde(other)] Unknown, } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, strum::Display)] pub enum RapydWebhookDisputeStatus { #[serde(rename = "ACT")] Active, #[serde(rename = "RVW")] Review, #[serde(rename = "LOS")] Lose, #[serde(rename = "WIN")] Win, #[serde(other)] Unknown, } impl From<RapydWebhookDisputeStatus> for api_models::webhooks::IncomingWebhookEvent { fn from(value: RapydWebhookDisputeStatus) -> Self { match value { RapydWebhookDisputeStatus::Active => Self::DisputeOpened, RapydWebhookDisputeStatus::Review => Self::DisputeChallenged, RapydWebhookDisputeStatus::Lose => Self::DisputeLost, RapydWebhookDisputeStatus::Win => Self::DisputeWon, RapydWebhookDisputeStatus::Unknown => Self::EventNotSupported, } } } #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum WebhookData { Payment(ResponseData), Refund(RefundResponseData), Dispute(DisputeResponseData), } impl From<ResponseData> for RapydPaymentsResponse { fn from(value: ResponseData) -> Self { Self { status: Status { error_code: NO_ERROR_CODE.to_owned(), status: None, message: None, response_code: None, operation_id: None, }, data: Some(value), } } } impl From<RefundResponseData> for RefundResponse { fn from(value: RefundResponseData) -> Self { Self { status: Status { error_code: NO_ERROR_CODE.to_owned(), status: None, message: None, response_code: None, operation_id: None, }, data: Some(value), } } }
crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs
hyperswitch_connectors::src::connectors::rapyd::transformers
4,453
true
// File: crates/hyperswitch_connectors/src/connectors/mpgs/transformers.rs // Module: hyperswitch_connectors::src::connectors::mpgs::transformers use common_enums::enums; use common_utils::types::StringMinorUnit; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::types::{RefundsResponseRouterData, ResponseRouterData}; //TODO: Fill the struct with respective fields pub struct MpgsRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for MpgsRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { //Todo : use utils to convert the amount to the type of amount that a connector accepts Self { amount, router_data: item, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] pub struct MpgsPaymentsRequest { amount: StringMinorUnit, card: MpgsCard, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct MpgsCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } impl TryFrom<&MpgsRouterData<&PaymentsAuthorizeRouterData>> for MpgsPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &MpgsRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( "Card payment method not implemented".to_string(), ) .into()), _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } //TODO: Fill the struct with respective fields // Auth Struct pub struct MpgsAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for MpgsAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse //TODO: Append the remaining status flags #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum MpgsPaymentStatus { Succeeded, Failed, #[default] Processing, } impl From<MpgsPaymentStatus> for common_enums::AttemptStatus { fn from(item: MpgsPaymentStatus) -> Self { match item { MpgsPaymentStatus::Succeeded => Self::Charged, MpgsPaymentStatus::Failed => Self::Failure, MpgsPaymentStatus::Processing => Self::Authorizing, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct MpgsPaymentsResponse { status: MpgsPaymentStatus, id: String, } impl<F, T> TryFrom<ResponseRouterData<F, MpgsPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, MpgsPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } //TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct MpgsRefundRequest { pub amount: StringMinorUnit, } impl<F> TryFrom<&MpgsRouterData<&RefundsRouterData<F>>> for MpgsRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &MpgsRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct MpgsErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, pub network_advice_code: Option<String>, pub network_decline_code: Option<String>, pub network_error_message: Option<String>, }
crates/hyperswitch_connectors/src/connectors/mpgs/transformers.rs
hyperswitch_connectors::src::connectors::mpgs::transformers
1,690
true
// File: crates/hyperswitch_connectors/src/connectors/hyperwallet/transformers.rs // Module: hyperswitch_connectors::src::connectors::hyperwallet::transformers use common_enums::enums; use common_utils::types::StringMinorUnit; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::types::{RefundsResponseRouterData, ResponseRouterData}; //TODO: Fill the struct with respective fields pub struct HyperwalletRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for HyperwalletRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { //Todo : use utils to convert the amount to the type of amount that a connector accepts Self { amount, router_data: item, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] pub struct HyperwalletPaymentsRequest { amount: StringMinorUnit, card: HyperwalletCard, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct HyperwalletCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } impl TryFrom<&HyperwalletRouterData<&PaymentsAuthorizeRouterData>> for HyperwalletPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &HyperwalletRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( "Card payment method not implemented".to_string(), ) .into()), _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } //TODO: Fill the struct with respective fields // Auth Struct pub struct HyperwalletAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for HyperwalletAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse //TODO: Append the remaining status flags #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum HyperwalletPaymentStatus { Succeeded, Failed, #[default] Processing, } impl From<HyperwalletPaymentStatus> for common_enums::AttemptStatus { fn from(item: HyperwalletPaymentStatus) -> Self { match item { HyperwalletPaymentStatus::Succeeded => Self::Charged, HyperwalletPaymentStatus::Failed => Self::Failure, HyperwalletPaymentStatus::Processing => Self::Authorizing, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct HyperwalletPaymentsResponse { status: HyperwalletPaymentStatus, id: String, } impl<F, T> TryFrom<ResponseRouterData<F, HyperwalletPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, HyperwalletPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } //TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct HyperwalletRefundRequest { pub amount: StringMinorUnit, } impl<F> TryFrom<&HyperwalletRouterData<&RefundsRouterData<F>>> for HyperwalletRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &HyperwalletRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct HyperwalletErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, pub network_advice_code: Option<String>, pub network_decline_code: Option<String>, pub network_error_message: Option<String>, }
crates/hyperswitch_connectors/src/connectors/hyperwallet/transformers.rs
hyperswitch_connectors::src::connectors::hyperwallet::transformers
1,671
true
// File: crates/hyperswitch_connectors/src/connectors/paytm/transformers.rs // Module: hyperswitch_connectors::src::connectors::paytm::transformers use common_enums::enums; use common_utils::types::StringMinorUnit; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::types::{RefundsResponseRouterData, ResponseRouterData}; //TODO: Fill the struct with respective fields pub struct PaytmRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for PaytmRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { //Todo : use utils to convert the amount to the type of amount that a connector accepts Self { amount, router_data: item, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] pub struct PaytmPaymentsRequest { amount: StringMinorUnit, card: PaytmCard, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct PaytmCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } impl TryFrom<&PaytmRouterData<&PaymentsAuthorizeRouterData>> for PaytmPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaytmRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( "Card payment method not implemented".to_string(), ) .into()), _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } //TODO: Fill the struct with respective fields // Auth Struct pub struct PaytmAuthType { pub merchant_id: Secret<String>, pub merchant_key: Secret<String>, pub website: Secret<String>, } impl TryFrom<&ConnectorAuthType> for PaytmAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { merchant_id: key1.to_owned(), // merchant_id merchant_key: api_key.to_owned(), // signing key website: api_secret.to_owned(), // website name }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse //TODO: Append the remaining status flags #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum PaytmPaymentStatus { Succeeded, Failed, #[default] Processing, } impl From<PaytmPaymentStatus> for common_enums::AttemptStatus { fn from(item: PaytmPaymentStatus) -> Self { match item { PaytmPaymentStatus::Succeeded => Self::Charged, PaytmPaymentStatus::Failed => Self::Failure, PaytmPaymentStatus::Processing => Self::Authorizing, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PaytmPaymentsResponse { status: PaytmPaymentStatus, id: String, } impl<F, T> TryFrom<ResponseRouterData<F, PaytmPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaytmPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } //TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct PaytmRefundRequest { pub amount: StringMinorUnit, } impl<F> TryFrom<&PaytmRouterData<&RefundsRouterData<F>>> for PaytmRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaytmRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct PaytmErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, pub network_advice_code: Option<String>, pub network_decline_code: Option<String>, pub network_error_message: Option<String>, }
crates/hyperswitch_connectors/src/connectors/paytm/transformers.rs
hyperswitch_connectors::src::connectors::paytm::transformers
1,721
true
// File: crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs // Module: hyperswitch_connectors::src::connectors::bambora::transformers use base64::Engine; use common_enums::enums; use common_utils::{ ext_traits::ValueExt, pii::{Email, IpAddress}, types::FloatMajorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, ResponseId, }, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Deserializer, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, AddressDetailsData, BrowserInformationData, CardData as _, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, PaymentsSyncRequestData, RouterData as _, }, }; pub struct BamboraRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, } impl<T> TryFrom<(FloatMajorUnit, T)> for BamboraRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct BamboraCard { name: Secret<String>, number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvd: Secret<String>, complete: bool, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "3d_secure")] three_d_secure: Option<ThreeDSecure>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct ThreeDSecure { browser: Option<BamboraBrowserInfo>, //Needed only in case of 3Ds 2.0. Need to update request for this. enabled: bool, version: Option<i64>, auth_required: Option<bool>, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct BamboraBrowserInfo { accept_header: String, java_enabled: bool, language: String, color_depth: u8, screen_height: u32, screen_width: u32, time_zone: i32, user_agent: String, javascript_enabled: bool, } #[derive(Default, Debug, Serialize)] pub struct BamboraPaymentsRequest { order_number: String, amount: FloatMajorUnit, payment_method: PaymentMethod, customer_ip: Option<Secret<String, IpAddress>>, term_url: Option<String>, card: BamboraCard, billing: AddressData, } #[derive(Default, Debug, Serialize)] pub struct BamboraVoidRequest { amount: FloatMajorUnit, } fn get_browser_info( item: &types::PaymentsAuthorizeRouterData, ) -> Result<Option<BamboraBrowserInfo>, error_stack::Report<errors::ConnectorError>> { if matches!(item.auth_type, enums::AuthenticationType::ThreeDs) { item.request .browser_info .as_ref() .map(|info| { Ok(BamboraBrowserInfo { accept_header: info.get_accept_header()?, java_enabled: info.get_java_enabled()?, language: info.get_language()?, screen_height: info.get_screen_height()?, screen_width: info.get_screen_width()?, color_depth: info.get_color_depth()?, user_agent: info.get_user_agent()?, time_zone: info.get_time_zone()?, javascript_enabled: info.get_java_script_enabled()?, }) }) .transpose() } else { Ok(None) } } impl TryFrom<&CompleteAuthorizeData> for BamboraThreedsContinueRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: &CompleteAuthorizeData) -> Result<Self, Self::Error> { let card_response: CardResponse = value .redirect_response .as_ref() .and_then(|f| f.payload.to_owned()) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "redirect_response.payload", })? .parse_value("CardResponse") .change_context(errors::ConnectorError::ParsingFailed)?; let bambora_req = Self { payment_method: "credit_card".to_string(), card_response, }; Ok(bambora_req) } } impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for BamboraPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: BamboraRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let (three_ds, customer_ip) = match item.router_data.auth_type { enums::AuthenticationType::ThreeDs => ( Some(ThreeDSecure { enabled: true, browser: get_browser_info(item.router_data)?, version: Some(2), auth_required: Some(true), }), Some( item.router_data .request .get_browser_info()? .get_ip_address()?, ), ), enums::AuthenticationType::NoThreeDs => (None, None), }; let card = BamboraCard { name: item.router_data.get_billing_address()?.get_full_name()?, expiry_year: req_card.get_card_expiry_year_2_digit()?, number: req_card.card_number, expiry_month: req_card.card_exp_month, cvd: req_card.card_cvc, three_d_secure: three_ds, complete: item.router_data.request.is_auto_capture()?, }; let (country, province) = match ( item.router_data.get_optional_billing_country(), item.router_data.get_optional_billing_state_2_digit(), ) { (Some(billing_country), Some(billing_state)) => { (Some(billing_country), Some(billing_state)) } _ => (None, None), }; let billing = AddressData { name: item.router_data.get_optional_billing_full_name(), address_line1: item.router_data.get_optional_billing_line1(), address_line2: item.router_data.get_optional_billing_line2(), city: item.router_data.get_optional_billing_city(), province, country, postal_code: item.router_data.get_optional_billing_zip(), phone_number: item.router_data.get_optional_billing_phone_number(), email_address: item.router_data.get_optional_billing_email(), }; Ok(Self { order_number: item.router_data.connector_request_reference_id.clone(), amount: item.amount, payment_method: PaymentMethod::Card, card, customer_ip, term_url: item.router_data.request.complete_authorize_url.clone(), billing, }) } PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("bambora"), ) .into()) } } } } impl TryFrom<BamboraRouterData<&types::PaymentsCancelRouterData>> for BamboraVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: BamboraRouterData<&types::PaymentsCancelRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount, }) } } pub struct BamboraAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for BamboraAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { let auth_key = format!("{}:{}", key1.peek(), api_key.peek()); let auth_header = format!( "Passcode {}", common_utils::consts::BASE64_ENGINE.encode(auth_key) ); Ok(Self { api_key: Secret::new(auth_header), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } fn str_or_i32<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] #[serde(untagged)] enum StrOrI32 { Str(String), I32(i32), } let value = StrOrI32::deserialize(deserializer)?; let res = match value { StrOrI32::Str(v) => v, StrOrI32::I32(v) => v.to_string(), }; Ok(res) } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(untagged)] pub enum BamboraResponse { NormalTransaction(Box<BamboraPaymentsResponse>), ThreeDsResponse(Box<Bambora3DsResponse>), } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct BamboraPaymentsResponse { #[serde(deserialize_with = "str_or_i32")] id: String, authorizing_merchant_id: i32, #[serde(deserialize_with = "str_or_i32")] approved: String, #[serde(deserialize_with = "str_or_i32")] message_id: String, message: String, auth_code: String, created: String, amount: FloatMajorUnit, order_number: String, #[serde(rename = "type")] payment_type: String, comments: Option<String>, batch_number: Option<String>, total_refunds: Option<f32>, total_completions: Option<f32>, payment_method: String, card: CardData, billing: Option<AddressData>, shipping: Option<AddressData>, custom: CustomData, adjusted_by: Option<Vec<AdjustedBy>>, links: Vec<Links>, risk_score: Option<f32>, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Bambora3DsResponse { #[serde(rename = "3d_session_data")] three_d_session_data: Secret<String>, contents: String, } #[derive(Debug, Serialize, Default, Deserialize)] pub struct BamboraMeta { pub three_d_session_data: String, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct BamboraThreedsContinueRequest { pub(crate) payment_method: String, pub card_response: CardResponse, } #[derive(Default, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct CardResponse { pub(crate) cres: Option<common_utils::pii::SecretSerdeValue>, } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] pub struct CardData { name: Option<Secret<String>>, expiry_month: Option<Secret<String>>, expiry_year: Option<Secret<String>>, card_type: String, last_four: Secret<String>, card_bin: Option<Secret<String>>, avs_result: String, cvd_result: String, cavv_result: Option<String>, address_match: Option<i32>, postal_result: Option<i32>, avs: Option<AvsObject>, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct AvsObject { id: String, message: String, processed: bool, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct AddressData { name: Option<Secret<String>>, address_line1: Option<Secret<String>>, address_line2: Option<Secret<String>>, city: Option<String>, province: Option<Secret<String>>, country: Option<enums::CountryAlpha2>, postal_code: Option<Secret<String>>, phone_number: Option<Secret<String>>, email_address: Option<Email>, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CustomData { ref1: String, ref2: String, ref3: String, ref4: String, ref5: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct AdjustedBy { id: i32, #[serde(rename = "type")] adjusted_by_type: String, approval: i32, message: String, amount: FloatMajorUnit, created: String, url: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Links { rel: String, href: String, method: String, } #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethod { #[default] Card, Token, PaymentProfile, Cash, Cheque, Interac, ApplePay, AndroidPay, #[serde(rename = "3d_secure")] ThreeDSecure, ProcessorToken, } // Capture #[derive(Default, Debug, Clone, Serialize, PartialEq)] pub struct BamboraPaymentsCaptureRequest { amount: FloatMajorUnit, payment_method: PaymentMethod, } impl TryFrom<BamboraRouterData<&types::PaymentsCaptureRouterData>> for BamboraPaymentsCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: BamboraRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount, payment_method: PaymentMethod::Card, }) } } impl<F> TryFrom<ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, PaymentsResponseData>> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response { BamboraResponse::NormalTransaction(pg_response) => Ok(Self { status: if pg_response.approved.as_str() == "1" { match item.data.request.is_auto_capture()? { true => enums::AttemptStatus::Charged, false => enums::AttemptStatus::Authorized, } } else { match item.data.request.is_auto_capture()? { true => enums::AttemptStatus::Failure, false => enums::AttemptStatus::AuthorizationFailed, } }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(pg_response.id.to_string()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(pg_response.order_number.to_string()), incremental_authorization_allowed: None, charges: None, }), ..item.data }), BamboraResponse::ThreeDsResponse(response) => { let value = url::form_urlencoded::parse(response.contents.as_bytes()) .map(|(key, val)| [key, val].concat()) .collect(); let redirection_data = Some(RedirectForm::Html { html_data: value }); Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: Some( serde_json::to_value(BamboraMeta { three_d_session_data: response.three_d_session_data.expose(), }) .change_context(errors::ConnectorError::ResponseHandlingFailed)?, ), network_txn_id: None, connector_response_reference_id: Some( item.data.connector_request_reference_id.to_string(), ), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } } } impl<F> TryFrom< ResponseRouterData<F, BamboraPaymentsResponse, CompleteAuthorizeData, PaymentsResponseData>, > for RouterData<F, CompleteAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BamboraPaymentsResponse, CompleteAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { status: if item.response.approved.as_str() == "1" { match item.data.request.is_auto_capture()? { true => enums::AttemptStatus::Charged, false => enums::AttemptStatus::Authorized, } } else { match item.data.request.is_auto_capture()? { true => enums::AttemptStatus::Failure, false => enums::AttemptStatus::AuthorizationFailed, } }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.order_number.to_string()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl<F> TryFrom<ResponseRouterData<F, BamboraPaymentsResponse, PaymentsSyncData, PaymentsResponseData>> for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BamboraPaymentsResponse, PaymentsSyncData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { status: match item.data.request.is_auto_capture()? { true => { if item.response.approved.as_str() == "1" { enums::AttemptStatus::Charged } else { enums::AttemptStatus::Failure } } false => { if item.response.approved.as_str() == "1" { enums::AttemptStatus::Authorized } else { enums::AttemptStatus::AuthorizationFailed } } }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.order_number.to_string()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl<F> TryFrom< ResponseRouterData<F, BamboraPaymentsResponse, PaymentsCaptureData, PaymentsResponseData>, > for RouterData<F, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BamboraPaymentsResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { status: if item.response.approved.as_str() == "1" { enums::AttemptStatus::Charged } else { enums::AttemptStatus::Failure }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.order_number.to_string()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl<F> TryFrom< ResponseRouterData<F, BamboraPaymentsResponse, PaymentsCancelData, PaymentsResponseData>, > for RouterData<F, PaymentsCancelData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BamboraPaymentsResponse, PaymentsCancelData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { status: if item.response.approved.as_str() == "1" { enums::AttemptStatus::Voided } else { enums::AttemptStatus::VoidFailed }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.order_number.to_string()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct BamboraRefundRequest { amount: FloatMajorUnit, } impl<F> TryFrom<BamboraRouterData<&types::RefundsRouterData<F>>> for BamboraRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: BamboraRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount, }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, } } } #[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct RefundResponse { #[serde(deserialize_with = "str_or_i32")] pub id: String, pub authorizing_merchant_id: i32, #[serde(deserialize_with = "str_or_i32")] pub approved: String, #[serde(deserialize_with = "str_or_i32")] pub message_id: String, pub message: String, pub auth_code: String, pub created: String, pub amount: FloatMajorUnit, pub order_number: String, #[serde(rename = "type")] pub payment_type: String, pub comments: Option<String>, pub batch_number: Option<String>, pub total_refunds: Option<f32>, pub total_completions: Option<f32>, pub payment_method: String, pub card: CardData, pub billing: Option<AddressData>, pub shipping: Option<AddressData>, pub custom: CustomData, pub adjusted_by: Option<Vec<AdjustedBy>>, pub links: Vec<Links>, pub risk_score: Option<f32>, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = if item.response.approved.as_str() == "1" { enums::RefundStatus::Success } else { enums::RefundStatus::Failure }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status, }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = if item.response.approved.as_str() == "1" { enums::RefundStatus::Success } else { enums::RefundStatus::Failure }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status, }), ..item.data }) } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct BamboraErrorResponse { pub code: i32, pub category: i32, pub message: String, pub reference: String, pub details: Option<Vec<ErrorDetail>>, pub validation: Option<CardValidation>, pub card: Option<CardError>, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CardError { pub avs: AVSDetails, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct AVSDetails { pub message: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct ErrorDetail { field: String, message: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CardValidation { id: String, approved: i32, message_id: i32, message: String, auth_code: String, trans_date: String, order_number: String, type_: String, amount: f64, cvd_id: i32, }
crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
hyperswitch_connectors::src::connectors::bambora::transformers
5,928
true
// File: crates/hyperswitch_connectors/src/connectors/custombilling/transformers.rs // Module: hyperswitch_connectors::src::connectors::custombilling::transformers use common_enums::enums; use common_utils::types::StringMinorUnit; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::RouterData, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::PaymentsAuthorizeRequestData, }; //TODO: Fill the struct with respective fields pub struct CustombillingRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for CustombillingRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { //Todo : use utils to convert the amount to the type of amount that a connector accepts Self { amount, router_data: item, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] pub struct CustombillingPaymentsRequest { amount: StringMinorUnit, card: CustombillingCard, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct CustombillingCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } impl TryFrom<&CustombillingRouterData<&PaymentsAuthorizeRouterData>> for CustombillingPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CustombillingRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let card = CustombillingCard { number: req_card.card_number, expiry_month: req_card.card_exp_month, expiry_year: req_card.card_exp_year, cvc: req_card.card_cvc, complete: item.router_data.request.is_auto_capture()?, }; Ok(Self { amount: item.amount.clone(), card, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } // PaymentsResponse //TODO: Append the remaining status flags #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum CustombillingPaymentStatus { Succeeded, Failed, #[default] Processing, } impl From<CustombillingPaymentStatus> for common_enums::AttemptStatus { fn from(item: CustombillingPaymentStatus) -> Self { match item { CustombillingPaymentStatus::Succeeded => Self::Charged, CustombillingPaymentStatus::Failed => Self::Failure, CustombillingPaymentStatus::Processing => Self::Authorizing, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CustombillingPaymentsResponse { status: CustombillingPaymentStatus, id: String, } impl<F, T> TryFrom<ResponseRouterData<F, CustombillingPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, CustombillingPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } //TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct CustombillingRefundRequest { pub amount: StringMinorUnit, } impl<F> TryFrom<&CustombillingRouterData<&RefundsRouterData<F>>> for CustombillingRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &CustombillingRouterData<&RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct CustombillingErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, }
crates/hyperswitch_connectors/src/connectors/custombilling/transformers.rs
hyperswitch_connectors::src::connectors::custombilling::transformers
1,570
true
// File: crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs // Module: hyperswitch_connectors::src::connectors::gocardless::transformers use common_enums::{enums, CountryAlpha2, UsStatesAbbreviation}; use common_utils::{ id_type, pii::{self, IpAddress}, types::MinorUnit, }; use hyperswitch_domain_models::{ address::AddressDetails, payment_method_data::{BankDebitData, PaymentMethodData}, router_data::{ConnectorAuthType, PaymentMethodToken, RouterData}, router_flow_types::refunds::Execute, router_request_types::{ ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsSyncData, ResponseId, SetupMandateRequestData, }, router_response_types::{ ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RefundsResponseData, }, types, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, AddressDetailsData, BrowserInformationData, CustomerData, ForeignTryFrom, PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData, RouterData as _, }, }; pub struct GocardlessRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> From<(MinorUnit, T)> for GocardlessRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Default, Debug, Serialize)] pub struct GocardlessCustomerRequest { customers: GocardlessCustomer, } #[derive(Default, Debug, Serialize)] pub struct GocardlessCustomer { address_line1: Option<Secret<String>>, address_line2: Option<Secret<String>>, address_line3: Option<Secret<String>>, city: Option<Secret<String>>, region: Option<Secret<String>>, country_code: Option<CountryAlpha2>, email: pii::Email, given_name: Secret<String>, family_name: Secret<String>, metadata: CustomerMetaData, danish_identity_number: Option<Secret<String>>, postal_code: Option<Secret<String>>, swedish_identity_number: Option<Secret<String>>, } #[derive(Default, Debug, Serialize)] pub struct CustomerMetaData { crm_id: Option<Secret<id_type::CustomerId>>, } impl TryFrom<&types::ConnectorCustomerRouterData> for GocardlessCustomerRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> { let email = item.request.get_email()?; let billing_details_name = item.get_billing_full_name()?.expose(); let (given_name, family_name) = billing_details_name .trim() .rsplit_once(' ') .unwrap_or((&billing_details_name, &billing_details_name)); let billing_address = item.get_billing_address()?; let metadata = CustomerMetaData { crm_id: item.customer_id.clone().map(Secret::new), }; let region = get_region(billing_address)?; Ok(Self { customers: GocardlessCustomer { email, given_name: Secret::new(given_name.to_string()), family_name: Secret::new(family_name.to_string()), metadata, address_line1: billing_address.line1.to_owned(), address_line2: billing_address.line2.to_owned(), address_line3: billing_address.line3.to_owned(), country_code: billing_address.country, region, // Should be populated based on the billing country danish_identity_number: None, postal_code: billing_address.zip.to_owned(), // Should be populated based on the billing country swedish_identity_number: None, city: billing_address.city.clone().map(Secret::new), }, }) } } fn get_region( address_details: &AddressDetails, ) -> Result<Option<Secret<String>>, error_stack::Report<errors::ConnectorError>> { match address_details.country { Some(CountryAlpha2::US) => { let state = address_details.get_state()?.to_owned(); Ok(Some(Secret::new( UsStatesAbbreviation::foreign_try_from(state.expose())?.to_string(), ))) } _ => Ok(None), } } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct GocardlessCustomerResponse { customers: Customers, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Customers { id: Secret<String>, } impl<F> TryFrom< ResponseRouterData< F, GocardlessCustomerResponse, ConnectorCustomerData, PaymentsResponseData, >, > for RouterData<F, ConnectorCustomerData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, GocardlessCustomerResponse, ConnectorCustomerData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PaymentsResponseData::ConnectorCustomerResponse( ConnectorCustomerResponseData::new_with_customer_id( item.response.customers.id.expose(), ), )), ..item.data }) } } #[derive(Debug, Serialize)] pub struct GocardlessBankAccountRequest { customer_bank_accounts: CustomerBankAccounts, } #[derive(Debug, Serialize)] pub struct CustomerBankAccounts { #[serde(flatten)] accounts: CustomerBankAccount, links: CustomerAccountLink, } #[derive(Debug, Serialize)] pub struct CustomerAccountLink { customer: Secret<String>, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum CustomerBankAccount { InternationalBankAccount(InternationalBankAccount), AUBankAccount(AUBankAccount), USBankAccount(USBankAccount), } #[derive(Debug, Serialize)] pub struct InternationalBankAccount { iban: Secret<String>, account_holder_name: Secret<String>, } #[derive(Debug, Serialize)] pub struct AUBankAccount { country_code: CountryAlpha2, account_number: Secret<String>, branch_code: Secret<String>, account_holder_name: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] pub struct USBankAccount { country_code: CountryAlpha2, account_number: Secret<String>, bank_code: Secret<String>, account_type: AccountType, account_holder_name: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] pub enum AccountType { Checking, Savings, } impl TryFrom<&types::TokenizationRouterData> for GocardlessBankAccountRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { let customer = item.get_connector_customer_id()?; let accounts = CustomerBankAccount::try_from(item)?; let links = CustomerAccountLink { customer: Secret::new(customer), }; Ok(Self { customer_bank_accounts: CustomerBankAccounts { accounts, links }, }) } } impl TryFrom<&types::TokenizationRouterData> for CustomerBankAccount { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { match &item.request.payment_method_data { PaymentMethodData::BankDebit(bank_debit_data) => { Self::try_from((bank_debit_data, item)) } PaymentMethodData::Card(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Gocardless"), ) .into()) } } } } impl TryFrom<(&BankDebitData, &types::TokenizationRouterData)> for CustomerBankAccount { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (bank_debit_data, item): (&BankDebitData, &types::TokenizationRouterData), ) -> Result<Self, Self::Error> { match bank_debit_data { BankDebitData::AchBankDebit { account_number, routing_number, bank_type, .. } => { let bank_type = bank_type.ok_or_else(utils::missing_field_err("bank_type"))?; let country_code = item.get_billing_country()?; let account_holder_name = item.get_billing_full_name()?; let us_bank_account = USBankAccount { country_code, account_number: account_number.clone(), bank_code: routing_number.clone(), account_type: AccountType::from(bank_type), account_holder_name, }; Ok(Self::USBankAccount(us_bank_account)) } BankDebitData::BecsBankDebit { account_number, bsb_number, .. } => { let country_code = item.get_billing_country()?; let account_holder_name = item.get_billing_full_name()?; let au_bank_account = AUBankAccount { country_code, account_number: account_number.clone(), branch_code: bsb_number.clone(), account_holder_name, }; Ok(Self::AUBankAccount(au_bank_account)) } BankDebitData::SepaBankDebit { iban, .. } => { let account_holder_name = item.get_billing_full_name()?; let international_bank_account = InternationalBankAccount { iban: iban.clone(), account_holder_name, }; Ok(Self::InternationalBankAccount(international_bank_account)) } BankDebitData::BacsBankDebit { .. } | BankDebitData::SepaGuarenteedBankDebit { .. } => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Gocardless"), ) .into()) } } } } impl From<common_enums::BankType> for AccountType { fn from(item: common_enums::BankType) -> Self { match item { common_enums::BankType::Checking => Self::Checking, common_enums::BankType::Savings => Self::Savings, } } } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct GocardlessBankAccountResponse { customer_bank_accounts: CustomerBankAccountResponse, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct CustomerBankAccountResponse { pub id: Secret<String>, } impl<F> TryFrom< ResponseRouterData< F, GocardlessBankAccountResponse, PaymentMethodTokenizationData, PaymentsResponseData, >, > for RouterData<F, PaymentMethodTokenizationData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, GocardlessBankAccountResponse, PaymentMethodTokenizationData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PaymentsResponseData::TokenizationResponse { token: item.response.customer_bank_accounts.id.expose(), }), ..item.data }) } } #[derive(Debug, Serialize)] pub struct GocardlessMandateRequest { mandates: Mandate, } #[derive(Debug, Serialize)] pub struct Mandate { scheme: GocardlessScheme, metadata: MandateMetaData, payer_ip_address: Option<Secret<String, IpAddress>>, links: MandateLink, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum GocardlessScheme { Becs, SepaCore, Ach, BecsNz, } #[derive(Debug, Serialize)] pub struct MandateMetaData { payment_reference: String, } #[derive(Debug, Serialize)] pub struct MandateLink { customer_bank_account: Secret<String>, } impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { let (scheme, payer_ip_address) = match &item.request.payment_method_data { PaymentMethodData::BankDebit(bank_debit_data) => { let payer_ip_address = get_ip_if_required(bank_debit_data, item)?; Ok(( GocardlessScheme::try_from(bank_debit_data)?, payer_ip_address, )) } PaymentMethodData::Card(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( "Setup Mandate flow for selected payment method through Gocardless".to_string(), )) } }?; let payment_method_token = item.get_payment_method_token()?; let customer_bank_account = match payment_method_token { PaymentMethodToken::Token(token) => Ok(token), PaymentMethodToken::ApplePayDecrypt(_) | PaymentMethodToken::PazeDecrypt(_) | PaymentMethodToken::GooglePayDecrypt(_) => { Err(errors::ConnectorError::NotImplemented( "Setup Mandate flow for selected payment method through Gocardless".to_string(), )) } }?; Ok(Self { mandates: Mandate { scheme, metadata: MandateMetaData { payment_reference: item.connector_request_reference_id.clone(), }, payer_ip_address, links: MandateLink { customer_bank_account, }, }, }) } } fn get_ip_if_required( bank_debit_data: &BankDebitData, item: &types::SetupMandateRouterData, ) -> Result<Option<Secret<String, IpAddress>>, error_stack::Report<errors::ConnectorError>> { let ip_address = item.request.get_browser_info()?.get_ip_address()?; match bank_debit_data { BankDebitData::AchBankDebit { .. } => Ok(Some(ip_address)), BankDebitData::SepaBankDebit { .. } | BankDebitData::SepaGuarenteedBankDebit { .. } | BankDebitData::BecsBankDebit { .. } | BankDebitData::BacsBankDebit { .. } => Ok(None), } } impl TryFrom<&BankDebitData> for GocardlessScheme { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &BankDebitData) -> Result<Self, Self::Error> { match item { BankDebitData::AchBankDebit { .. } => Ok(Self::Ach), BankDebitData::SepaBankDebit { .. } => Ok(Self::SepaCore), BankDebitData::BecsBankDebit { .. } => Ok(Self::Becs), BankDebitData::BacsBankDebit { .. } | BankDebitData::SepaGuarenteedBankDebit { .. } => { Err(errors::ConnectorError::NotImplemented( "Setup Mandate flow for selected payment method through Gocardless".to_string(), ) .into()) } } } } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct GocardlessMandateResponse { mandates: MandateResponse, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct MandateResponse { id: Secret<String>, } impl<F> TryFrom< ResponseRouterData< F, GocardlessMandateResponse, SetupMandateRequestData, PaymentsResponseData, >, > for RouterData<F, SetupMandateRequestData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, GocardlessMandateResponse, SetupMandateRequestData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let mandate_reference = Some(MandateReference { connector_mandate_id: Some(item.response.mandates.id.clone().expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }); Ok(Self { response: Ok(PaymentsResponseData::TransactionResponse { connector_metadata: None, connector_response_reference_id: None, incremental_authorization_allowed: None, resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference), network_txn_id: None, charges: None, }), status: enums::AttemptStatus::Charged, ..item.data }) } } #[derive(Debug, Serialize)] pub struct GocardlessPaymentsRequest { payments: GocardlessPayment, } #[derive(Debug, Serialize)] pub struct GocardlessPayment { amount: MinorUnit, currency: enums::Currency, description: Option<String>, metadata: PaymentMetaData, links: PaymentLink, } #[derive(Debug, Serialize)] pub struct PaymentMetaData { payment_reference: String, } #[derive(Debug, Serialize)] pub struct PaymentLink { mandate: Secret<String>, } impl TryFrom<&GocardlessRouterData<&types::PaymentsAuthorizeRouterData>> for GocardlessPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &GocardlessRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let mandate_id = if item.router_data.request.is_mandate_payment() { item.router_data .request .connector_mandate_id() .ok_or_else(utils::missing_field_err("mandate_id")) } else { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("gocardless"), ) .into()) }?; let payments = GocardlessPayment { amount: item.router_data.request.minor_amount, currency: item.router_data.request.currency, description: item.router_data.description.clone(), metadata: PaymentMetaData { payment_reference: item.router_data.connector_request_reference_id.clone(), }, links: PaymentLink { mandate: Secret::new(mandate_id), }, }; Ok(Self { payments }) } } // Auth Struct pub struct GocardlessAuthType { pub(super) access_token: Secret<String>, } impl TryFrom<&ConnectorAuthType> for GocardlessAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { access_token: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum GocardlessPaymentStatus { PendingCustomerApproval, PendingSubmission, Submitted, Confirmed, PaidOut, Cancelled, CustomerApprovalDenied, Failed, } impl From<GocardlessPaymentStatus> for enums::AttemptStatus { fn from(item: GocardlessPaymentStatus) -> Self { match item { GocardlessPaymentStatus::PendingCustomerApproval | GocardlessPaymentStatus::PendingSubmission | GocardlessPaymentStatus::Submitted => Self::Pending, GocardlessPaymentStatus::Confirmed | GocardlessPaymentStatus::PaidOut => Self::Charged, GocardlessPaymentStatus::Cancelled => Self::Voided, GocardlessPaymentStatus::CustomerApprovalDenied => Self::AuthenticationFailed, GocardlessPaymentStatus::Failed => Self::Failure, } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct GocardlessPaymentsResponse { payments: PaymentResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentResponse { status: GocardlessPaymentStatus, id: String, } impl<F> TryFrom< ResponseRouterData< F, GocardlessPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, GocardlessPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let mandate_reference = MandateReference { connector_mandate_id: Some(item.data.request.get_connector_mandate_id()?), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }; Ok(Self { status: enums::AttemptStatus::from(item.response.payments.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id), redirection_data: Box::new(None), mandate_reference: Box::new(Some(mandate_reference)), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl<F> TryFrom< ResponseRouterData<F, GocardlessPaymentsResponse, PaymentsSyncData, PaymentsResponseData>, > for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, GocardlessPaymentsResponse, PaymentsSyncData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.payments.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } // REFUND : #[derive(Default, Debug, Serialize)] pub struct GocardlessRefundRequest { refunds: GocardlessRefund, } #[derive(Default, Debug, Serialize)] pub struct GocardlessRefund { amount: MinorUnit, metadata: RefundMetaData, links: RefundLink, } #[derive(Default, Debug, Serialize)] pub struct RefundMetaData { refund_reference: String, } #[derive(Default, Debug, Serialize)] pub struct RefundLink { payment: String, } impl<F> TryFrom<&GocardlessRouterData<&types::RefundsRouterData<F>>> for GocardlessRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &GocardlessRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { refunds: GocardlessRefund { amount: item.amount.to_owned(), metadata: RefundMetaData { refund_reference: item.router_data.connector_request_reference_id.clone(), }, links: RefundLink { payment: item.router_data.request.connector_transaction_id.clone(), }, }, }) } } #[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct RefundResponse { id: String, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::Pending, }), ..item.data }) } } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct GocardlessErrorResponse { pub error: GocardlessError, } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct GocardlessError { pub message: String, pub code: u16, pub errors: Vec<Error>, #[serde(rename = "type")] pub error_type: String, } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Error { pub field: Option<String>, pub message: String, } #[derive(Debug, Deserialize)] pub struct GocardlessWebhookEvent { pub events: Vec<WebhookEvent>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct WebhookEvent { pub resource_type: WebhookResourceType, pub action: WebhookAction, pub links: WebhooksLink, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum WebhookResourceType { Payments, Refunds, Mandates, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum WebhookAction { PaymentsAction(PaymentsAction), RefundsAction(RefundsAction), MandatesAction(MandatesAction), } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum PaymentsAction { Created, CustomerApprovalGranted, CustomerApprovalDenied, Submitted, Confirmed, PaidOut, LateFailureSettled, SurchargeFeeDebited, Failed, Cancelled, ResubmissionRequired, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RefundsAction { Created, Failed, Paid, // Payout statuses RefundSettled, FundsReturned, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum MandatesAction { Created, CustomerApprovalGranted, CustomerApprovalSkipped, Active, Cancelled, Failed, Transferred, Expired, Submitted, ResubmissionRequested, Reinstated, Replaced, Consumed, Blocked, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum WebhooksLink { PaymentWebhooksLink(PaymentWebhooksLink), RefundWebhookLink(RefundWebhookLink), MandateWebhookLink(MandateWebhookLink), } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct RefundWebhookLink { pub refund: String, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct PaymentWebhooksLink { pub payment: String, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct MandateWebhookLink { pub mandate: String, } impl TryFrom<&WebhookEvent> for GocardlessPaymentsResponse { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &WebhookEvent) -> Result<Self, Self::Error> { let id = match &item.links { WebhooksLink::PaymentWebhooksLink(link) => link.payment.to_owned(), WebhooksLink::RefundWebhookLink(_) | WebhooksLink::MandateWebhookLink(_) => { Err(errors::ConnectorError::WebhookEventTypeNotFound)? } }; Ok(Self { payments: PaymentResponse { status: GocardlessPaymentStatus::try_from(&item.action)?, id, }, }) } } impl TryFrom<&WebhookAction> for GocardlessPaymentStatus { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &WebhookAction) -> Result<Self, Self::Error> { match item { WebhookAction::PaymentsAction(action) => match action { PaymentsAction::CustomerApprovalGranted | PaymentsAction::Submitted => { Ok(Self::Submitted) } PaymentsAction::CustomerApprovalDenied => Ok(Self::CustomerApprovalDenied), PaymentsAction::LateFailureSettled => Ok(Self::Failed), PaymentsAction::Failed => Ok(Self::Failed), PaymentsAction::Cancelled => Ok(Self::Cancelled), PaymentsAction::Confirmed => Ok(Self::Confirmed), PaymentsAction::PaidOut => Ok(Self::PaidOut), PaymentsAction::SurchargeFeeDebited | PaymentsAction::ResubmissionRequired | PaymentsAction::Created => Err(errors::ConnectorError::WebhookEventTypeNotFound)?, }, WebhookAction::RefundsAction(_) | WebhookAction::MandatesAction(_) => { Err(errors::ConnectorError::WebhookEventTypeNotFound)? } } } }
crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
hyperswitch_connectors::src::connectors::gocardless::transformers
6,636
true
// File: crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs // Module: hyperswitch_connectors::src::connectors::netcetera::transformers use common_enums::enums; use common_utils::{ext_traits::OptionExt as _, types::SemanticVersion}; use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, ErrorResponse}, router_flow_types::authentication::{Authentication, PreAuthentication}, router_request_types::authentication::{ AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData, MessageExtensionAttribute, PreAuthNRequestData, }, router_response_types::AuthenticationResponseData, }; use hyperswitch_interfaces::{api::CurrencyUnit, errors::ConnectorError}; use masking::Secret; use serde::{Deserialize, Serialize}; use super::netcetera_types; use crate::{ types::{ConnectorAuthenticationRouterData, PreAuthNRouterData, ResponseRouterData}, utils::{get_card_details, to_connector_meta_from_secret, CardData as _}, }; //TODO: Fill the struct with respective fields pub struct NetceteraRouterData<T> { pub amount: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for NetceteraRouterData<T> { type Error = error_stack::Report<ConnectorError>; fn try_from( (_currency_unit, _currency, amount, item): (&CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { //Todo : use utils to convert the amount to the type of amount that a connector accepts Ok(Self { amount, router_data: item, }) } } impl<T> TryFrom<(i64, T)> for NetceteraRouterData<T> { type Error = error_stack::Report<ConnectorError>; fn try_from((amount, router_data): (i64, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data, }) } } impl TryFrom< ResponseRouterData< PreAuthentication, NetceteraPreAuthenticationResponse, PreAuthNRequestData, AuthenticationResponseData, >, > for PreAuthNRouterData { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData< PreAuthentication, NetceteraPreAuthenticationResponse, PreAuthNRequestData, AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let response = match item.response { NetceteraPreAuthenticationResponse::Success(pre_authn_response) => { // if card is not enrolled for 3ds, card_range will be None let card_range = pre_authn_response.get_card_range_if_available(); let maximum_supported_3ds_version = card_range .as_ref() .map(|card_range| card_range.highest_common_supported_version.clone()) .unwrap_or_else(|| { // Version "0.0.0" will be less that "2.0.0", hence we will treat this card as not eligible for 3ds authentication SemanticVersion::new(0, 0, 0) }); let three_ds_method_data = card_range.as_ref().and_then(|card_range| { card_range .three_ds_method_data_form .as_ref() .map(|data| data.three_ds_method_data.clone()) }); let three_ds_method_url = card_range .as_ref() .and_then(|card_range| card_range.get_three_ds_method_url()); Ok(AuthenticationResponseData::PreAuthNResponse { threeds_server_transaction_id: pre_authn_response .three_ds_server_trans_id .clone(), maximum_supported_3ds_version: maximum_supported_3ds_version.clone(), connector_authentication_id: pre_authn_response.three_ds_server_trans_id, three_ds_method_data, three_ds_method_url, message_version: maximum_supported_3ds_version, connector_metadata: None, directory_server_id: card_range .as_ref() .and_then(|card_range| card_range.directory_server_id.clone()), }) } NetceteraPreAuthenticationResponse::Failure(error_response) => Err(ErrorResponse { code: error_response.error_details.error_code, message: error_response.error_details.error_description, reason: error_response.error_details.error_detail, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), }; Ok(Self { response, ..item.data.clone() }) } } impl TryFrom< ResponseRouterData< Authentication, NetceteraAuthenticationResponse, ConnectorAuthenticationRequestData, AuthenticationResponseData, >, > for ConnectorAuthenticationRouterData { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData< Authentication, NetceteraAuthenticationResponse, ConnectorAuthenticationRequestData, AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let response = match item.response { NetceteraAuthenticationResponse::Success(response) => { let authn_flow_type = match response.acs_challenge_mandated { Some(ACSChallengeMandatedIndicator::Y) => { AuthNFlowType::Challenge(Box::new(ChallengeParams { acs_url: response.authentication_response.acs_url.clone(), challenge_request: response.encoded_challenge_request, acs_reference_number: response .authentication_response .acs_reference_number, acs_trans_id: response.authentication_response.acs_trans_id, three_dsserver_trans_id: Some(response.three_ds_server_trans_id), acs_signed_content: response.authentication_response.acs_signed_content, challenge_request_key: None, })) } Some(ACSChallengeMandatedIndicator::N) | None => AuthNFlowType::Frictionless, }; let challenge_code = response .authentication_request .as_ref() .and_then(|req| req.three_ds_requestor_challenge_ind.as_ref()) .and_then(|ind| match ind { ThreedsRequestorChallengeInd::Single(s) => Some(s.clone()), ThreedsRequestorChallengeInd::Multiple(v) => v.first().cloned(), }); let message_extension = response .authentication_response .message_extension .as_ref() .and_then(|v| match serde_json::to_value(v) { Ok(val) => Some(Secret::new(val)), Err(e) => { router_env::logger::error!( "Failed to serialize message_extension: {:?}", e ); None } }); Ok(AuthenticationResponseData::AuthNResponse { authn_flow_type, authentication_value: response.authentication_value, trans_status: response.trans_status, connector_metadata: None, ds_trans_id: response.authentication_response.ds_trans_id, eci: response.eci, challenge_code, challenge_cancel: None, // Note - challenge_cancel field is received in the RReq and updated in DB during external_authentication_incoming_webhook_flow challenge_code_reason: response.authentication_response.trans_status_reason, message_extension, }) } NetceteraAuthenticationResponse::Error(error_response) => Err(ErrorResponse { code: error_response.error_details.error_code, message: error_response.error_details.error_description, reason: error_response.error_details.error_detail, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), }; Ok(Self { response, ..item.data.clone() }) } } pub struct NetceteraAuthType { pub(super) certificate: Secret<String>, pub(super) private_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for NetceteraAuthType { type Error = error_stack::Report<ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type.to_owned() { ConnectorAuthType::CertificateAuth { certificate, private_key, } => Ok(Self { certificate, private_key, }), _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NetceteraErrorResponse { pub three_ds_server_trans_id: Option<String>, pub error_details: NetceteraErrorDetails, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NetceteraErrorDetails { /// Universally unique identifier for the transaction assigned by the 3DS Server. #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: Option<String>, /// Universally Unique identifier for the transaction assigned by the ACS. #[serde(rename = "acsTransID")] pub acs_trans_id: Option<String>, /// Universally unique identifier for the transaction assigned by the DS. #[serde(rename = "dsTransID")] pub ds_trans_id: Option<String>, /// Code indicating the type of problem identified. pub error_code: String, /// Code indicating the 3-D Secure component that identified the error. pub error_component: Option<String>, /// Text describing the problem identified. pub error_description: String, /// Additional detail regarding the problem identified. pub error_detail: Option<String>, /// Universally unique identifier for the transaction assigned by the 3DS SDK. #[serde(rename = "sdkTransID")] pub sdk_trans_id: Option<String>, /// The Message Type that was identified as erroneous. pub error_message_type: Option<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct NetceteraMetaData { pub mcc: Option<String>, pub merchant_country_code: Option<String>, pub merchant_name: Option<String>, pub endpoint_prefix: String, pub three_ds_requestor_name: Option<String>, pub three_ds_requestor_id: Option<String>, pub merchant_configuration_id: Option<String>, } impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for NetceteraMetaData { type Error = error_stack::Report<ConnectorError>; fn try_from( meta_data: &Option<common_utils::pii::SecretSerdeValue>, ) -> Result<Self, Self::Error> { let metadata: Self = to_connector_meta_from_secret::<Self>(meta_data.clone()) .change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?; Ok(metadata) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NetceteraPreAuthenticationRequest { cardholder_account_number: cards::CardNumber, scheme_id: Option<netcetera_types::SchemeId>, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum NetceteraPreAuthenticationResponse { Success(Box<NetceteraPreAuthenticationResponseData>), Failure(Box<NetceteraErrorResponse>), } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NetceteraPreAuthenticationResponseData { #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, pub card_ranges: Vec<CardRange>, } impl NetceteraPreAuthenticationResponseData { pub fn get_card_range_if_available(&self) -> Option<CardRange> { let card_range = self .card_ranges .iter() .max_by_key(|card_range| &card_range.highest_common_supported_version); card_range.cloned() } } #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct CardRange { pub scheme_id: netcetera_types::SchemeId, pub directory_server_id: Option<String>, pub acs_protocol_versions: Vec<AcsProtocolVersion>, #[serde(rename = "threeDSMethodDataForm")] pub three_ds_method_data_form: Option<ThreeDSMethodDataForm>, pub highest_common_supported_version: SemanticVersion, } impl CardRange { pub fn get_three_ds_method_url(&self) -> Option<String> { self.acs_protocol_versions .iter() .find(|acs_protocol_version| { acs_protocol_version.version == self.highest_common_supported_version }) .and_then(|acs_version| acs_version.three_ds_method_url.clone()) } } #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct ThreeDSMethodDataForm { // base64 encoded value for 3ds method data collection #[serde(rename = "threeDSMethodData")] pub three_ds_method_data: String, } #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct AcsProtocolVersion { pub version: SemanticVersion, #[serde(rename = "threeDSMethodURL")] pub three_ds_method_url: Option<String>, } impl TryFrom<&NetceteraRouterData<&PreAuthNRouterData>> for NetceteraPreAuthenticationRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(value: &NetceteraRouterData<&PreAuthNRouterData>) -> Result<Self, Self::Error> { let router_data = value.router_data; let is_cobadged_card = || { router_data .request .card .card_number .is_cobadged_card() .change_context(ConnectorError::RequestEncodingFailed) .attach_printable("error while checking is_cobadged_card") }; Ok(Self { cardholder_account_number: router_data.request.card.card_number.clone(), scheme_id: router_data .request .card .card_network .clone() .map(|card_network| { is_cobadged_card().map(|is_cobadged_card| { is_cobadged_card .then_some(netcetera_types::SchemeId::try_from(card_network)) }) }) .transpose()? .flatten() .transpose()?, }) } } #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(rename_all = "camelCase")] #[serde_with::skip_serializing_none] pub struct NetceteraAuthenticationRequest { /// Specifies the preferred version of 3D Secure protocol to be utilized while executing 3D Secure authentication. /// 3DS Server initiates an authentication request with the preferred version and if this version is not supported by /// other 3D Secure components, it falls back to the next supported version(s) and continues authentication. /// /// If the preferred version is enforced by setting #enforcePreferredProtocolVersion flag, but this version /// is not supported by one of the 3D Secure components, 3DS Server does not initiate an authentication and provides /// corresponding error message to the customer. /// /// The accepted values are: /// - 2.1.0 -> prefer authentication with 2.1.0 version, /// - 2.2.0 -> prefer authentication with 2.2.0 version, /// - 2.3.1 -> prefer authentication with 2.3.1 version, /// - latest -> prefer authentication with the latest version, the 3DS Server is certified for. 2.3.1 at this moment. pub preferred_protocol_version: Option<SemanticVersion>, /// Boolean flag that enforces preferred 3D Secure protocol version to be used in 3D Secure authentication. /// The value should be set true to enforce preferred version. If value is false or not provided, /// 3DS Server can fall back to next supported 3DS protocol version while initiating 3D Secure authentication. /// /// For application initiated transactions (deviceChannel = '01'), the preferred protocol version must be enforced. pub enforce_preferred_protocol_version: Option<bool>, pub device_channel: netcetera_types::NetceteraDeviceChannel, /// Identifies the category of the message for a specific use case. The accepted values are: /// /// - 01 -> PA /// - 02 -> NPA /// - 80 - 99 -> PS Specific Values (80 -> MasterCard Identity Check Insights; /// 85 -> MasterCard Identity Check, Production Validation PA; /// 86 -> MasterCard Identity Check, Production Validation NPA) pub message_category: netcetera_types::NetceteraMessageCategory, #[serde(rename = "threeDSCompInd")] pub three_ds_comp_ind: Option<netcetera_types::ThreeDSMethodCompletionIndicator>, /** * Contains the 3DS Server Transaction ID used during the previous execution of the 3DS method. Accepted value * length is 36 characters. Accepted value is a Canonical format as defined in IETF RFC 4122. May utilise any of the * specified versions if the output meets specified requirements. * * This field is required if the 3DS Requestor reuses previous 3DS Method execution with deviceChannel = 02 (BRW). * Available for supporting EMV 3DS 2.3.1 and later versions. */ #[serde(rename = "threeDSMethodId")] pub three_ds_method_id: Option<String>, #[serde(rename = "threeDSRequestor")] pub three_ds_requestor: Option<netcetera_types::ThreeDSRequestor>, #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, #[serde(rename = "threeDSRequestorURL")] pub three_ds_requestor_url: Option<String>, pub cardholder_account: netcetera_types::CardholderAccount, pub cardholder: Option<netcetera_types::Cardholder>, pub purchase: Option<netcetera_types::Purchase>, pub acquirer: Option<netcetera_types::AcquirerData>, pub merchant: Option<netcetera_types::MerchantData>, pub broad_info: Option<String>, pub device_render_options: Option<netcetera_types::DeviceRenderingOptionsSupported>, pub message_extension: Option<Vec<MessageExtensionAttribute>>, pub challenge_message_extension: Option<Vec<MessageExtensionAttribute>>, pub browser_information: Option<netcetera_types::Browser>, #[serde(rename = "threeRIInd")] pub three_ri_ind: Option<String>, pub sdk_information: Option<netcetera_types::Sdk>, pub device: Option<String>, pub multi_transaction: Option<String>, pub device_id: Option<String>, pub user_id: Option<String>, pub payee_origin: Option<url::Url>, } impl TryFrom<&NetceteraRouterData<&ConnectorAuthenticationRouterData>> for NetceteraAuthenticationRequest { type Error = error_stack::Report<ConnectorError>; fn try_from( item: &NetceteraRouterData<&ConnectorAuthenticationRouterData>, ) -> Result<Self, Self::Error> { let now = common_utils::date_time::now(); let request = item.router_data.request.clone(); let pre_authn_data = request.pre_authentication_data.clone(); let ip_address = request .browser_details .as_ref() .and_then(|browser| browser.ip_address); let three_ds_requestor = netcetera_types::ThreeDSRequestor::new( ip_address, item.router_data.psd2_sca_exemption_type, item.router_data.request.force_3ds_challenge, item.router_data .request .pre_authentication_data .message_version .clone(), ); let card = get_card_details(request.payment_method_data, "netcetera")?; let is_cobadged_card = card .card_number .clone() .is_cobadged_card() .change_context(ConnectorError::RequestEncodingFailed) .attach_printable("error while checking is_cobadged_card")?; let cardholder_account = netcetera_types::CardholderAccount { acct_type: None, card_expiry_date: Some(card.get_expiry_date_as_yymm()?), acct_info: None, acct_number: card.card_number, scheme_id: card .card_network .clone() .and_then(|card_network| { is_cobadged_card.then_some(netcetera_types::SchemeId::try_from(card_network)) }) .transpose()?, acct_id: None, pay_token_ind: None, pay_token_info: None, card_security_code: Some(card.card_cvc), }; let currency = request .currency .get_required_value("currency") .change_context(ConnectorError::MissingRequiredField { field_name: "currency", })?; let purchase = netcetera_types::Purchase { purchase_instal_data: None, merchant_risk_indicator: None, purchase_amount: request.amount, purchase_currency: currency.iso_4217().to_string(), purchase_exponent: currency.number_of_digits_after_decimal_point(), purchase_date: Some( common_utils::date_time::format_date( now, common_utils::date_time::DateFormat::YYYYMMDDHHmmss, ) .change_context( ConnectorError::RequestEncodingFailedWithReason( "Failed to format Date".to_string(), ), )?, ), recurring_expiry: None, recurring_frequency: None, // 01 -> Goods and Services, hardcoding this as we serve this usecase only for now trans_type: Some("01".to_string()), recurring_amount: None, recurring_currency: None, recurring_exponent: None, recurring_date: None, amount_ind: None, frequency_ind: None, }; let acquirer_details = netcetera_types::AcquirerData { acquirer_bin: request.pre_authentication_data.acquirer_bin, acquirer_merchant_id: request.pre_authentication_data.acquirer_merchant_id, acquirer_country_code: request.pre_authentication_data.acquirer_country_code, }; let connector_meta_data: NetceteraMetaData = item .router_data .connector_meta_data .clone() .parse_value("NetceteraMetaData") .change_context(ConnectorError::RequestEncodingFailed)?; let merchant_data = netcetera_types::MerchantData { merchant_configuration_id: connector_meta_data.merchant_configuration_id, mcc: connector_meta_data.mcc, merchant_country_code: connector_meta_data.merchant_country_code, merchant_name: connector_meta_data.merchant_name, notification_url: request.return_url.clone(), three_ds_requestor_id: connector_meta_data.three_ds_requestor_id, three_ds_requestor_name: connector_meta_data.three_ds_requestor_name, white_list_status: None, trust_list_status: None, seller_info: None, results_response_notification_url: Some(request.webhook_url), }; let browser_information = match request.device_channel { api_models::payments::DeviceChannel::Browser => { request.browser_details.map(netcetera_types::Browser::from) } api_models::payments::DeviceChannel::App => None, }; let sdk_information = match request.device_channel { api_models::payments::DeviceChannel::App => { request.sdk_information.map(netcetera_types::Sdk::from) } api_models::payments::DeviceChannel::Browser => None, }; let device_render_options = match request.device_channel { api_models::payments::DeviceChannel::App => { Some(netcetera_types::DeviceRenderingOptionsSupported { // hard-coded until core provides these values. sdk_interface: netcetera_types::SdkInterface::Both, sdk_ui_type: vec![ netcetera_types::SdkUiType::Text, netcetera_types::SdkUiType::SingleSelect, netcetera_types::SdkUiType::MultiSelect, netcetera_types::SdkUiType::Oob, netcetera_types::SdkUiType::HtmlOther, ], }) } api_models::payments::DeviceChannel::Browser => None, }; Ok(Self { preferred_protocol_version: Some(pre_authn_data.message_version), // For Device channel App, we should enforce the preferred protocol version enforce_preferred_protocol_version: Some(matches!( request.device_channel, api_models::payments::DeviceChannel::App )), device_channel: netcetera_types::NetceteraDeviceChannel::from(request.device_channel), message_category: netcetera_types::NetceteraMessageCategory::from( request.message_category, ), three_ds_comp_ind: Some(netcetera_types::ThreeDSMethodCompletionIndicator::from( request.threeds_method_comp_ind, )), three_ds_method_id: None, three_ds_requestor: Some(three_ds_requestor), three_ds_server_trans_id: pre_authn_data.threeds_server_transaction_id, three_ds_requestor_url: Some(request.three_ds_requestor_url), cardholder_account, cardholder: Some(netcetera_types::Cardholder::try_from(( request.billing_address, request.shipping_address, ))?), purchase: Some(purchase), acquirer: Some(acquirer_details), merchant: Some(merchant_data), broad_info: None, device_render_options, message_extension: None, challenge_message_extension: None, browser_information, three_ri_ind: None, sdk_information, device: None, multi_transaction: None, device_id: None, user_id: None, payee_origin: None, }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum NetceteraAuthenticationResponse { Error(NetceteraAuthenticationFailureResponse), Success(NetceteraAuthenticationSuccessResponse), } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NetceteraAuthenticationSuccessResponse { #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, pub trans_status: common_enums::TransactionStatus, pub authentication_value: Option<Secret<String>>, pub eci: Option<String>, pub acs_challenge_mandated: Option<ACSChallengeMandatedIndicator>, pub authentication_request: Option<AuthenticationRequest>, pub authentication_response: AuthenticationResponse, #[serde(rename = "base64EncodedChallengeRequest")] pub encoded_challenge_request: Option<String>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NetceteraAuthenticationFailureResponse { pub error_details: NetceteraErrorDetails, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthenticationRequest { #[serde(rename = "threeDSRequestorChallengeInd")] pub three_ds_requestor_challenge_ind: Option<ThreedsRequestorChallengeInd>, } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum ThreedsRequestorChallengeInd { Single(String), Multiple(Vec<String>), } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthenticationResponse { #[serde(rename = "acsURL")] pub acs_url: Option<url::Url>, pub acs_reference_number: Option<String>, #[serde(rename = "acsTransID")] pub acs_trans_id: Option<String>, #[serde(rename = "dsTransID")] pub ds_trans_id: Option<String>, pub acs_signed_content: Option<String>, pub trans_status_reason: Option<String>, pub message_extension: Option<serde_json::Value>, } #[derive(Debug, Deserialize, Serialize, Clone)] pub enum ACSChallengeMandatedIndicator { /// Challenge is mandated Y, /// Challenge is not mandated N, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ResultsResponseData { /// Universally unique transaction identifier assigned by the 3DS Server to identify a single transaction. /// It has the same value as the authentication request and conforms to the format defined in IETF RFC 4122. #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, /// Indicates the status of a transaction in terms of its authentication. /// /// Valid values: /// - `Y`: Authentication / Account verification successful. /// - `N`: Not authenticated / Account not verified; Transaction denied. /// - `U`: Authentication / Account verification could not be performed; technical or other problem. /// - `C`: A challenge is required to complete the authentication. /// - `R`: Authentication / Account verification Rejected. Issuer is rejecting authentication/verification /// and request that authorization not be attempted. /// - `A`: Attempts processing performed; Not authenticated / verified, but a proof of attempt /// authentication / verification is provided. /// - `D`: A challenge is required to complete the authentication. Decoupled Authentication confirmed. /// - `I`: Informational Only; 3DS Requestor challenge preference acknowledged. pub trans_status: Option<common_enums::TransactionStatus>, /// Payment System-specific value provided as part of the ACS registration for each supported DS. /// Authentication Value may be used to provide proof of authentication. pub authentication_value: Option<Secret<String>>, /// Payment System-specific value provided by the ACS to indicate the results of the attempt to authenticate /// the Cardholder. pub eci: Option<String>, /// The received Results Request from the Directory Server. pub results_request: Option<serde_json::Value>, /// The sent Results Response to the Directory Server. pub results_response: Option<serde_json::Value>, /// Optional object containing error details if any errors occurred during the process. pub error_details: Option<NetceteraErrorDetails>, }
crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs
hyperswitch_connectors::src::connectors::netcetera::transformers
6,667
true
// File: crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs // Module: hyperswitch_connectors::src::connectors::netcetera::netcetera_types use std::collections::HashMap; use common_utils::{pii::Email, types::SemanticVersion}; use hyperswitch_domain_models::router_request_types::{ authentication::MessageCategory, BrowserInformation, }; use hyperswitch_interfaces::errors::ConnectorError; use masking::ExposeInterface; use serde::{Deserialize, Serialize}; use unidecode::unidecode; use crate::utils::{AddressDetailsData as _, PhoneDetailsData as _}; #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(untagged)] pub enum SingleOrListElement<T> { Single(T), List(Vec<T>), } impl<T> SingleOrListElement<T> { fn get_version_checked(message_version: SemanticVersion, value: T) -> Self { if message_version.get_major() >= 2 && message_version.get_minor() >= 3 { Self::List(vec![value]) } else { Self::Single(value) } } } impl<T> SingleOrListElement<T> { pub fn new_single(value: T) -> Self { Self::Single(value) } pub fn new_list(value: Vec<T>) -> Self { Self::List(value) } } #[derive(Debug, Deserialize, Serialize, Clone)] pub enum NetceteraDeviceChannel { #[serde(rename = "01")] AppBased, #[serde(rename = "02")] Browser, #[serde(rename = "03")] ThreeDsRequestorInitiated, } impl From<api_models::payments::DeviceChannel> for NetceteraDeviceChannel { fn from(value: api_models::payments::DeviceChannel) -> Self { match value { api_models::payments::DeviceChannel::App => Self::AppBased, api_models::payments::DeviceChannel::Browser => Self::Browser, } } } #[derive(Debug, Deserialize, Serialize, Clone)] pub enum NetceteraMessageCategory { #[serde(rename = "01")] PaymentAuthentication, #[serde(rename = "02")] NonPaymentAuthentication, } impl From<MessageCategory> for NetceteraMessageCategory { fn from(value: MessageCategory) -> Self { match value { MessageCategory::NonPayment => Self::NonPaymentAuthentication, MessageCategory::Payment => Self::PaymentAuthentication, } } } #[derive(Debug, Deserialize, Serialize, Clone)] pub enum ThreeDSMethodCompletionIndicator { /// Successfully completed Y, /// Did not successfully complete N, /// Unavailable - 3DS Method URL was not present in the PRes message data U, } impl From<api_models::payments::ThreeDsCompletionIndicator> for ThreeDSMethodCompletionIndicator { fn from(value: api_models::payments::ThreeDsCompletionIndicator) -> Self { match value { api_models::payments::ThreeDsCompletionIndicator::Success => Self::Y, api_models::payments::ThreeDsCompletionIndicator::Failure => Self::N, api_models::payments::ThreeDsCompletionIndicator::NotAvailable => Self::U, } } } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct ThreeDSRequestor { #[serde(rename = "threeDSRequestorAuthenticationInd")] pub three_ds_requestor_authentication_ind: ThreeDSRequestorAuthenticationIndicator, /// Format of this field was changed with EMV 3DS 2.3.1 version: /// In versions prior to 2.3.1, this field is a single object. /// Starting from EMVCo version 2.3.1, this field is now an array of objects. Accepted value length is 1-3 elements. /// /// This field is optional, but recommended to include. #[serde(rename = "threeDSRequestorAuthenticationInfo")] pub three_ds_requestor_authentication_info: Option<SingleOrListElement<ThreeDSRequestorAuthenticationInformation>>, #[serde(rename = "threeDSRequestorChallengeInd")] pub three_ds_requestor_challenge_ind: Option<SingleOrListElement<ThreeDSRequestorChallengeIndicator>>, #[serde(rename = "threeDSRequestorPriorAuthenticationInfo")] pub three_ds_requestor_prior_authentication_info: Option<SingleOrListElement<ThreeDSRequestorPriorTransactionAuthenticationInformation>>, #[serde(rename = "threeDSRequestorDecReqInd")] pub three_ds_requestor_dec_req_ind: Option<ThreeDSRequestorDecoupledRequestIndicator>, /// Indicates the maximum amount of time that the 3DS Requestor will wait for an ACS to provide the results /// of a Decoupled Authentication transaction (in minutes). Valid values are between 1 and 10080. /// /// The field is optional and if value is not present, the expected action is for the ACS to interpret it as /// 10080 minutes (7 days). /// Available for supporting EMV 3DS 2.2.0 and later versions. /// /// Starting from EMV 3DS 2.3.1: /// This field is required if threeDSRequestorDecReqInd = Y, F or B. #[serde(rename = "threeDSRequestorDecMaxTime")] pub three_ds_requestor_dec_max_time: Option<u32>, /// External IP address (i.e., the device public IP address) used by the 3DS Requestor App when it connects to the /// 3DS Requestor environment. The value length is maximum 45 characters. Accepted values are: /// /// - IPv4 address is represented in the dotted decimal f. Refer to RFC 791. /// - IPv6 address. Refer to RFC 4291. /// /// This field is required when deviceChannel = 01 (APP) and unless market or regional mandate restricts sending /// this information. /// Available for supporting EMV 3DS 2.3.1 and later versions. pub app_ip: Option<std::net::IpAddr>, /// Indicate if the 3DS Requestor supports the SPC authentication. /// /// The accepted values are: /// /// - Y -> Supported /// /// This field is required if deviceChannel = 02 (BRW) and it is supported by the 3DS Requestor. /// Available for supporting EMV 3DS 2.3.1 and later versions. #[serde(rename = "threeDSRequestorSpcSupport")] pub three_ds_requestor_spc_support: Option<String>, /// Reason that the SPC authentication was not completed. /// Accepted value length is 2 characters. /// /// The accepted values are: /// /// - 01 -> SPC did not run or did not successfully complete /// - 02 -> Cardholder cancels the SPC authentication /// /// This field is required if deviceChannel = 02 (BRW) and the 3DS Requestor attempts to invoke SPC API and there is an /// error. /// Available for supporting EMV 3DS 2.3.1 and later versions. pub spc_incomp_ind: Option<String>, } /// Indicates the type of Authentication request. /// /// This data element provides additional information to the ACS to determine the best approach for handling an authentication request. /// /// This value is used for App-based and Browser flows. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ThreeDSRequestorAuthenticationIndicator { #[serde(rename = "01")] Payment, #[serde(rename = "02")] Recurring, #[serde(rename = "03")] Installment, #[serde(rename = "04")] AddCard, #[serde(rename = "05")] MaintainCard, #[serde(rename = "06")] CardholderVerification, #[serde(rename = "07")] BillingAgreement, } impl ThreeDSRequestor { pub fn new( app_ip: Option<std::net::IpAddr>, psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, force_3ds_challenge: bool, message_version: SemanticVersion, ) -> Self { // if sca exemption is provided, we need to set the challenge indicator to NoChallengeRequestedTransactionalRiskAnalysis let three_ds_requestor_challenge_ind = if force_3ds_challenge { Some(SingleOrListElement::get_version_checked( message_version, ThreeDSRequestorChallengeIndicator::ChallengeRequestedMandate, )) } else if let Some(common_enums::ScaExemptionType::TransactionRiskAnalysis) = psd2_sca_exemption_type { Some(SingleOrListElement::get_version_checked( message_version, ThreeDSRequestorChallengeIndicator::NoChallengeRequestedTransactionalRiskAnalysis, )) } else { None }; Self { three_ds_requestor_authentication_ind: ThreeDSRequestorAuthenticationIndicator::Payment, three_ds_requestor_authentication_info: None, three_ds_requestor_challenge_ind, three_ds_requestor_prior_authentication_info: None, three_ds_requestor_dec_req_ind: None, three_ds_requestor_dec_max_time: None, app_ip, three_ds_requestor_spc_support: None, spc_incomp_ind: None, } } } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct ThreeDSRequestorAuthenticationInformation { /// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Accepted values are: /// - 01 -> No 3DS Requestor authentication occurred (i.e. cardholder "logged in" as guest) /// - 02 -> Login to the cardholder account at the 3DS Requestor system using 3DS Requestor's own credentials /// - 03 -> Login to the cardholder account at the 3DS Requestor system using federated ID /// - 04 -> Login to the cardholder account at the 3DS Requestor system using issuer credentials /// - 05 -> Login to the cardholder account at the 3DS Requestor system using third-party authentication /// - 06 -> Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. /// /// The next values are accepted as well if 3DS Server initiates authentication with EMV 3DS 2.2.0 version or greater (required protocol version can be set in ThreeDSServerAuthenticationRequest#preferredProtocolVersion field): /// - 07 -> Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator (FIDO assurance data signed). /// - 08 -> SRC Assurance Data. /// - Additionally, 80-99 can be used for PS-specific values, regardless of protocol version. #[serde(rename = "threeDSReqAuthMethod")] pub three_ds_req_auth_method: ThreeDSReqAuthMethod, /// Date and time converted into UTC of the cardholder authentication. Field is limited to 12 characters and accepted format is YYYYMMDDHHMM #[serde(rename = "threeDSReqAuthTimestamp")] pub three_ds_req_auth_timestamp: String, /// Data that documents and supports a specific authentication process. In the current version of the specification, this data element is not defined in detail, however the intention is that for each 3DS Requestor Authentication Method, this field carry data that the ACS can use to verify the authentication process. /// For example, if the 3DS Requestor Authentication Method is: /// /// - 03 -> then this element can carry information about the provider of the federated ID and related information /// - 06 -> then this element can carry the FIDO attestation data (incl. the signature) /// - 07 -> then this element can carry FIDO Attestation data with the FIDO assurance data signed. /// - 08 -> then this element can carry the SRC assurance data. #[serde(rename = "threeDSReqAuthData")] pub three_ds_req_auth_data: Option<String>, } /// Indicates whether a challenge is requested for this transaction. For example: For 01-PA, a 3DS Requestor may have /// concerns about the transaction, and request a challenge. For 02-NPA, a challenge may be necessary when adding a new /// card to a wallet. /// /// This field is optional. The accepted values are: /// /// - 01 -> No preference /// - 02 -> No challenge requested /// - 03 -> Challenge requested: 3DS Requestor Preference /// - 04 -> Challenge requested: Mandate. /// The next values are accepted as well if 3DS Server initiates authentication with EMV 3DS 2.2.0 version /// or greater (required protocol version can be set in /// ThreeDSServerAuthenticationRequest#preferredProtocolVersion field): /// /// - 05 -> No challenge requested (transactional risk analysis is already performed) /// - 06 -> No challenge requested (Data share only) /// - 07 -> No challenge requested (strong consumer authentication is already performed) /// - 08 -> No challenge requested (utilise whitelist exemption if no challenge required) /// - 09 -> Challenge requested (whitelist prompt requested if challenge required). /// - Additionally, 80-99 can be used for PS-specific values, regardless of protocol version. /// /// If the element is not provided, the expected action is that the ACS would interpret as 01 -> No preference. /// /// Format of this field was changed with EMV 3DS 2.3.1 version: /// In versions prior to 2.3.1, this field is a String. /// Starting from EMVCo version 2.3.1, this field is now an array of objects. Accepted value length is 1-2 elements. /// When providing two preferences, the 3DS Requestor ensures that they are in preference order and are not /// conflicting. For example, 02 = No challenge requested and 04 = Challenge requested (Mandate). #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ThreeDSRequestorChallengeIndicator { #[serde(rename = "01")] NoPreference, #[serde(rename = "02")] NoChallengeRequested, #[serde(rename = "03")] ChallengeRequested3DSRequestorPreference, #[serde(rename = "04")] ChallengeRequestedMandate, #[serde(rename = "05")] NoChallengeRequestedTransactionalRiskAnalysis, #[serde(rename = "06")] NoChallengeRequestedDataShareOnly, #[serde(rename = "07")] NoChallengeRequestedStrongConsumerAuthentication, #[serde(rename = "08")] NoChallengeRequestedWhitelistExemption, #[serde(rename = "09")] ChallengeRequestedWhitelistPrompt, } /// This field contains information about how the 3DS Requestor authenticated the cardholder as part of a previous 3DS transaction. /// Format of this field was changed with EMV 3DS 2.3.1 version: /// In versions prior to 2.3.1, this field is a single object. /// Starting from EMVCo version 2.3.1, this field is now an array of objects. Accepted value length is 1-3 elements. /// /// This field is optional, but recommended to include for versions prior to 2.3.1. From 2.3.1, /// it is required for 3RI in the case of Decoupled Authentication Fallback or for SPC. #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct ThreeDSRequestorPriorTransactionAuthenticationInformation { /// This data element provides additional information to the ACS to determine the best /// approach for handling a request. The field is limited to 36 characters containing /// ACS Transaction ID for a prior authenticated transaction (for example, the first /// recurring transaction that was authenticated with the cardholder). pub three_ds_req_prior_ref: String, /// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor. /// Accepted values for this field are: /// - 01 -> Frictionless authentication occurred by ACS /// - 02 -> Cardholder challenge occurred by ACS /// - 03 -> AVS verified /// - 04 -> Other issuer methods /// - 80-99 -> PS-specific value (dependent on the payment scheme type). pub three_ds_req_prior_auth_method: String, /// Date and time converted into UTC of the prior authentication. Accepted date /// format is YYYYMMDDHHMM. pub three_ds_req_prior_auth_timestamp: String, /// Data that documents and supports a specific authentication process. In the current /// version of the specification this data element is not defined in detail, however /// the intention is that for each 3DS Requestor Authentication Method, this field carry /// data that the ACS can use to verify the authentication process. In future versions /// of the application, these details are expected to be included. Field is limited to /// maximum 2048 characters. pub three_ds_req_prior_auth_data: String, } /// Enum indicating whether the 3DS Requestor requests the ACS to utilize Decoupled Authentication. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ThreeDSRequestorDecoupledRequestIndicator { /// Decoupled Authentication is supported and preferred if challenge is necessary. Y, /// Do not use Decoupled Authentication. N, /// Decoupled Authentication is supported and is to be used only as a fallback challenge method /// if a challenge is necessary (Transaction Status = D in RReq). F, /// Decoupled Authentication is supported and can be used as a primary or fallback challenge method /// if a challenge is necessary (Transaction Status = D in either ARes or RReq). B, } #[derive(Debug, Serialize, Deserialize, Clone)] pub enum SchemeId { Visa, Mastercard, #[serde(rename = "JCB")] Jcb, #[serde(rename = "American Express")] AmericanExpress, Diners, // For Cartes Bancaires and UnionPay, it is recommended to send the scheme ID #[serde(rename = "CB")] CartesBancaires, UnionPay, } impl TryFrom<common_enums::CardNetwork> for SchemeId { type Error = error_stack::Report<ConnectorError>; fn try_from(network: common_enums::CardNetwork) -> Result<Self, Self::Error> { match network { common_enums::CardNetwork::Visa => Ok(Self::Visa), common_enums::CardNetwork::Mastercard => Ok(Self::Mastercard), common_enums::CardNetwork::JCB => Ok(Self::Jcb), common_enums::CardNetwork::AmericanExpress => Ok(Self::AmericanExpress), common_enums::CardNetwork::DinersClub => Ok(Self::Diners), common_enums::CardNetwork::CartesBancaires => Ok(Self::CartesBancaires), common_enums::CardNetwork::UnionPay => Ok(Self::UnionPay), _ => Err(ConnectorError::RequestEncodingFailedWithReason( "Invalid card network".to_string(), ))?, } } } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct CardholderAccount { /// Indicates the type of account. /// This is required if 3DS Requestor is asking Cardholder which Account Type they are using before making /// the purchase. This field is required in some markets. Otherwise, it is optional. pub acct_type: Option<AccountType>, /// Expiry date of the PAN or token supplied to the 3DS Requestor by the Cardholder. /// The field has 4 characters in a format YYMM. /// /// The requirements of the presence of this field are DS specific. pub card_expiry_date: Option<masking::Secret<String>>, /// This field contains additional information about the Cardholder’s account provided by the 3DS Requestor. /// /// The field is optional but recommended to include. /// /// Starting from EMV 3DS 2.3.1, added new field: /// - `ch_acc_req_id` -> The 3DS Requestor assigned account identifier of the transacting Cardholder. /// This identifier is a unique representation of the account identifier for the 3DS Requestor and /// is provided as a String. pub acct_info: Option<CardHolderAccountInformation>, /// Account number that will be used in the authorization request for payment transactions. /// May be represented by PAN or token. /// /// This field is required. pub acct_number: cards::CardNumber, /// ID for the scheme to which the Cardholder's acctNumber belongs to. /// It will be used to identify the Scheme from the 3DS Server configuration. /// /// This field is optional, but recommended to include. /// It should be present when it is not one of the schemes for which scheme resolving regular expressions /// are provided in the 3DS Server Configuration Properties. Additionally, /// if the schemeId is present in the request and there are card ranges found by multiple schemes, the schemeId will be /// used for proper resolving of the versioning data. pub scheme_id: Option<SchemeId>, /// Additional information about the account optionally provided by the 3DS Requestor. /// /// This field is limited to 64 characters and it is optional to use. #[serde(rename = "acctID")] pub acct_id: Option<String>, /// Indicates if the transaction was de-tokenized prior to being received by the ACS. /// /// The boolean value of true is the only valid response for this field when it is present. /// /// The field is required only if there is a de-tokenization of an Account Number. pub pay_token_ind: Option<bool>, /// Information about the de-tokenised Payment Token. /// Note: Data will be formatted into a JSON object prior to being placed into the EMV Payment Token field of the message. /// /// This field is optional. pub pay_token_info: Option<String>, /// Three or four-digit security code printed on the card. /// The value is numeric and limited to 3-4 characters. /// /// This field is required depending on the rules provided by the Directory Server. /// Available for supporting EMV 3DS 2.3.1 and later versions. pub card_security_code: Option<masking::Secret<String>>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum AccountType { #[serde(rename = "01")] NotApplicable, #[serde(rename = "02")] Credit, #[serde(rename = "03")] Debit, #[serde(rename = "80")] Jcb, /// 81-99 -> PS-specific value (dependent on the payment scheme type). #[serde(untagged)] PsSpecificValue(String), } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct CardHolderAccountInformation { /// Length of time that the cardholder has had the account with the 3DS Requestor. /// /// Accepted values are: /// - `01` -> No account /// - `02` -> Created during this transaction /// - `03` -> Less than 30 days /// - `04` -> Between 30 and 60 days /// - `05` -> More than 60 days pub ch_acc_age_ind: Option<String>, /// Date converted into UTC that the cardholder opened the account with the 3DS Requestor. /// /// Date format = YYYYMMDD. pub ch_acc_date: Option<String>, /// Length of time since the cardholder’s account information with the 3DS Requestor was /// last changed. /// /// Includes Billing or Shipping address, new payment account, or new user(s) added. /// /// Accepted values are: /// - `01` -> Changed during this transaction /// - `02` -> Less than 30 days /// - `03` -> 30 - 60 days /// - `04` -> More than 60 days pub ch_acc_change_ind: Option<String>, /// Date converted into UTC that the cardholder’s account with the 3DS Requestor was last changed. /// /// Including Billing or Shipping address, new payment account, or new user(s) added. /// /// Date format = YYYYMMDD. pub ch_acc_change: Option<String>, /// Length of time since the cardholder’s account with the 3DS Requestor had a password change /// or account reset. /// /// The accepted values are: /// - `01` -> No change /// - `02` -> Changed during this transaction /// - `03` -> Less than 30 days /// - `04` -> 30 - 60 days /// - `05` -> More than 60 days pub ch_acc_pw_change_ind: Option<String>, /// Date converted into UTC that cardholder’s account with the 3DS Requestor had a password /// change or account reset. /// /// Date format must be YYYYMMDD. pub ch_acc_pw_change: Option<String>, /// Indicates when the shipping address used for this transaction was first used with the /// 3DS Requestor. /// /// Accepted values are: /// - `01` -> This transaction /// - `02` -> Less than 30 days /// - `03` -> 30 - 60 days /// - `04` -> More than 60 days pub ship_address_usage_ind: Option<String>, /// Date converted into UTC when the shipping address used for this transaction was first /// used with the 3DS Requestor. /// /// Date format must be YYYYMMDD. pub ship_address_usage: Option<String>, /// Number of transactions (successful and abandoned) for this cardholder account with the /// 3DS Requestor across all payment accounts in the previous 24 hours. pub txn_activity_day: Option<u32>, /// Number of transactions (successful and abandoned) for this cardholder account with the /// 3DS Requestor across all payment accounts in the previous year. pub txn_activity_year: Option<u32>, /// Number of Add Card attempts in the last 24 hours. pub provision_attempts_day: Option<u32>, /// Number of purchases with this cardholder account during the previous six months. pub nb_purchase_account: Option<u32>, /// Indicates whether the 3DS Requestor has experienced suspicious activity /// (including previous fraud) on the cardholder account. /// /// Accepted values are: /// - `01` -> No suspicious activity has been observed /// - `02` -> Suspicious activity has been observed pub suspicious_acc_activity: Option<String>, /// Indicates if the Cardholder Name on the account is identical to the shipping Name used /// for this transaction. /// /// Accepted values are: /// - `01` -> Account Name identical to shipping Name /// - `02` -> Account Name different than shipping Name pub ship_name_indicator: Option<String>, /// Indicates the length of time that the payment account was enrolled in the cardholder’s /// account with the 3DS Requester. /// /// Accepted values are: /// - `01` -> No account (guest check-out) /// - `02` -> During this transaction /// - `03` -> Less than 30 days /// - `04` -> 30 - 60 days /// - `05` -> More than 60 days pub payment_acc_ind: Option<String>, /// Date converted into UTC that the payment account was enrolled in the cardholder’s account with /// the 3DS Requestor. /// /// Date format must be YYYYMMDD. pub payment_acc_age: Option<String>, /// The 3DS Requestor assigned account identifier of the transacting Cardholder. /// /// This identifier is a unique representation of the account identifier for the 3DS Requestor and /// is provided as a String. Accepted value length is maximum 64 characters. /// /// Added starting from EMV 3DS 2.3.1. pub ch_acc_req_id: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] #[serde_with::skip_serializing_none] pub struct Cardholder { /// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same. /// /// Accepted values: /// - `Y` -> Shipping Address matches Billing Address /// - `N` -> Shipping Address does not match Billing Address /// /// If the field is not set and the shipping and billing addresses are the same, the 3DS Server will set the value to /// `Y`. Otherwise, the value will not be changed. /// /// This field is optional. addr_match: Option<String>, /// The city of the Cardholder billing address associated with the card used for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless market or regional mandate restricts sending this information. bill_addr_city: Option<String>, /// The country of the Cardholder billing address associated with the card used for this purchase. /// /// This field is limited to 3 characters. This value shall be the ISO 3166-1 numeric country code, except values /// from range 901 - 999 which are reserved by ISO. /// /// The field is required if Cardholder Billing Address State is present and unless market or regional mandate /// restricts sending this information. bill_addr_country: Option<String>, /// First line of the street address or equivalent local portion of the Cardholder billing address associated with /// the card use for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless market or regional mandate restricts sending this information. bill_addr_line1: Option<masking::Secret<String>>, /// Second line of the street address or equivalent local portion of the Cardholder billing address associated with /// the card use for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless market or regional mandate restricts sending this information. bill_addr_line2: Option<masking::Secret<String>>, /// Third line of the street address or equivalent local portion of the Cardholder billing address associated with /// the card use for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless market or regional mandate restricts sending this information. bill_addr_line3: Option<masking::Secret<String>>, /// ZIP or other postal code of the Cardholder billing address associated with the card used for this purchase. /// /// This field is limited to a maximum of 16 characters. /// /// This field is required unless market or regional mandate restricts sending this information. bill_addr_post_code: Option<masking::Secret<String>>, /// The state or province of the Cardholder billing address associated with the card used for this purchase. /// /// This field is limited to 3 characters. The value should be the country subdivision code defined in ISO 3166-2. /// /// This field is required unless State is not applicable for this country and unless market or regional mandate /// restricts sending this information. bill_addr_state: Option<masking::Secret<String>>, /// The email address associated with the account that is either entered by the Cardholder, or is on file with /// the 3DS Requestor. /// /// This field is limited to a maximum of 256 characters and shall meet requirements of Section 3.4 of /// IETF RFC 5322. /// /// This field is required unless market or regional mandate restricts sending this information. email: Option<Email>, /// The home phone provided by the Cardholder. /// /// Refer to ITU-E.164 for additional information on format and length. /// /// This field is required if available, unless market or regional mandate restricts sending this information. home_phone: Option<PhoneNumber>, /// The mobile phone provided by the Cardholder. /// /// Refer to ITU-E.164 for additional information on format and length. /// /// This field is required if available, unless market or regional mandate restricts sending this information. mobile_phone: Option<PhoneNumber>, /// The work phone provided by the Cardholder. /// /// Refer to ITU-E.164 for additional information on format and length. /// /// This field is required if available, unless market or regional mandate restricts sending this information. work_phone: Option<PhoneNumber>, /// Name of the Cardholder. /// /// This field is limited to 2-45 characters. /// /// This field is required unless market or regional mandate restricts sending this information. /// /// Starting from EMV 3DS 2.3.1: /// This field is limited to 1-45 characters. cardholder_name: Option<masking::Secret<String>>, /// City portion of the shipping address requested by the Cardholder. /// /// This field is required unless shipping information is the same as billing information, or market or regional /// mandate restricts sending this information. ship_addr_city: Option<String>, /// Country of the shipping address requested by the Cardholder. /// /// This field is limited to 3 characters. This value shall be the ISO 3166-1 numeric country code, except values /// from range 901 - 999 which are reserved by ISO. /// /// This field is required if Cardholder Shipping Address State is present and if shipping information are not the same /// as billing information. This field can be omitted if market or regional mandate restricts sending this information. ship_addr_country: Option<String>, /// First line of the street address or equivalent local portion of the shipping address associated with /// the card use for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless shipping information is the same as billing information, or market or regional /// mandate restricts sending this information. ship_addr_line1: Option<masking::Secret<String>>, /// Second line of the street address or equivalent local portion of the shipping address associated with /// the card use for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless shipping information is the same as billing information, or market or regional /// mandate restricts sending this information. ship_addr_line2: Option<masking::Secret<String>>, /// Third line of the street address or equivalent local portion of the shipping address associated with /// the card use for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless shipping information is the same as billing information, or market or regional /// mandate restricts sending this information. ship_addr_line3: Option<masking::Secret<String>>, /// ZIP or other postal code of the shipping address associated with the card used for this purchase. /// /// This field is limited to a maximum of 16 characters. /// /// This field is required unless shipping information is the same as billing information, or market or regional /// mandate restricts sending this information. ship_addr_post_code: Option<masking::Secret<String>>, /// The state or province of the shipping address associated with the card used for this purchase. /// /// This field is limited to 3 characters. The value should be the country subdivision code defined in ISO 3166-2. /// /// This field is required unless shipping information is the same as billing information, or State is not applicable /// for this country, or market or regional mandate restricts sending this information. ship_addr_state: Option<masking::Secret<String>>, /// Tax ID is the Cardholder's tax identification. /// /// The value is limited to 45 characters. /// /// This field is required depending on the rules provided by the Directory Server. /// Available for supporting EMV 3DS 2.3.1 and later versions. tax_id: Option<String>, } impl TryFrom<( hyperswitch_domain_models::address::Address, Option<hyperswitch_domain_models::address::Address>, )> for Cardholder { type Error = error_stack::Report<ConnectorError>; fn try_from( (billing_address, shipping_address): ( hyperswitch_domain_models::address::Address, Option<hyperswitch_domain_models::address::Address>, ), ) -> Result<Self, Self::Error> { Ok(Self { addr_match: None, bill_addr_city: billing_address .address .as_ref() .and_then(|add| add.city.clone()), bill_addr_country: billing_address.address.as_ref().and_then(|add| { add.country.map(|country| { common_enums::Country::from_alpha2(country) .to_numeric() .to_string() }) }), bill_addr_line1: billing_address .address .as_ref() .and_then(|add| add.line1.clone()), bill_addr_line2: billing_address .address .as_ref() .and_then(|add| add.line2.clone()), bill_addr_line3: billing_address .address .as_ref() .and_then(|add| add.line3.clone()), bill_addr_post_code: billing_address .address .as_ref() .and_then(|add| add.zip.clone()), bill_addr_state: billing_address .address .as_ref() .and_then(|add| add.to_state_code_as_optional().transpose()) .transpose()?, email: billing_address.email, home_phone: billing_address .phone .clone() .map(PhoneNumber::try_from) .transpose()?, mobile_phone: billing_address .phone .clone() .map(PhoneNumber::try_from) .transpose()?, work_phone: billing_address .phone .clone() .map(PhoneNumber::try_from) .transpose()?, cardholder_name: billing_address.address.and_then(|address| { address .get_optional_full_name() .map(|name| masking::Secret::new(unidecode(&name.expose()))) }), ship_addr_city: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.city.clone()), ship_addr_country: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| { add.country.map(|country| { common_enums::Country::from_alpha2(country) .to_numeric() .to_string() }) }), ship_addr_line1: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.line1.clone()), ship_addr_line2: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.line2.clone()), ship_addr_line3: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.line3.clone()), ship_addr_post_code: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.zip.clone()), ship_addr_state: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.to_state_code_as_optional().transpose()) .transpose()?, tax_id: None, }) } } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct PhoneNumber { /// Country Code of the phone, limited to 1-3 characters #[serde(rename = "cc")] country_code: Option<String>, subscriber: Option<masking::Secret<String>>, } impl TryFrom<hyperswitch_domain_models::address::PhoneDetails> for PhoneNumber { type Error = error_stack::Report<ConnectorError>; fn try_from( value: hyperswitch_domain_models::address::PhoneDetails, ) -> Result<Self, Self::Error> { Ok(Self { country_code: Some(value.extract_country_code()?), subscriber: value.number, }) } } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct Purchase { /// Indicates the maximum number of authorisations permitted for instalment payments. /// /// The field is limited to a maximum of 3 characters and value shall be greater than 1. /// /// The field is required if the Merchant and Cardholder have agreed to installment payments, i.e. if 3DS Requestor /// Authentication Indicator = 03. Omitted if not an installment payment authentication. /// /// Starting from EMV 3DS 2.3.1: /// Additionally this field is required for deviceChannel = 03 (3RI) if threeRIInd = 02. pub purchase_instal_data: Option<i32>, /// Merchant's assessment of the level of fraud risk for the specific authentication for both the cardholder and the /// authentication being conducted. /// /// The field is optional but strongly recommended to include. pub merchant_risk_indicator: Option<MerchantRiskIndicator>, /// Purchase amount in minor units of currency with all punctuation removed. When used in conjunction with the Purchase /// Currentcy Exponent field, proper punctuation can be calculated. Example: If the purchase amount is USD 123.45, /// element will contain the value 12345. The field is limited to maximum 48 characters. /// /// This field is required for 02 - NPA message category if 3DS Requestor Authentication Indicator = 02 or 03. /// /// Starting from EMV 3DS 2.3.1: /// Additionally this field is required for messageCategory = 02 (NPA) if threeRIInd = 01, 02, 06, 07, 08, 09, or 11. pub purchase_amount: Option<i64>, /// Currency in which purchase amount is expressed. The value is limited to 3 numeric characters and is represented by /// the ISO 4217 three-digit currency code, except 955-964 and 999. /// /// This field is required for requests where messageCategory = 01-PA and for 02-NPA if 3DS Requestor Authentication /// Indicator = 02 or 03. /// /// Starting from EMV 3DS 2.3.1: /// Additionally this field is required for messageCategory = 02 (NPA) if threeRIInd = 01, 02, 06, 07, 08, 09, or 11. pub purchase_currency: String, /// Minor units of currency as specified in the ISO 4217 currency exponent. The field is limited to 1 character and it /// is required for 01-PA and for 02-NPA if 3DS Requestor Authentication Indicator = 02 or 03. /// /// Example: for currency USD the exponent should be 2, and for Yen the exponent should be 0. /// /// Starting from EMV 3DS 2.3.1: /// Additionally this field is required for messageCategory = 02 (NPA) if threeRIInd = 01, 02, 06, 07, 08, 09, or 11. pub purchase_exponent: u8, /// Date and time of the purchase, converted into UTC. The field is limited to 14 characters, /// formatted as YYYYMMDDHHMMSS. /// /// This field is required for 01-PA and for 02-NPA, if 3DS Requestor Authentication Indicator = 02 or 03. /// /// Starting from EMV 3DS 2.3.1: /// Additionally this field is required for messageCategory = 02 (NPA) if threeRIInd = 01, 02, 06, 07, 08, 09, or 11. pub purchase_date: Option<String>, /// Date after which no further authorizations shall be performed. This field is limited to 8 characters, and the /// accepted format is YYYYMMDD. /// /// This field is required for 01-PA and for 02-NPA, if 3DS Requestor Authentication Indicator = 02 or 03. /// /// Starting from EMV 3DS 2.3.1: /// This field is required if recurringInd = 01. pub recurring_expiry: Option<String>, /// Indicates the minimum number of days between authorizations. The field is limited to maximum 4 characters. /// /// This field is required if 3DS Requestor Authentication Indicator = 02 or 03. /// /// Starting from EMV 3DS 2.3.1: /// This field is required if recurringInd = 01 pub recurring_frequency: Option<i32>, /// Identifies the type of transaction being authenticated. The values are derived from ISO 8583. Accepted values are: /// - 01 -> Goods / Service purchase /// - 03 -> Check Acceptance /// - 10 -> Account Funding /// - 11 -> Quasi-Cash Transaction /// - 28 -> Prepaid activation and Loan /// /// This field is required in some markets. Otherwise, the field is optional. /// /// This field is required if 3DS Requestor Authentication Indicator = 02 or 03. pub trans_type: Option<String>, /// Recurring amount after first/promotional payment in minor units of currency with all punctuation removed. /// Example: If the recurring amount is USD 123.45, element will contain the value 12345. The field is limited to /// maximum 48 characters. /// /// The field is required if threeDSRequestorAuthenticationInd = 02 or 03 OR threeRIInd = 01 or 02 AND /// purchaseAmount != recurringAmount AND recurringInd = 01. /// /// Available for supporting EMV 3DS 2.3.1 and later versions. pub recurring_amount: Option<i64>, /// Currency in which recurring amount is expressed. The value is limited to 3 numeric characters and is represented by /// the ISO 4217 three-digit currency code, except 955-964 and 999. /// /// This field is required if recurringAmount is present. /// /// Available for supporting EMV 3DS 2.3.1 and later versions. pub recurring_currency: Option<String>, /// Minor units of currency as specified in the ISO 4217 currency exponent. Example: USD = 2, Yen = 0. The value is /// limited to 1 numeric character. /// /// This field is required if recurringAmount is present. /// /// Available for supporting EMV 3DS 2.3.1 and later versions. pub recurring_exponent: Option<i32>, /// Effective date of new authorised amount following first/promotional payment in recurring transaction. The value /// is limited to 8 characters. Accepted format: YYYYMMDD. /// /// This field is required if recurringInd = 01. /// /// Available for supporting EMV 3DS 2.3.1 and later versions. pub recurring_date: Option<String>, /// Part of the indication whether the recurring or instalment payment has a fixed or variable amount. /// /// Accepted values are: /// - 01 -> Fixed Purchase Amount /// - 02 -> Variable Purchase Amount /// - 03–79 -> Reserved for EMVCo future use (values invalid until defined by EMVCo) /// - 80-99 -> PS-specific value (dependent on the payment scheme type) /// /// Available for supporting EMV 3DS 2.3.1 and later versions. pub amount_ind: Option<String>, /// Part of the indication whether the recurring or instalment payment has a fixed or variable frequency. /// /// Accepted values are: /// - 01 -> Fixed Frequency /// - 02 -> Variable Frequency /// - 03–79 -> Reserved for EMVCo future use (values invalid until defined by EMVCo) /// - 80-99 -> PS-specific value (dependent on the payment scheme type) /// /// Available for supporting EMV 3DS 2.3.1 and later versions. pub frequency_ind: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct MerchantRiskIndicator { /// Indicates the shipping method chosen for the transaction. /// /// Merchants must choose the Shipping Indicator code that most accurately describes the cardholder's specific transaction. /// If one or more items are included in the sale, use the Shipping Indicator code for the physical goods, or if all digital goods, /// use the code that describes the most expensive item. /// /// Accepted values: /// - Ship to cardholder's billing address (01) /// - Ship to another verified address on file with merchant (02) /// - Ship to address that is different than the cardholder's billing address (03) /// - Ship to Store / Pick-up at local store (Store address shall be populated in shipping address fields) (04) /// - Digital goods (includes online services, electronic gift cards and redemption codes) (05) /// - Travel and Event tickets, not shipped (06) /// - Other (for example, Gaming, digital services not shipped, e-media subscriptions, etc.) (07) /// - PS-specific value (dependent on the payment scheme type) (80-81) /// /// Starting from EMV 3DS 2.3.1: /// Changed values to shipIndicator -> Accepted values are: /// - 01 -> Ship to cardholder's billing address /// - 02 -> Ship to another verified address on file with merchant /// - 03 -> Ship to address that is different than the cardholder's billing address /// - 04 -> "Ship to Store" / Pick-up at local store (Store address shall be populated in shipping /// address fields) /// - 05 -> Digital goods (includes online services, electronic gift cards and redemption codes) /// - 06 -> Travel and Event tickets, not shipped /// - 07 -> Other (for example, Gaming, digital services not shipped, e-media subscriptions, etc.) /// - 08 -> Pick-up and go delivery /// - 09 -> Locker delivery (or other automated pick-up) ship_indicator: Option<String>, /// Indicates the merchandise delivery timeframe. /// /// Accepted values: /// - Electronic Delivery (01) /// - Same day shipping (02) /// - Overnight shipping (03) /// - Two-day or more shipping (04) delivery_timeframe: Option<String>, /// For electronic delivery, the email address to which the merchandise was delivered. delivery_email_address: Option<String>, /// Indicates whether the cardholder is reordering previously purchased merchandise. /// /// Accepted values: /// - First time ordered (01) /// - Reordered (02) reorder_items_ind: Option<String>, /// Indicates whether Cardholder is placing an order for merchandise with a future availability or release date. /// /// Accepted values: /// - Merchandise available (01) /// - Future availability (02) pre_order_purchase_ind: Option<String>, /// For a pre-ordered purchase, the expected date that the merchandise will be available. /// /// Date format: YYYYMMDD pre_order_date: Option<String>, /// For prepaid or gift card purchase, the purchase amount total of prepaid or gift card(s) in major units. gift_card_amount: Option<i32>, /// For prepaid or gift card purchase, the currency code of the card as defined in ISO 4217 except 955 - 964 and 999. gift_card_curr: Option<String>, // ISO 4217 currency code /// For prepaid or gift card purchase, total count of individual prepaid or gift cards/codes purchased. /// /// Field is limited to 2 characters. gift_card_count: Option<i32>, /// Starting from EMV 3DS 2.3.1.1: /// New field introduced: /// - transChar -> Indicates to the ACS specific transactions identified by the Merchant. /// - Size: Variable, 1-2 elements. JSON Data Type: Array of String. Accepted values: /// - 01 -> Cryptocurrency transaction /// - 02 -> NFT transaction trans_char: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct AcquirerData { /// Acquiring institution identification code as assigned by the DS receiving the AReq message. /// /// This field is limited to 11 characters. This field can be omitted if it there is a MerchantAcquirer already configured for 3DS Server, /// referenced by the acquirerMerchantId. /// /// This field is required if no MerchantAcquirer is present for the acquirer BIN in the 3DS Server configuration and /// for requests where messageCategory = 01 (PA). For requests where messageCategory=02 (NPA), the field is required /// only if scheme is Mastercard, for other schemes it is optional. #[serde(skip_serializing_if = "Option::is_none")] pub acquirer_bin: Option<String>, /// Acquirer-assigned Merchant identifier. /// /// This may be the same value that is used in authorization requests sent on behalf of the 3DS Requestor and is represented in ISO 8583 formatting requirements. /// The field is limited to maximum 35 characters. Individual Directory Servers may impose specific format and character requirements on /// the contents of this field. /// /// This field will be used to identify the Directory Server where the AReq will be sent and the acquirerBin from the 3DS Server configuration. /// If no MerchantAcquirer configuration is present in the 3DS Server, the DirectoryServer information will be resolved from the scheme to which the cardholder account belongs to. /// /// This field is required if merchantConfigurationId is not provided in the request and messageCategory = 01 (PA). /// For Mastercard, if merchantConfigurationId is not provided, the field must be present if messageCategory = 02 (NPA). #[serde(skip_serializing_if = "Option::is_none")] pub acquirer_merchant_id: Option<String>, /// Acquirer Country Code. /// /// This is the code of the country where the acquiring institution is located. The specified /// length of this field is 3 characters and will accept values according to the ISO 3166-1 numeric three-digit /// country code. /// /// The Directory Server may edit the value of this field provided by the 3DS Server. /// /// This field is required. #[serde(skip_serializing_if = "Option::is_none")] pub acquirer_country_code: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] #[serde_with::skip_serializing_none] pub struct MerchantData { /// ID of the merchant. This value will be used to find merchant information from the configuration. /// From the merchant configuration the 3DS Server can fill the other values (mcc, merchantCountryCode and merchantName), if provided. /// /// This field can be left out if merchant information are provided in the request. pub merchant_configuration_id: Option<String>, /// Merchant Category Code. This is the DS-specific code describing the Merchant's type of business, product or service. /// The field is limited to 4 characters. The value correlates to the Merchant Category Code as defined by each Payment System or DS. /// /// If not present in the request it will be filled from the merchant configuration referenced by the merchantConfigurationId. /// /// This field is required for messageCategory=01 (PA) and optional, but strongly recommended for 02 (NPA). #[serde(skip_serializing_if = "Option::is_none")] pub mcc: Option<String>, /// Country code for the merchant. This value correlates to the Merchant Country Code as defined by each Payment System or DS. /// The field is limited to 3 characters accepting ISO 3166-1 format, except 901-999. /// /// If not present in the request it will be filled from the merchant configuration referenced by the merchantConfigurationId. /// /// This field is required for messageCategory=01 (PA) and optional, but strongly recommended for 02 (NPA). #[serde(skip_serializing_if = "Option::is_none")] pub merchant_country_code: Option<String>, /// Merchant name assigned by the Acquirer or Payment System. This field is limited to maximum 40 characters, /// and it is the same name used in the authorisation message as defined in ISO 8583. /// /// If not present in the request it will be filled from the merchant configuration referenced by the merchantConfigurationId. /// /// This field is required for messageCategory=01 (PA) and optional, but strongly recommended for 02 (NPA). #[serde(skip_serializing_if = "Option::is_none")] pub merchant_name: Option<String>, /// Fully qualified URL of the merchant that receives the CRes message or Error Message. /// Incorrect formatting will result in a failure to deliver the notification of the final CRes message. /// This field is limited to 256 characters. /// /// This field should be present if the merchant will receive the final CRes message and the device channel is BROWSER. /// If not present in the request it will be filled from the notificationURL configured in the XML or database configuration. #[serde(rename = "notificationURL")] #[serde(skip_serializing_if = "Option::is_none")] pub notification_url: Option<String>, /// Each DS provides rules for the 3DS Requestor ID. The 3DS Requestor is responsible for providing the 3DS Requestor ID according to the DS rules. /// /// This value is mandatory, therefore it should be either configured for each Merchant Acquirer, or should be /// passed in the transaction payload as part of the Merchant data. #[serde(rename = "threeDSRequestorId")] #[serde(skip_serializing_if = "Option::is_none")] pub three_ds_requestor_id: Option<String>, /// Each DS provides rules for the 3DS Requestor Name. The 3DS Requestor is responsible for providing the 3DS Requestor Name according to the DS rules. /// /// This value is mandatory, therefore it should be either configured for each Merchant Acquirer, or should be /// passed in the transaction payload as part of the Merchant data. #[serde(rename = "threeDSRequestorName")] #[serde(skip_serializing_if = "Option::is_none")] pub three_ds_requestor_name: Option<String>, /// Set whitelisting status of the merchant. /// /// The field is optional and if value is not present, the whitelist remains unchanged. /// This field is only available for supporting EMV 3DS 2.2.0. pub white_list_status: Option<WhitelistStatus>, /// Set trustlisting status of the merchant. /// /// The field is optional and if value is not present, the trustlist remains unchanged. /// From EMV 3DS 2.3.1 this field replaces whiteListStatus. pub trust_list_status: Option<WhitelistStatus>, /// Additional transaction information for transactions where merchants submit transaction details on behalf of another entity. /// The accepted value length is 1-50 elements. /// /// This field is optional. pub seller_info: Option<Vec<SellerInfo>>, /// Fully qualified URL of the merchant that receives the RRes message or Error Message. /// Incorrect formatting will result in a failure to deliver the notification of the final RRes message. /// This field is limited to 256 characters. /// /// This field is not mandatory and could be present if the Results Response (in case of a challenge transaction) /// should be sent to a dynamic URL different from the one present in the configuration, only if dynamic provision /// of the Results Response notification URL is allowed per the license. /// /// If not present in the request it will be filled from the notificationURL configured in the XML or database /// configuration. #[serde(skip_serializing_if = "Option::is_none")] pub results_response_notification_url: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub enum WhitelistStatus { /// 3DS Requestor is whitelisted by cardholder Y, /// 3DS Requestor is not whitelisted by cardholder N, /// Not eligible as determined by issuer E, /// Pending confirmation by cardholder P, /// Cardholder rejected R, /// Whitelist status unknown, unavailable, or does not apply. U, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] #[serde_with::skip_serializing_none] pub struct SellerInfo { /// Name of the Seller. The value length is maximum 100 characters. This field is required. seller_name: String, /// Merchant-assigned Seller identifier. If this data element is present, this must match the Seller ID field /// in the Seller Information object. The value length is maximum 50 characters. This field is required if /// sellerId in multiTransaction object is present. seller_id: Option<String>, /// Business name of the Seller. The value length is maximum 100 characters. This field is optional. seller_business_name: Option<String>, /// Date converted into UTC that the Seller started using the Merchant's services. The accepted value length is /// 8 characters. The accepted format is: YYYYMMDD. seller_acc_date: Option<String>, /// First line of the business or contact street address of the Seller. The value length is maximum 50 characters. /// This field is optional. seller_addr_line1: Option<String>, /// Second line of the business or contact street address of the Seller. The value length is maximum 50 characters. /// This field is optional. seller_addr_line2: Option<String>, /// Third line of the business or contact street address of the Seller. The value length is maximum 50 characters. /// This field is optional. seller_addr_line3: Option<String>, /// Business or contact city of the Seller. The value length is maximum 50 characters. This field is optional. seller_addr_city: Option<String>, /// Business or contact state or province of the Seller. The value length is maximum 3 characters. Accepted values /// are: Country subdivision code defined in ISO 3166-2. For example, using the ISO entry US-CA (California, /// United States), the correct value for this field = CA. Note that the country and hyphen are not included in /// this value. This field is optional. seller_addr_state: Option<String>, /// Business or contact ZIP or other postal code of the Seller. The value length is maximum 16 characters. /// This field is optional. seller_addr_post_code: Option<String>, /// Business or contact country of the Seller. The accepted value length is 3 characters. Accepted values are /// ISO 3166-1 numeric three-digit country code, except 955-964 and 999. This field is optional. seller_addr_country: Option<String>, /// Business or contact email address of the Seller. The value length is maximum 254 characters. Accepted values /// shall meet requirements of Section 3.4 of IETF RFC 5322. This field is optional. seller_email: Option<String>, /// Business or contact phone number of the Seller. Country Code and Subscriber sections of the number represented /// by the following named fields: /// - cc -> Accepted value length is 1-3 characters. /// - subscriber -> Accepted value length is maximum 15 characters. /// This field is optional. seller_phone: Option<PhoneNumber>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct Browser { /// Exact content of the HTTP accept headers as sent to the 3DS Requestor from the Cardholder's browser. /// This field is limited to maximum 2048 characters and if the total length exceeds the limit, the 3DS Server /// truncates the excess portion. /// /// This field is required for requests where deviceChannel=02 (BRW). browser_accept_header: Option<String>, /// IP address of the browser as returned by the HTTP headers to the 3DS Requestor. The field is limited to maximum 45 /// characters and the accepted values are as following: /// - IPv4 address is represented in the dotted decimal format of 4 sets of decimal numbers separated by dots. The /// decimal number in each and every set is in the range 0 - 255. Example: 1.12.123.255 /// - IPv6 address is represented as eight groups of four hexadecimal digits, each group representing 16 bits (two /// octets). The groups are separated by colons (:). Example: 2011:0db8:85a3:0101:0101:8a2e:0370:7334 /// /// This field is required for requests when deviceChannel = 02 (BRW) where regionally acceptable. #[serde(rename = "browserIP")] browser_ip: Option<masking::Secret<String, common_utils::pii::IpAddress>>, /// Boolean that represents the ability of the cardholder browser to execute Java. Value is returned from the /// navigator.javaEnabled property. /// /// Depending on the message version, the field is required for requests: /// - with message version = 2.1.0 and deviceChannel = 02 (BRW). /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true. browser_java_enabled: Option<bool>, /// Value representing the browser language as defined in IETF BCP47. /// /// Until EMV 3DS 2.2.0: /// The value is limited to 1-8 characters. If the value exceeds 8 characters, it will be truncated to a /// semantically valid value, if possible. The value is returned from navigator.language property. /// /// This field is required for requests where deviceChannel = 02 (BRW) /// In other cases this field is optional. /// /// Starting from EMV 3DS 2.3.1: /// The value is limited to 35 characters. If the value exceeds 35 characters, it will be truncated to a /// semantically valid value, if possible. The value is returned from navigator.language property. /// /// This field is required for requests where deviceChannel = 02 (BRW) and browserJavascriptEnabled = true. /// In other cases this field is optional. browser_language: Option<String>, /// Value representing the bit depth of the colour palette for displaying images, in bits per pixel. Obtained from /// Cardholder browser using the screen.colorDepth property. The field is limited to 1-2 characters. /// /// Accepted values are: /// - 1 -> 1 bit /// - 4 -> 4 bits /// - 8 -> 8 bits /// - 15 -> 15 bits /// - 16 -> 16 bits /// - 24 -> 24 bits /// - 32 -> 32 bits /// - 48 -> 48 bits /// /// If the value is not in the accepted values, it will be resolved to the first accepted value lower from the one /// provided. /// /// Depending on the message version, the field is required for requests: /// - with message version = 2.1.0 and deviceChannel = 02 (BRW). /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true. browser_color_depth: Option<String>, /// Total height of the Cardholder's screen in pixels. Value is returned from the screen.height property. The value is /// limited to 1-6 characters. /// /// Depending on the message version, the field is required for requests: /// - with message version = 2.1.0 and deviceChannel = 02 (BRW). /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true. browser_screen_height: Option<u32>, /// Total width of the Cardholder's screen in pixels. Value is returned from the screen.width property. The value is /// limited to 1-6 characters. /// /// Depending on the message version, the field is required for requests: /// - with message version = 2.1.0 and deviceChannel = 02 (BRW). /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true. browser_screen_width: Option<u32>, /// Time difference between UTC time and the Cardholder browser local time, in minutes. The field is limited to 1-5 /// characters where the vauyes is returned from the getTimezoneOffset() method. /// /// Depending on the message version, the field is required for requests: /// - with message version = 2.1.0 and deviceChannel = 02 (BRW). /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true. #[serde(rename = "browserTZ")] browser_tz: Option<i32>, /// Exact content of the HTTP user-agent header. The field is limited to maximum 2048 characters. If the total length of /// the User-Agent sent by the browser exceeds 2048 characters, the 3DS Server truncates the excess portion. /// /// This field is required for requests where deviceChannel = 02 (BRW). browser_user_agent: Option<String>, /// Dimensions of the challenge window that has been displayed to the Cardholder. The ACS shall reply with content /// that is formatted to appropriately render in this window to provide the best possible user experience. /// /// Preconfigured sizes are width X height in pixels of the window displayed in the Cardholder browser window. This is /// used only to prepare the CReq request and it is not part of the AReq flow. If not present it will be omitted. /// /// However, when sending the Challenge Request, this field is required when deviceChannel = 02 (BRW). /// /// Accepted values are: /// - 01 -> 250 x 400 /// - 02 -> 390 x 400 /// - 03 -> 500 x 600 /// - 04 -> 600 x 400 /// - 05 -> Full screen challenge_window_size: Option<ChallengeWindowSizeEnum>, /// Boolean that represents the ability of the cardholder browser to execute JavaScript. /// /// This field is required for requests where deviceChannel = 02 (BRW). /// Available for supporting EMV 3DS 2.2.0 and later versions. browser_javascript_enabled: Option<bool>, /// Value representing the browser language preference present in the http header, as defined in IETF BCP 47. /// /// The value is limited to 1-99 elements. Each element should contain a maximum of 100 characters. /// /// This field is required for requests where deviceChannel = 02 (BRW). /// Available for supporting EMV 3DS 2.3.1 and later versions. accept_language: Option<Vec<String>>, } // Split by comma and return the list of accept languages // If Accept-Language is : fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, List should be [fr-CH, fr, en, de] pub fn get_list_of_accept_languages(accept_language: String) -> Vec<String> { accept_language .split(',') .map(|lang| lang.split(';').next().unwrap_or(lang).trim().to_string()) .collect() } impl From<BrowserInformation> for Browser { fn from(value: BrowserInformation) -> Self { Self { browser_accept_header: value.accept_header, browser_ip: value .ip_address .map(|ip| masking::Secret::new(ip.to_string())), browser_java_enabled: value.java_enabled, browser_language: value.language, browser_color_depth: value.color_depth.map(|cd| cd.to_string()), browser_screen_height: value.screen_height, browser_screen_width: value.screen_width, browser_tz: value.time_zone, browser_user_agent: value.user_agent, challenge_window_size: Some(ChallengeWindowSizeEnum::FullScreen), browser_javascript_enabled: value.java_script_enabled, // Default to ["en"] locale if accept_language is not provided accept_language: value .accept_language .map(get_list_of_accept_languages) .or(Some(vec!["en".to_string()])), } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ChallengeWindowSizeEnum { #[serde(rename = "01")] Size250x400, #[serde(rename = "02")] Size390x400, #[serde(rename = "03")] Size500x600, #[serde(rename = "04")] Size600x400, #[serde(rename = "05")] FullScreen, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct Sdk { /// Universally unique ID created upon all installations and updates of the 3DS Requestor App on a Customer Device. /// This will be newly generated and stored by the 3DS SDK for each installation or update. The field is limited to 36 /// characters and it shall have a canonical format as defined in IETF RFC 4122. This may utilize any of the specified /// versions as long as the output meets specified requirements. /// /// Starting from EMV 3DS 2.3.1: /// In case of Browser-SDK, the SDK App ID value is not reliable, and may change for each transaction. #[serde(rename = "sdkAppID")] sdk_app_id: Option<String>, /// JWE Object as defined Section 6.2.2.1 containing data encrypted by the SDK for the DS to decrypt. This element is /// the only field encrypted in this version of the EMV 3-D Secure specification. The field is sent from the SDK and it /// is limited to 64.000 characters. The data will be present when sending to DS, but not present from DS to ACS. sdk_enc_data: Option<String>, /// Public key component of the ephemeral key pair generated by the 3DS SDK and used to establish session keys between /// the 3DS SDK and ACS. In AReq, this data element is contained within the ACS Signed Content JWS Object. The field is /// limited to maximum 256 characters. sdk_ephem_pub_key: Option<HashMap<String, String>>, /// Indicates the maximum amount of time (in minutes) for all exchanges. The field shall have value greater or equals /// than 05. sdk_max_timeout: Option<u8>, /// Identifies the vendor and version of the 3DS SDK that is integrated in a 3DS Requestor App, assigned by EMVCo when /// the 3DS SDK is approved. The field is limited to 32 characters. /// /// Starting from EMV 3DS 2.3.1: /// Identifies the vendor and version of the 3DS SDK that is utilised for a specific transaction. The value is /// assigned by EMVCo when the Letter of Approval of the specific 3DS SDK is issued. sdk_reference_number: Option<String>, /// Universally unique transaction identifier assigned by the 3DS SDK to identify a single transaction. The field is /// limited to 36 characters and it shall be in a canonical format as defined in IETF RFC 4122. This may utilize any of /// the specified versions as long as the output meets specific requirements. #[serde(rename = "sdkTransID")] sdk_trans_id: Option<String>, /// Contains the JWS object(represented as a string) created by the Split-SDK Server for the AReq message. A /// Split-SDK Server creates a time-stamped signature on certain transaction data that is sent to the DS for /// verification. As a prerequisite, the Split-SDK Server has a key pair PbSDK, PvSDK certificate Cert (PbSDK). This /// certificate is an X.509 certificate signed by a DS CA whose public key is known to the DS. /// /// The Split-SDK Server: /// Creates a JSON object of the following data as the JWS payload to be signed: /// /// - SDK Reference Number -> Identifies the vendor and version of the 3DS SDK that is utilised for a specific /// transaction. The value is assigned by EMVCo when the Letter of Approval of the /// specific 3DS SDK is issued. The field is limited to 32 characters. /// - SDK Signature Timestamp -> Date and time indicating when the 3DS SDK generated the Split-SDK Server Signed /// Content converted into UTC. The value is limited to 14 characters. Accepted /// format: YYYYMMDDHHMMSS. /// - SDK Transaction ID -> Universally unique transaction identifier assigned by the 3DS SDK to identify a /// single transaction. The field is limited to 36 characters and it shall be in a /// canonical format as defined in IETF RFC 4122. This may utilize any of the specified /// versions as long as the output meets specific requirements. /// - Split-SDK Server ID -> DS assigned Split-SDK Server identifier. Each DS can provide a unique ID to each /// Split-SDK Server on an individual basis. The field is limited to 32 characters. /// Any individual DS may impose specific formatting and character requirements on the /// contents of this field. /// /// Generates a digital signature of the full JSON object according to JWS (RFC 7515) using JWS Compact /// Serialization. The parameter values for this version of the specification and to be included in the JWS /// header are: /// /// - `alg`: PS2567 or ES256 /// - `x5c`: X.5C v3: Cert (PbSDK) and chaining certificates if present /// /// All other parameters: optional /// /// Includes the resulting JWS in the AReq message as SDK Server Signed Content /// /// This field is required if sdkType = 02 or 03 and deviceChannel = 01 (APP) /// Available for supporting EMV 3DS 2.3.1 and later versions. sdk_server_signed_content: Option<String>, /// Indicates the type of 3DS SDK. /// This data element provides additional information to the DS and ACS to determine the best approach for handling /// the transaction. Accepted values are: /// /// - 01 -> Default SDK /// - 02 -> Split-SDK /// - 03 -> Limited-SDK /// - 04 -> Browser-SDK /// - 05 -> Shell-SDK /// - 80-99 -> PS-specific value (dependent on the payment scheme type) /// /// This field is required for requests where deviceChannel = 01 (APP). /// Available for supporting EMV 3DS 2.3.1 and later versions. sdk_type: Option<SdkType>, /// Indicates the characteristics of a Default-SDK. /// /// This field is required for requests where deviceChannel = 01 (APP) and SDK Type = 01. /// Available for supporting EMV 3DS 2.3.1 and later versions. default_sdk_type: Option<DefaultSdkType>, /// Indicates the characteristics of a Split-SDK. /// /// This field is required for requests where deviceChannel = 01 (APP) and SDK Type = 02. /// Available for supporting EMV 3DS 2.3.1 and later versions. split_sdk_type: Option<SplitSdkType>, } impl From<api_models::payments::SdkInformation> for Sdk { fn from(sdk_info: api_models::payments::SdkInformation) -> Self { Self { sdk_app_id: Some(sdk_info.sdk_app_id), sdk_enc_data: Some(sdk_info.sdk_enc_data), sdk_ephem_pub_key: Some(sdk_info.sdk_ephem_pub_key), sdk_max_timeout: Some(sdk_info.sdk_max_timeout), sdk_reference_number: Some(sdk_info.sdk_reference_number), sdk_trans_id: Some(sdk_info.sdk_trans_id), sdk_server_signed_content: None, sdk_type: sdk_info .sdk_type .map(SdkType::from) .or(Some(SdkType::DefaultSdk)), default_sdk_type: Some(DefaultSdkType { // hardcoding this value because, it's the only value that is accepted sdk_variant: "01".to_string(), wrapped_ind: None, }), split_sdk_type: None, } } } impl From<api_models::payments::SdkType> for SdkType { fn from(sdk_type: api_models::payments::SdkType) -> Self { match sdk_type { api_models::payments::SdkType::DefaultSdk => Self::DefaultSdk, api_models::payments::SdkType::SplitSdk => Self::SplitSdk, api_models::payments::SdkType::LimitedSdk => Self::LimitedSdk, api_models::payments::SdkType::BrowserSdk => Self::BrowserSdk, api_models::payments::SdkType::ShellSdk => Self::ShellSdk, } } } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, /// - 80-99 -> PS-specific value (dependent on the payment scheme type) #[serde(untagged)] PsSpecific(String), } /// Struct representing characteristics of a Default-SDK. #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct DefaultSdkType { /// SDK Variant: SDK implementation characteristics /// - Length: 2 characters /// - Values accepted: /// - 01 = Native /// - 02–79 = Reserved for EMVCo future use (values invalid until defined by EMVCo) /// - 80–99 = Reserved for DS use sdk_variant: String, /// Wrapped Indicator: If the Default-SDK is embedded as a wrapped component in the 3DS Requestor App /// - Length: 1 character /// - Value accepted: Y = Wrapped /// - Only present if value = Y wrapped_ind: Option<String>, } /// Struct representing characteristics of a Split-SDK. #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct SplitSdkType { /// Split-SDK Variant: Implementation characteristics of the Split-SDK client /// - Length: 2 characters /// - Values accepted: /// - 01 = Native Client /// - 02 = Browser /// - 03 = Shell /// - 04–79 = Reserved for EMVCo future use (values invalid until defined by EMVCo) /// - 80–99 = Reserved for DS use sdk_variant: String, /// Limited Split-SDK Indicator: If the Split-SDK client has limited capabilities /// - Length: 1 character /// - Value accepted: /// • Y = Limited /// - Only present if value = Y limited_ind: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ThreeDSReqAuthMethod { /// No 3DS Requestor authentication occurred (i.e. cardholder "logged in" as guest) #[serde(rename = "01")] Guest, /// Login to the cardholder account at the 3DS Requestor system using 3DS Requestor's own credentials #[serde(rename = "02")] ThreeDsRequestorCredentials, /// Login to the cardholder account at the 3DS Requestor system using federated ID #[serde(rename = "03")] FederatedID, /// Login to the cardholder account at the 3DS Requestor system using issuer credentials #[serde(rename = "04")] IssuerCredentials, /// Login to the cardholder account at the 3DS Requestor system using third-party authentication #[serde(rename = "05")] ThirdPartyAuthentication, /// Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. #[serde(rename = "06")] FidoAuthenticator, /// Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator(FIDO assurance data signed). #[serde(rename = "07")] FidoAssuranceData, /// SRC Assurance Data. #[serde(rename = "08")] SRCAssuranceData, /// Additionally, 80-99 can be used for PS-specific values, regardless of protocol version. #[serde(untagged)] PsSpecificValue(String), } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct DeviceRenderingOptionsSupported { pub sdk_interface: SdkInterface, /// For Native UI SDK Interface accepted values are 01-04 and for HTML UI accepted values are 01-05. pub sdk_ui_type: Vec<SdkUiType>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum SdkInterface { #[serde(rename = "01")] Native, #[serde(rename = "02")] Html, #[serde(rename = "03")] Both, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum SdkUiType { #[serde(rename = "01")] Text, #[serde(rename = "02")] SingleSelect, #[serde(rename = "03")] MultiSelect, #[serde(rename = "04")] Oob, #[serde(rename = "05")] HtmlOther, }
crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs
hyperswitch_connectors::src::connectors::netcetera::netcetera_types
19,891
true
// File: crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs // Module: hyperswitch_connectors::src::connectors::vgs::transformers use common_utils::{ ext_traits::{Encode, StringExt}, types::StringMinorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, RouterData}, router_flow_types::{ExternalVaultInsertFlow, ExternalVaultRetrieveFlow}, router_request_types::VaultRequestData, router_response_types::VaultResponseData, types::VaultRouterData, vault::PaymentMethodVaultingData, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::types::ResponseRouterData; pub struct VgsRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for VgsRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { Self { amount, router_data: item, } } } const VGS_FORMAT: &str = "UUID"; const VGS_CLASSIFIER: &str = "data"; #[derive(Default, Debug, Serialize, PartialEq)] pub struct VgsTokenRequestItem { value: Secret<String>, classifiers: Vec<String>, format: String, } #[derive(Default, Debug, Serialize, PartialEq)] pub struct VgsInsertRequest { data: Vec<VgsTokenRequestItem>, } impl<F> TryFrom<&VaultRouterData<F>> for VgsInsertRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &VaultRouterData<F>) -> Result<Self, Self::Error> { match item.request.payment_method_vaulting_data.clone() { Some(PaymentMethodVaultingData::Card(req_card)) => { let stringified_card = req_card .encode_to_string_of_json() .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Self { data: vec![VgsTokenRequestItem { value: Secret::new(stringified_card), classifiers: vec![VGS_CLASSIFIER.to_string()], format: VGS_FORMAT.to_string(), }], }) } _ => Err(errors::ConnectorError::NotImplemented( "Payment method apart from card".to_string(), ) .into()), } } } pub struct VgsAuthType { pub(super) username: Secret<String>, pub(super) password: Secret<String>, // vault_id is used in sessions API pub(super) _vault_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for VgsAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { username: api_key.to_owned(), password: key1.to_owned(), _vault_id: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct VgsAliasItem { alias: String, format: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct VgsTokenResponseItem { value: Secret<String>, classifiers: Vec<String>, aliases: Vec<VgsAliasItem>, created_at: Option<String>, storage: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct VgsInsertResponse { data: Vec<VgsTokenResponseItem>, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct VgsRetrieveResponse { data: Vec<VgsTokenResponseItem>, } impl TryFrom< ResponseRouterData< ExternalVaultInsertFlow, VgsInsertResponse, VaultRequestData, VaultResponseData, >, > for RouterData<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< ExternalVaultInsertFlow, VgsInsertResponse, VaultRequestData, VaultResponseData, >, ) -> Result<Self, Self::Error> { let vgs_alias = item .response .data .first() .and_then(|val| val.aliases.first()) .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; Ok(Self { status: common_enums::AttemptStatus::Started, response: Ok(VaultResponseData::ExternalVaultInsertResponse { connector_vault_id: vgs_alias.alias.clone(), fingerprint_id: vgs_alias.alias.clone(), }), ..item.data }) } } impl TryFrom< ResponseRouterData< ExternalVaultRetrieveFlow, VgsRetrieveResponse, VaultRequestData, VaultResponseData, >, > for RouterData<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< ExternalVaultRetrieveFlow, VgsRetrieveResponse, VaultRequestData, VaultResponseData, >, ) -> Result<Self, Self::Error> { let token_response_item = item .response .data .first() .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; let card_detail: api_models::payment_methods::CardDetail = token_response_item .value .clone() .expose() .parse_struct("CardDetail") .change_context(errors::ConnectorError::ParsingFailed)?; Ok(Self { status: common_enums::AttemptStatus::Started, response: Ok(VaultResponseData::ExternalVaultRetrieveResponse { vault_data: PaymentMethodVaultingData::Card(card_detail), }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct VgsErrorItem { pub status: u16, pub code: String, pub detail: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct VgsErrorResponse { pub errors: Vec<VgsErrorItem>, pub trace_id: String, }
crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs
hyperswitch_connectors::src::connectors::vgs::transformers
1,443
true
// File: crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs // Module: hyperswitch_connectors::src::connectors::ebanx::transformers #[cfg(feature = "payouts")] use api_models::enums::Currency; #[cfg(feature = "payouts")] use api_models::payouts::{Bank, PayoutMethodData}; #[cfg(feature = "payouts")] use common_enums::{PayoutStatus, PayoutType}; #[cfg(feature = "payouts")] use common_utils::pii::Email; use common_utils::types::FloatMajorUnit; use hyperswitch_domain_models::router_data::ConnectorAuthType; #[cfg(feature = "payouts")] use hyperswitch_domain_models::router_flow_types::PoCreate; #[cfg(feature = "payouts")] use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData}; use hyperswitch_interfaces::errors::ConnectorError; #[cfg(feature = "payouts")] use masking::ExposeInterface; use masking::Secret; use serde::{Deserialize, Serialize}; #[cfg(feature = "payouts")] use crate::types::PayoutsResponseRouterData; #[cfg(feature = "payouts")] use crate::utils::{ AddressDetailsData as _, CustomerDetails as _, PayoutsData as _, RouterData as _, }; pub struct EbanxRouterData<T> { pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for EbanxRouterData<T> { fn from((amount, item): (FloatMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Clone)] pub struct EbanxPayoutCreateRequest { integration_key: Secret<String>, external_reference: String, country: String, amount: FloatMajorUnit, currency: Currency, target: EbanxPayoutType, target_account: Secret<String>, payee: EbanxPayoutDetails, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Clone)] pub enum EbanxPayoutType { BankAccount, Mercadopago, EwalletNequi, PixKey, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Clone)] pub struct EbanxPayoutDetails { name: Secret<String>, email: Option<Email>, document: Option<Secret<String>>, document_type: Option<EbanxDocumentType>, bank_info: EbanxBankDetails, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Clone)] pub enum EbanxDocumentType { #[serde(rename = "CPF")] NaturalPersonsRegister, #[serde(rename = "CNPJ")] NationalRegistryOfLegalEntities, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Clone)] pub struct EbanxBankDetails { bank_name: Option<String>, bank_branch: Option<String>, bank_account: Option<Secret<String>>, account_type: Option<EbanxBankAccountType>, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Clone)] pub enum EbanxBankAccountType { #[serde(rename = "C")] CheckingAccount, } #[cfg(feature = "payouts")] impl TryFrom<&EbanxRouterData<&PayoutsRouterData<PoCreate>>> for EbanxPayoutCreateRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &EbanxRouterData<&PayoutsRouterData<PoCreate>>) -> Result<Self, Self::Error> { let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?; match item.router_data.get_payout_method_data()? { PayoutMethodData::Bank(Bank::Pix(pix_data)) => { let bank_info = EbanxBankDetails { bank_account: Some(pix_data.bank_account_number), bank_branch: pix_data.bank_branch, bank_name: pix_data.bank_name, account_type: Some(EbanxBankAccountType::CheckingAccount), }; let billing_address = item.router_data.get_billing_address()?; let customer_details = item.router_data.request.get_customer_details()?; let document_type = pix_data.tax_id.clone().map(|tax_id| { if tax_id.clone().expose().len() == 11 { EbanxDocumentType::NaturalPersonsRegister } else { EbanxDocumentType::NationalRegistryOfLegalEntities } }); let payee = EbanxPayoutDetails { name: billing_address.get_full_name()?, email: customer_details.email.clone(), bank_info, document_type, document: pix_data.tax_id.to_owned(), }; Ok(Self { amount: item.amount, integration_key: ebanx_auth_type.integration_key, country: customer_details.get_customer_phone_country_code()?, currency: item.router_data.request.source_currency, external_reference: item.router_data.connector_request_reference_id.to_owned(), target: EbanxPayoutType::PixKey, target_account: pix_data.pix_key, payee, }) } PayoutMethodData::Card(_) | PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) | PayoutMethodData::BankRedirect(_) => Err(ConnectorError::NotSupported { message: "Payment Method Not Supported".to_string(), connector: "Ebanx", })?, } } } pub struct EbanxAuthType { pub integration_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for EbanxAuthType { type Error = error_stack::Report<ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { integration_key: api_key.to_owned(), }), _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum EbanxPayoutStatus { #[serde(rename = "PA")] Succeeded, #[serde(rename = "CA")] Cancelled, #[serde(rename = "PE")] Processing, #[serde(rename = "OP")] RequiresFulfillment, } #[cfg(feature = "payouts")] impl From<EbanxPayoutStatus> for PayoutStatus { fn from(item: EbanxPayoutStatus) -> Self { match item { EbanxPayoutStatus::Succeeded => Self::Success, EbanxPayoutStatus::Cancelled => Self::Cancelled, EbanxPayoutStatus::Processing => Self::Pending, EbanxPayoutStatus::RequiresFulfillment => Self::RequiresFulfillment, } } } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EbanxPayoutResponse { payout: EbanxPayoutResponseDetails, } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EbanxPayoutResponseDetails { uid: String, status: EbanxPayoutStatus, } #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxPayoutResponse>> for PayoutsRouterData<F> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: PayoutsResponseRouterData<F, EbanxPayoutResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PayoutsResponseData { status: Some(PayoutStatus::from(item.response.payout.status)), connector_payout_id: Some(item.response.payout.uid), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EbanxPayoutFulfillRequest { integration_key: Secret<String>, uid: String, } #[cfg(feature = "payouts")] impl<F> TryFrom<&EbanxRouterData<&PayoutsRouterData<F>>> for EbanxPayoutFulfillRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &EbanxRouterData<&PayoutsRouterData<F>>) -> Result<Self, Self::Error> { let request = item.router_data.request.to_owned(); let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?; let payout_type = request.get_payout_type()?; match payout_type { PayoutType::Bank => Ok(Self { integration_key: ebanx_auth_type.integration_key, uid: request .connector_payout_id .to_owned() .ok_or(ConnectorError::MissingRequiredField { field_name: "uid" })?, }), PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => { Err(ConnectorError::NotSupported { message: "Payout Method Not Supported".to_string(), connector: "Ebanx", })? } } } } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EbanxFulfillResponse { #[serde(rename = "type")] status: EbanxFulfillStatus, message: String, } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum EbanxFulfillStatus { Success, ApiError, AuthenticationError, InvalidRequestError, RequestError, } #[cfg(feature = "payouts")] impl From<EbanxFulfillStatus> for PayoutStatus { fn from(item: EbanxFulfillStatus) -> Self { match item { EbanxFulfillStatus::Success => Self::Success, EbanxFulfillStatus::ApiError | EbanxFulfillStatus::AuthenticationError | EbanxFulfillStatus::InvalidRequestError | EbanxFulfillStatus::RequestError => Self::Failed, } } } #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxFulfillResponse>> for PayoutsRouterData<F> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: PayoutsResponseRouterData<F, EbanxFulfillResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PayoutsResponseData { status: Some(PayoutStatus::from(item.response.status)), connector_payout_id: Some(item.data.request.get_transfer_id()?), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct EbanxErrorResponse { pub code: String, pub status_code: String, pub message: Option<String>, } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EbanxPayoutCancelRequest { integration_key: Secret<String>, uid: String, } #[cfg(feature = "payouts")] impl<F> TryFrom<&PayoutsRouterData<F>> for EbanxPayoutCancelRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let ebanx_auth_type = EbanxAuthType::try_from(&item.connector_auth_type)?; let payout_type = request.get_payout_type()?; match payout_type { PayoutType::Bank => Ok(Self { integration_key: ebanx_auth_type.integration_key, uid: request .connector_payout_id .to_owned() .ok_or(ConnectorError::MissingRequiredField { field_name: "uid" })?, }), PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => { Err(ConnectorError::NotSupported { message: "Payout Method Not Supported".to_string(), connector: "Ebanx", })? } } } } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EbanxCancelResponse { #[serde(rename = "type")] status: EbanxCancelStatus, message: String, } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum EbanxCancelStatus { Success, ApiError, AuthenticationError, InvalidRequestError, RequestError, } #[cfg(feature = "payouts")] impl From<EbanxCancelStatus> for PayoutStatus { fn from(item: EbanxCancelStatus) -> Self { match item { EbanxCancelStatus::Success => Self::Cancelled, EbanxCancelStatus::ApiError | EbanxCancelStatus::AuthenticationError | EbanxCancelStatus::InvalidRequestError | EbanxCancelStatus::RequestError => Self::Failed, } } } #[cfg(feature = "payouts")] impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxCancelResponse>> for PayoutsRouterData<F> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: PayoutsResponseRouterData<F, EbanxCancelResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PayoutsResponseData { status: Some(PayoutStatus::from(item.response.status)), connector_payout_id: item.data.request.connector_payout_id.clone(), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } }
crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs
hyperswitch_connectors::src::connectors::ebanx::transformers
3,202
true
// File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers.rs // Module: hyperswitch_connectors::src::connectors::signifyd::transformers #[cfg(feature = "frm")] pub mod api; pub mod auth; #[cfg(feature = "frm")] pub use self::api::*; pub use self::auth::*;
crates/hyperswitch_connectors/src/connectors/signifyd/transformers.rs
hyperswitch_connectors::src::connectors::signifyd::transformers
75
true
// File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers/auth.rs // Module: hyperswitch_connectors::src::connectors::signifyd::transformers::auth use error_stack; use hyperswitch_domain_models::router_data::ConnectorAuthType; use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; pub struct SignifydAuthType { pub api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for SignifydAuthType { type Error = error_stack::Report<ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } }
crates/hyperswitch_connectors/src/connectors/signifyd/transformers/auth.rs
hyperswitch_connectors::src::connectors::signifyd::transformers::auth
193
true
// File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs // Module: hyperswitch_connectors::src::connectors::signifyd::transformers::api use api_models::webhooks::IncomingWebhookEvent; use common_enums::{AttemptStatus, Currency, FraudCheckStatus, PaymentMethod}; use common_utils::{ext_traits::ValueExt, pii::Email}; use error_stack::{self, ResultExt}; pub use hyperswitch_domain_models::router_request_types::fraud_check::RefundMethod; use hyperswitch_domain_models::{ router_data::RouterData, router_flow_types::Fulfillment, router_request_types::{ fraud_check::{self, FraudCheckFulfillmentData, FrmFulfillmentRequest}, ResponseId, }, router_response_types::fraud_check::FraudCheckResponseData, }; use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use num_traits::ToPrimitive; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{ types::{ FrmCheckoutRouterData, FrmFulfillmentRouterData, FrmRecordReturnRouterData, FrmSaleRouterData, FrmTransactionRouterData, ResponseRouterData, }, utils::{ AddressDetailsData as _, FraudCheckCheckoutRequest, FraudCheckRecordReturnRequest as _, FraudCheckSaleRequest as _, FraudCheckTransactionRequest as _, RouterData as _, }, }; #[allow(dead_code)] #[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum DecisionDelivery { Sync, AsyncOnly, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Purchase { #[serde(with = "common_utils::custom_serde::iso8601")] created_at: PrimitiveDateTime, order_channel: OrderChannel, total_price: i64, products: Vec<Products>, shipments: Shipments, currency: Option<Currency>, total_shipping_cost: Option<i64>, confirmation_email: Option<Email>, confirmation_phone: Option<Secret<String>>, } #[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)] #[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))] pub enum OrderChannel { Web, Phone, MobileApp, Social, Marketplace, InStoreKiosk, ScanAndGo, SmartTv, Mit, } #[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)] #[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))] pub enum FulfillmentMethod { Delivery, CounterPickup, CubsidePickup, LockerPickup, StandardShipping, ExpeditedShipping, GasPickup, ScheduledDelivery, } #[derive(Debug, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Products { item_name: String, item_price: i64, item_quantity: i32, item_id: Option<String>, item_category: Option<String>, item_sub_category: Option<String>, item_is_digital: Option<bool>, } #[derive(Debug, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Shipments { destination: Destination, fulfillment_method: Option<FulfillmentMethod>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Destination { full_name: Secret<String>, organization: Option<String>, email: Option<Email>, address: Address, } #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Address { street_address: Secret<String>, unit: Option<Secret<String>>, postal_code: Secret<String>, city: String, province_code: Secret<String>, country_code: common_enums::CountryAlpha2, } #[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)] #[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))] pub enum CoverageRequests { Fraud, // use when you need a financial guarantee for Payment Fraud. Inr, // use when you need a financial guarantee for Item Not Received. Snad, // use when you need a financial guarantee for fraud alleging items are Significantly Not As Described. All, // use when you need a financial guarantee on all chargebacks. None, // use when you do not need a financial guarantee. Suggested actions in decision.checkpointAction are recommendations. } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SignifydPaymentsSaleRequest { order_id: String, purchase: Purchase, decision_delivery: DecisionDelivery, coverage_requests: Option<CoverageRequests>, } #[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)] #[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))] pub struct SignifydFrmMetadata { pub total_shipping_cost: Option<i64>, pub fulfillment_method: Option<FulfillmentMethod>, pub coverage_request: Option<CoverageRequests>, pub order_channel: OrderChannel, } impl TryFrom<&FrmSaleRouterData> for SignifydPaymentsSaleRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &FrmSaleRouterData) -> Result<Self, Self::Error> { let products = item .request .get_order_details()? .iter() .map(|order_detail| Products { item_name: order_detail.product_name.clone(), item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future. item_quantity: i32::from(order_detail.quantity), item_id: order_detail.product_id.clone(), item_category: order_detail.category.clone(), item_sub_category: order_detail.sub_category.clone(), item_is_digital: order_detail .product_type .as_ref() .map(|product| product == &common_enums::ProductType::Digital), }) .collect::<Vec<_>>(); let metadata: SignifydFrmMetadata = item .frm_metadata .clone() .ok_or(ConnectorError::MissingRequiredField { field_name: "frm_metadata", })? .parse_value("Signifyd Frm Metadata") .change_context(ConnectorError::InvalidDataFormat { field_name: "frm_metadata", })?; let ship_address = item.get_shipping_address()?; let billing_address = item.get_billing()?; let street_addr = ship_address.get_line1()?; let city_addr = ship_address.get_city()?; let zip_code_addr = ship_address.get_zip()?; let country_code_addr = ship_address.get_country()?; let _first_name_addr = ship_address.get_first_name()?; let _last_name_addr = ship_address.get_last_name()?; let address: Address = Address { street_address: street_addr.clone(), unit: None, postal_code: zip_code_addr.clone(), city: city_addr.clone(), province_code: zip_code_addr.clone(), country_code: country_code_addr.to_owned(), }; let destination: Destination = Destination { full_name: ship_address.get_full_name().unwrap_or_default(), organization: None, email: None, address, }; let created_at = common_utils::date_time::now(); let order_channel = metadata.order_channel; let shipments = Shipments { destination, fulfillment_method: metadata.fulfillment_method, }; let purchase = Purchase { created_at, order_channel, total_price: item.request.amount, products, shipments, currency: item.request.currency, total_shipping_cost: metadata.total_shipping_cost, confirmation_email: item.request.email.clone(), confirmation_phone: billing_address .clone() .phone .and_then(|phone_data| phone_data.number), }; Ok(Self { order_id: item.attempt_id.clone(), purchase, decision_delivery: DecisionDelivery::Sync, // Specify SYNC if you require the Response to contain a decision field. If you have registered for a webhook associated with this checkpoint, then the webhook will also be sent when SYNC is specified. If ASYNC_ONLY is specified, then the decision field in the response will be null, and you will require a Webhook integration to receive Signifyd's final decision coverage_requests: metadata.coverage_request, }) } } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Decision { #[serde(with = "common_utils::custom_serde::iso8601")] created_at: PrimitiveDateTime, checkpoint_action: SignifydPaymentStatus, checkpoint_action_reason: Option<String>, checkpoint_action_policy: Option<String>, score: Option<f64>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SignifydPaymentStatus { Accept, Challenge, Credit, Hold, Reject, } impl From<SignifydPaymentStatus> for FraudCheckStatus { fn from(item: SignifydPaymentStatus) -> Self { match item { SignifydPaymentStatus::Accept => Self::Legit, SignifydPaymentStatus::Reject => Self::Fraud, SignifydPaymentStatus::Hold => Self::ManualReview, SignifydPaymentStatus::Challenge | SignifydPaymentStatus::Credit => Self::Pending, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SignifydPaymentsResponse { signifyd_id: i64, order_id: String, decision: Decision, } impl<F, T> TryFrom<ResponseRouterData<F, SignifydPaymentsResponse, T, FraudCheckResponseData>> for RouterData<F, T, FraudCheckResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, SignifydPaymentsResponse, T, FraudCheckResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(FraudCheckResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id), status: FraudCheckStatus::from(item.response.decision.checkpoint_action), connector_metadata: None, score: item.response.decision.score.and_then(|data| data.to_i32()), reason: item .response .decision .checkpoint_action_reason .map(serde_json::Value::from), }), ..item.data }) } } #[derive(Debug, Deserialize, PartialEq, Serialize)] pub struct SignifydErrorResponse { pub messages: Vec<String>, pub errors: serde_json::Value, } #[derive(Debug, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Transactions { transaction_id: String, gateway_status_code: String, payment_method: PaymentMethod, amount: i64, currency: Currency, gateway: Option<String>, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SignifydPaymentsTransactionRequest { order_id: String, checkout_id: String, transactions: Transactions, } impl From<AttemptStatus> for GatewayStatusCode { fn from(item: AttemptStatus) -> Self { match item { AttemptStatus::Pending => Self::Pending, AttemptStatus::Failure => Self::Failure, AttemptStatus::Charged => Self::Success, _ => Self::Pending, } } } impl TryFrom<&FrmTransactionRouterData> for SignifydPaymentsTransactionRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &FrmTransactionRouterData) -> Result<Self, Self::Error> { let currency = item.request.get_currency()?; let transactions = Transactions { amount: item.request.amount, transaction_id: item.clone().payment_id, gateway_status_code: GatewayStatusCode::from(item.status).to_string(), payment_method: item.payment_method, currency, gateway: item.request.connector.clone(), }; Ok(Self { order_id: item.attempt_id.clone(), checkout_id: item.payment_id.clone(), transactions, }) } } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GatewayStatusCode { Success, Failure, #[default] Pending, Error, Cancelled, Expired, SoftDecline, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SignifydPaymentsCheckoutRequest { checkout_id: String, order_id: String, purchase: Purchase, coverage_requests: Option<CoverageRequests>, } impl TryFrom<&FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &FrmCheckoutRouterData) -> Result<Self, Self::Error> { let products = item .request .get_order_details()? .iter() .map(|order_detail| Products { item_name: order_detail.product_name.clone(), item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future. item_quantity: i32::from(order_detail.quantity), item_id: order_detail.product_id.clone(), item_category: order_detail.category.clone(), item_sub_category: order_detail.sub_category.clone(), item_is_digital: order_detail .product_type .as_ref() .map(|product| product == &common_enums::ProductType::Digital), }) .collect::<Vec<_>>(); let metadata: SignifydFrmMetadata = item .frm_metadata .clone() .ok_or(ConnectorError::MissingRequiredField { field_name: "frm_metadata", })? .parse_value("Signifyd Frm Metadata") .change_context(ConnectorError::InvalidDataFormat { field_name: "frm_metadata", })?; let ship_address = item.get_shipping_address()?; let street_addr = ship_address.get_line1()?; let city_addr = ship_address.get_city()?; let zip_code_addr = ship_address.get_zip()?; let country_code_addr = ship_address.get_country()?; let _first_name_addr = ship_address.get_first_name()?; let _last_name_addr = ship_address.get_last_name()?; let billing_address = item.get_billing()?; let address: Address = Address { street_address: street_addr.clone(), unit: None, postal_code: zip_code_addr.clone(), city: city_addr.clone(), province_code: zip_code_addr.clone(), country_code: country_code_addr.to_owned(), }; let destination: Destination = Destination { full_name: ship_address.get_full_name().unwrap_or_default(), organization: None, email: None, address, }; let created_at = common_utils::date_time::now(); let order_channel = metadata.order_channel; let shipments: Shipments = Shipments { destination, fulfillment_method: metadata.fulfillment_method, }; let purchase = Purchase { created_at, order_channel, total_price: item.request.amount, products, shipments, currency: item.request.currency, total_shipping_cost: metadata.total_shipping_cost, confirmation_email: item.request.email.clone(), confirmation_phone: billing_address .clone() .phone .and_then(|phone_data| phone_data.number), }; Ok(Self { checkout_id: item.payment_id.clone(), order_id: item.attempt_id.clone(), purchase, coverage_requests: metadata.coverage_request, }) } } #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct FrmFulfillmentSignifydRequest { pub order_id: String, pub fulfillment_status: Option<FulfillmentStatus>, pub fulfillments: Vec<Fulfillments>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(untagged)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub enum FulfillmentStatus { PARTIAL, COMPLETE, REPLACEMENT, CANCELED, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct Fulfillments { pub shipment_id: String, pub products: Option<Vec<Product>>, pub destination: Destination, pub fulfillment_method: Option<String>, pub carrier: Option<String>, pub shipment_status: Option<String>, pub tracking_urls: Option<Vec<String>>, pub tracking_numbers: Option<Vec<String>>, pub shipped_at: Option<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct Product { pub item_name: String, pub item_quantity: i64, pub item_id: String, } impl TryFrom<&FrmFulfillmentRouterData> for FrmFulfillmentSignifydRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &FrmFulfillmentRouterData) -> Result<Self, Self::Error> { Ok(Self { order_id: item.request.fulfillment_req.order_id.clone(), fulfillment_status: item .request .fulfillment_req .fulfillment_status .as_ref() .map(|fulfillment_status| FulfillmentStatus::from(&fulfillment_status.clone())), fulfillments: get_signifyd_fulfillments_from_frm_fulfillment_request( &item.request.fulfillment_req, ), }) } } impl From<&fraud_check::FulfillmentStatus> for FulfillmentStatus { fn from(status: &fraud_check::FulfillmentStatus) -> Self { match status { fraud_check::FulfillmentStatus::PARTIAL => Self::PARTIAL, fraud_check::FulfillmentStatus::COMPLETE => Self::COMPLETE, fraud_check::FulfillmentStatus::REPLACEMENT => Self::REPLACEMENT, fraud_check::FulfillmentStatus::CANCELED => Self::CANCELED, } } } pub(crate) fn get_signifyd_fulfillments_from_frm_fulfillment_request( fulfillment_req: &FrmFulfillmentRequest, ) -> Vec<Fulfillments> { fulfillment_req .fulfillments .iter() .map(|fulfillment| Fulfillments { shipment_id: fulfillment.shipment_id.clone(), products: fulfillment .products .as_ref() .map(|products| products.iter().map(|p| Product::from(p.clone())).collect()), destination: Destination::from(fulfillment.destination.clone()), tracking_urls: fulfillment_req.tracking_urls.clone(), tracking_numbers: fulfillment_req.tracking_numbers.clone(), fulfillment_method: fulfillment_req.fulfillment_method.clone(), carrier: fulfillment_req.carrier.clone(), shipment_status: fulfillment_req.shipment_status.clone(), shipped_at: fulfillment_req.shipped_at.clone(), }) .collect() } impl From<fraud_check::Product> for Product { fn from(product: fraud_check::Product) -> Self { Self { item_name: product.item_name, item_quantity: product.item_quantity, item_id: product.item_id, } } } impl From<fraud_check::Destination> for Destination { fn from(destination: fraud_check::Destination) -> Self { Self { full_name: destination.full_name, organization: destination.organization, email: destination.email, address: Address::from(destination.address), } } } impl From<fraud_check::Address> for Address { fn from(address: fraud_check::Address) -> Self { Self { street_address: address.street_address, unit: address.unit, postal_code: address.postal_code, city: address.city, province_code: address.province_code, country_code: address.country_code, } } } #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct FrmFulfillmentSignifydApiResponse { pub order_id: String, pub shipment_ids: Vec<String>, } impl TryFrom< ResponseRouterData< Fulfillment, FrmFulfillmentSignifydApiResponse, FraudCheckFulfillmentData, FraudCheckResponseData, >, > for RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData< Fulfillment, FrmFulfillmentSignifydApiResponse, FraudCheckFulfillmentData, FraudCheckResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(FraudCheckResponseData::FulfillmentResponse { order_id: item.response.order_id, shipment_ids: item.response.shipment_ids, }), ..item.data }) } } #[derive(Debug, Serialize, Eq, PartialEq, Clone)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct SignifydRefund { method: RefundMethod, amount: String, currency: Currency, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct SignifydPaymentsRecordReturnRequest { order_id: String, return_id: String, refund_transaction_id: Option<String>, refund: SignifydRefund, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct SignifydPaymentsRecordReturnResponse { return_id: String, order_id: String, } impl<F, T> TryFrom<ResponseRouterData<F, SignifydPaymentsRecordReturnResponse, T, FraudCheckResponseData>> for RouterData<F, T, FraudCheckResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData< F, SignifydPaymentsRecordReturnResponse, T, FraudCheckResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(FraudCheckResponseData::RecordReturnResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id), return_id: Some(item.response.return_id.to_string()), connector_metadata: None, }), ..item.data }) } } impl TryFrom<&FrmRecordReturnRouterData> for SignifydPaymentsRecordReturnRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &FrmRecordReturnRouterData) -> Result<Self, Self::Error> { let currency = item.request.get_currency()?; let refund = SignifydRefund { method: item.request.refund_method.clone(), amount: item.request.amount.to_string(), currency, }; Ok(Self { return_id: uuid::Uuid::new_v4().to_string(), refund_transaction_id: item.request.refund_transaction_id.clone(), refund, order_id: item.attempt_id.clone(), }) } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct SignifydWebhookBody { pub order_id: String, pub review_disposition: ReviewDisposition, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum ReviewDisposition { Fraudulent, Good, } impl From<ReviewDisposition> for IncomingWebhookEvent { fn from(value: ReviewDisposition) -> Self { match value { ReviewDisposition::Fraudulent => Self::FrmRejected, ReviewDisposition::Good => Self::FrmApproved, } } }
crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
hyperswitch_connectors::src::connectors::signifyd::transformers::api
5,413
true
// File: crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs // Module: hyperswitch_connectors::src::connectors::paybox::transformers use bytes::Bytes; use common_enums::enums; use common_utils::{ date_time::DateFormat, errors::CustomResult, ext_traits::ValueExt, types::MinorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{CompleteAuthorizeData, PaymentsAuthorizeData, ResponseId}, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types, }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors, }; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, AddressDetailsData, CardData as _, CardMandateInfo, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, RouterData as _, }, }; pub struct PayboxRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> From<(MinorUnit, T)> for PayboxRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } const AUTH_REQUEST: &str = "00001"; const CAPTURE_REQUEST: &str = "00002"; const AUTH_AND_CAPTURE_REQUEST: &str = "00003"; const SYNC_REQUEST: &str = "00017"; const REFUND_REQUEST: &str = "00014"; const SUCCESS_CODE: &str = "00000"; const VERSION_PAYBOX: &str = "00104"; const PAY_ORIGIN_INTERNET: &str = "024"; const THREE_DS_FAIL_CODE: &str = "00000000"; const RECURRING_ORIGIN: &str = "027"; const MANDATE_REQUEST: &str = "00056"; const MANDATE_AUTH_ONLY: &str = "00051"; const MANDATE_AUTH_AND_CAPTURE_ONLY: &str = "00053"; type Error = error_stack::Report<errors::ConnectorError>; #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PayboxPaymentsRequest { Card(PaymentsRequest), CardThreeDs(ThreeDSPaymentsRequest), Mandate(MandatePaymentRequest), } #[derive(Debug, Serialize)] pub struct PaymentsRequest { #[serde(rename = "DATEQ")] pub date: String, #[serde(rename = "TYPE")] pub transaction_type: String, #[serde(rename = "NUMQUESTION")] pub paybox_request_number: String, #[serde(rename = "MONTANT")] pub amount: MinorUnit, #[serde(rename = "REFERENCE")] pub description_reference: String, #[serde(rename = "VERSION")] pub version: String, #[serde(rename = "DEVISE")] pub currency: String, #[serde(rename = "PORTEUR")] pub card_number: cards::CardNumber, #[serde(rename = "DATEVAL")] pub expiration_date: Secret<String>, #[serde(rename = "CVV")] pub cvv: Secret<String>, #[serde(rename = "ACTIVITE")] pub activity: String, #[serde(rename = "SITE")] pub site: Secret<String>, #[serde(rename = "RANG")] pub rank: Secret<String>, #[serde(rename = "CLE")] pub key: Secret<String>, #[serde(rename = "ID3D")] #[serde(skip_serializing_if = "Option::is_none")] pub three_ds_data: Option<Secret<String>>, #[serde(rename = "REFABONNE")] #[serde(skip_serializing_if = "Option::is_none")] pub customer_id: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct ThreeDSPaymentsRequest { id_merchant: Secret<String>, id_session: String, amount: MinorUnit, currency: String, #[serde(rename = "CCNumber")] cc_number: cards::CardNumber, #[serde(rename = "CCExpDate")] cc_exp_date: Secret<String>, #[serde(rename = "CVVCode")] cvv_code: Secret<String>, #[serde(rename = "URLRetour")] url_retour: String, #[serde(rename = "URLHttpDirect")] url_http_direct: String, email_porteur: common_utils::pii::Email, first_name: Secret<String>, last_name: Secret<String>, address1: Secret<String>, zip_code: Secret<String>, city: String, country_code: String, total_quantity: i32, } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct PayboxCaptureRequest { #[serde(rename = "DATEQ")] pub date: String, #[serde(rename = "TYPE")] pub transaction_type: String, #[serde(rename = "NUMQUESTION")] pub paybox_request_number: String, #[serde(rename = "MONTANT")] pub amount: MinorUnit, #[serde(rename = "REFERENCE")] pub reference: String, #[serde(rename = "VERSION")] pub version: String, #[serde(rename = "DEVISE")] pub currency: String, #[serde(rename = "SITE")] pub site: Secret<String>, #[serde(rename = "RANG")] pub rank: Secret<String>, #[serde(rename = "CLE")] pub key: Secret<String>, #[serde(rename = "NUMTRANS")] pub transaction_number: String, #[serde(rename = "NUMAPPEL")] pub paybox_order_id: String, } impl TryFrom<&PayboxRouterData<&types::PaymentsCaptureRouterData>> for PayboxCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PayboxRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let currency = enums::Currency::iso_4217(item.router_data.request.currency).to_string(); let paybox_meta_data: PayboxMeta = utils::to_connector_meta(item.router_data.request.connector_meta.clone())?; let format_time = common_utils::date_time::format_date( common_utils::date_time::now(), DateFormat::DDMMYYYYHHmmss, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Self { date: format_time.clone(), transaction_type: CAPTURE_REQUEST.to_string(), paybox_request_number: get_paybox_request_number()?, version: VERSION_PAYBOX.to_string(), currency, site: auth_data.site, rank: auth_data.rang, key: auth_data.cle, transaction_number: paybox_meta_data.connector_request_id, paybox_order_id: item.router_data.request.connector_transaction_id.clone(), amount: item.amount, reference: item.router_data.connector_request_reference_id.to_string(), }) } } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct PayboxRsyncRequest { #[serde(rename = "DATEQ")] pub date: String, #[serde(rename = "TYPE")] pub transaction_type: String, #[serde(rename = "NUMQUESTION")] pub paybox_request_number: String, #[serde(rename = "VERSION")] pub version: String, #[serde(rename = "SITE")] pub site: Secret<String>, #[serde(rename = "RANG")] pub rank: Secret<String>, #[serde(rename = "CLE")] pub key: Secret<String>, #[serde(rename = "NUMTRANS")] pub transaction_number: String, #[serde(rename = "NUMAPPEL")] pub paybox_order_id: String, } impl TryFrom<&types::RefundSyncRouterData> for PayboxRsyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> { let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let format_time = common_utils::date_time::format_date( common_utils::date_time::now(), DateFormat::DDMMYYYYHHmmss, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Self { date: format_time.clone(), transaction_type: SYNC_REQUEST.to_string(), paybox_request_number: get_paybox_request_number()?, version: VERSION_PAYBOX.to_string(), site: auth_data.site, rank: auth_data.rang, key: auth_data.cle, transaction_number: item .request .connector_refund_id .clone() .ok_or(errors::ConnectorError::RequestEncodingFailed)?, paybox_order_id: item.request.connector_transaction_id.clone(), }) } } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct PayboxPSyncRequest { #[serde(rename = "DATEQ")] pub date: String, #[serde(rename = "TYPE")] pub transaction_type: String, #[serde(rename = "NUMQUESTION")] pub paybox_request_number: String, #[serde(rename = "VERSION")] pub version: String, #[serde(rename = "SITE")] pub site: Secret<String>, #[serde(rename = "RANG")] pub rank: Secret<String>, #[serde(rename = "CLE")] pub key: Secret<String>, #[serde(rename = "NUMTRANS")] pub transaction_number: String, #[serde(rename = "NUMAPPEL")] pub paybox_order_id: String, } impl TryFrom<&types::PaymentsSyncRouterData> for PayboxPSyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let format_time = common_utils::date_time::format_date( common_utils::date_time::now(), DateFormat::DDMMYYYYHHmmss, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let paybox_meta_data: PayboxMeta = utils::to_connector_meta(item.request.connector_meta.clone())?; Ok(Self { date: format_time.clone(), transaction_type: SYNC_REQUEST.to_string(), paybox_request_number: get_paybox_request_number()?, version: VERSION_PAYBOX.to_string(), site: auth_data.site, rank: auth_data.rang, key: auth_data.cle, transaction_number: paybox_meta_data.connector_request_id, paybox_order_id: item .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?, }) } } #[derive(Debug, Serialize, Deserialize)] pub struct PayboxMeta { pub connector_request_id: String, } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct PayboxRefundRequest { #[serde(rename = "DATEQ")] pub date: String, #[serde(rename = "TYPE")] pub transaction_type: String, #[serde(rename = "NUMQUESTION")] pub paybox_request_number: String, #[serde(rename = "MONTANT")] pub amount: MinorUnit, #[serde(rename = "VERSION")] pub version: String, #[serde(rename = "DEVISE")] pub currency: String, #[serde(rename = "SITE")] pub site: Secret<String>, #[serde(rename = "RANG")] pub rank: Secret<String>, #[serde(rename = "CLE")] pub key: Secret<String>, #[serde(rename = "NUMTRANS")] pub transaction_number: String, #[serde(rename = "NUMAPPEL")] pub paybox_order_id: String, } impl TryFrom<&PayboxRouterData<&types::PaymentsAuthorizeRouterData>> for PayboxPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PayboxRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let transaction_type = get_transaction_type( item.router_data.request.capture_method, item.router_data.request.is_mandate_payment(), )?; let currency = enums::Currency::iso_4217(item.router_data.request.currency).to_string(); let expiration_date = req_card.get_card_expiry_month_year_2_digit_with_delimiter("".to_owned())?; let format_time = common_utils::date_time::format_date( common_utils::date_time::now(), DateFormat::DDMMYYYYHHmmss, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; if item.router_data.is_three_ds() { let address = item.router_data.get_billing_address()?; Ok(Self::CardThreeDs(ThreeDSPaymentsRequest { id_merchant: auth_data.merchant_id, id_session: item.router_data.connector_request_reference_id.clone(), amount: item.amount, currency, cc_number: req_card.card_number, cc_exp_date: expiration_date, cvv_code: req_card.card_cvc, url_retour: item.router_data.request.get_complete_authorize_url()?, url_http_direct: item.router_data.request.get_complete_authorize_url()?, email_porteur: item.router_data.request.get_email()?, first_name: address.get_first_name()?.clone(), last_name: address.get_last_name()?.clone(), address1: address.get_line1()?.clone(), zip_code: address.get_zip()?.clone(), city: address.get_city()?.clone(), country_code: format!( "{:03}", common_enums::Country::from_alpha2(*address.get_country()?) .to_numeric() ), total_quantity: 1, })) } else { Ok(Self::Card(PaymentsRequest { date: format_time.clone(), transaction_type, paybox_request_number: get_paybox_request_number()?, amount: item.amount, description_reference: item .router_data .connector_request_reference_id .clone(), version: VERSION_PAYBOX.to_string(), currency, card_number: req_card.card_number, expiration_date, cvv: req_card.card_cvc, activity: PAY_ORIGIN_INTERNET.to_string(), site: auth_data.site, rank: auth_data.rang, key: auth_data.cle, three_ds_data: None, customer_id: match item.router_data.request.is_mandate_payment() { true => { let reference_id = item .router_data .connector_mandate_request_reference_id .clone() .ok_or_else(|| { errors::ConnectorError::MissingRequiredField { field_name: "connector_mandate_request_reference_id", } })?; Some(Secret::new(reference_id)) } false => None, }, })) } } PaymentMethodData::MandatePayment => { let mandate_data = item.router_data.request.get_card_mandate_info()?; Ok(Self::Mandate(MandatePaymentRequest::try_from(( item, mandate_data, ))?)) } _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } fn get_transaction_type( capture_method: Option<enums::CaptureMethod>, is_mandate_request: bool, ) -> Result<String, Error> { match (capture_method, is_mandate_request) { (Some(enums::CaptureMethod::Automatic), false) | (None, false) | (Some(enums::CaptureMethod::SequentialAutomatic), false) => { Ok(AUTH_AND_CAPTURE_REQUEST.to_string()) } (Some(enums::CaptureMethod::Automatic), true) | (None, true) => { Err(errors::ConnectorError::NotSupported { message: "Automatic Capture in CIT payments".to_string(), connector: "Paybox", })? } (Some(enums::CaptureMethod::Manual), false) => Ok(AUTH_REQUEST.to_string()), (Some(enums::CaptureMethod::Manual), true) | (Some(enums::CaptureMethod::SequentialAutomatic), true) => { Ok(MANDATE_REQUEST.to_string()) } _ => Err(errors::ConnectorError::CaptureMethodNotSupported)?, } } fn get_paybox_request_number() -> Result<String, Error> { let time_stamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .ok() .ok_or(errors::ConnectorError::RequestEncodingFailed)? .as_millis() .to_string(); // unix time (in milliseconds) has 13 digits.if we consider 8 digits(the number digits to make day deterministic) there is no collision in the paybox_request_number as it will reset the paybox_request_number for each day and paybox accepting maximum length is 10 so we gonna take 9 (13-9) let request_number = time_stamp .get(4..) .ok_or(errors::ConnectorError::ParsingFailed)?; Ok(request_number.to_string()) } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct PayboxAuthType { pub(super) site: Secret<String>, pub(super) rang: Secret<String>, pub(super) cle: Secret<String>, pub(super) merchant_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for PayboxAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } = auth_type { Ok(Self { site: api_key.to_owned(), rang: key1.to_owned(), cle: api_secret.to_owned(), merchant_id: key2.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum PayboxResponse { NonThreeDs(TransactionResponse), ThreeDs(Secret<String>), Error(String), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TransactionResponse { #[serde(rename = "NUMTRANS")] pub transaction_number: String, #[serde(rename = "NUMAPPEL")] pub paybox_order_id: String, #[serde(rename = "CODEREPONSE")] pub response_code: String, #[serde(rename = "COMMENTAIRE")] pub response_message: String, #[serde(rename = "PORTEUR")] pub carrier_id: Option<Secret<String>>, #[serde(rename = "REFABONNE")] pub customer_id: Option<Secret<String>>, } pub fn parse_url_encoded_to_struct<T: DeserializeOwned>( query_bytes: Bytes, ) -> CustomResult<T, errors::ConnectorError> { let (cow, _, _) = encoding_rs::ISO_8859_15.decode(&query_bytes); serde_qs::from_str::<T>(cow.as_ref()).change_context(errors::ConnectorError::ParsingFailed) } pub fn parse_paybox_response( query_bytes: Bytes, is_three_ds: bool, ) -> CustomResult<PayboxResponse, errors::ConnectorError> { let (cow, _, _) = encoding_rs::ISO_8859_15.decode(&query_bytes); let response_str = cow.as_ref().trim(); if utils::is_html_response(response_str) && is_three_ds { let response = response_str.to_string(); return Ok(if response.contains("Erreur 201") { PayboxResponse::Error(response) } else { PayboxResponse::ThreeDs(response.into()) }); } serde_qs::from_str::<TransactionResponse>(response_str) .map(PayboxResponse::NonThreeDs) .change_context(errors::ConnectorError::ParsingFailed) } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum PayboxStatus { #[serde(rename = "Remboursé")] Refunded, #[serde(rename = "Annulé")] Cancelled, #[serde(rename = "Autorisé")] Authorised, #[serde(rename = "Capturé")] Captured, #[serde(rename = "Refusé")] Rejected, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PayboxSyncResponse { #[serde(rename = "NUMTRANS")] pub transaction_number: String, #[serde(rename = "NUMAPPEL")] pub paybox_order_id: String, #[serde(rename = "CODEREPONSE")] pub response_code: String, #[serde(rename = "COMMENTAIRE")] pub response_message: String, #[serde(rename = "STATUS")] pub status: PayboxStatus, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PayboxCaptureResponse { #[serde(rename = "NUMTRANS")] pub transaction_number: String, #[serde(rename = "NUMAPPEL")] pub paybox_order_id: String, #[serde(rename = "CODEREPONSE")] pub response_code: String, #[serde(rename = "COMMENTAIRE")] pub response_message: String, } impl<F, T> TryFrom<ResponseRouterData<F, PayboxCaptureResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PayboxCaptureResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let response = item.response.clone(); let status = get_status_of_request(response.response_code.clone()); match status { true => Ok(Self { status: enums::AttemptStatus::Charged, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response.paybox_order_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!(PayboxMeta { connector_request_id: response.transaction_number.clone() })), network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), amount_captured: None, ..item.data }), false => Ok(Self { response: Err(ErrorResponse { code: response.response_code.clone(), message: response.response_message.clone(), reason: Some(response.response_message), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transaction_number), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } impl<F> TryFrom<ResponseRouterData<F, PayboxResponse, PaymentsAuthorizeData, PaymentsResponseData>> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PayboxResponse, PaymentsAuthorizeData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response.clone() { PayboxResponse::NonThreeDs(response) => { let status: bool = get_status_of_request(response.response_code.clone()); match status { true => Ok(Self { status: match ( item.data.request.is_auto_capture()?, item.data.request.is_cit_mandate_payment(), ) { (_, true) | (false, false) => enums::AttemptStatus::Authorized, (true, false) => enums::AttemptStatus::Charged, }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( response.paybox_order_id, ), redirection_data: Box::new(None), mandate_reference: Box::new(response.carrier_id.as_ref().map( |pm: &Secret<String>| MandateReference { connector_mandate_id: Some(pm.clone().expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: response.customer_id.map(|secret| secret.expose()), }, )), connector_metadata: Some(serde_json::json!(PayboxMeta { connector_request_id: response.transaction_number.clone() })), network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), false => Ok(Self { response: Err(ErrorResponse { code: response.response_code.clone(), message: response.response_message.clone(), reason: Some(response.response_message), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(response.transaction_number), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } PayboxResponse::ThreeDs(data) => Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(Some(RedirectForm::Html { html_data: data.peek().to_string(), })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), PayboxResponse::Error(_) => Ok(Self { response: Err(ErrorResponse { code: NO_ERROR_CODE.to_string(), message: NO_ERROR_MESSAGE.to_string(), reason: Some(NO_ERROR_MESSAGE.to_string()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } impl<F, T> TryFrom<ResponseRouterData<F, PayboxSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PayboxSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let response = item.response.clone(); let status = get_status_of_request(response.response_code.clone()); let connector_payment_status = item.response.status; match status { true => Ok(Self { status: enums::AttemptStatus::from(connector_payment_status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response.paybox_order_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!(PayboxMeta { connector_request_id: response.transaction_number.clone() })), network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), false => Ok(Self { response: Err(ErrorResponse { code: response.response_code.clone(), message: response.response_message.clone(), reason: Some(response.response_message), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transaction_number), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } impl From<PayboxStatus> for common_enums::RefundStatus { fn from(item: PayboxStatus) -> Self { match item { PayboxStatus::Refunded => Self::Success, PayboxStatus::Cancelled | PayboxStatus::Authorised | PayboxStatus::Captured | PayboxStatus::Rejected => Self::Failure, } } } impl From<PayboxStatus> for enums::AttemptStatus { fn from(item: PayboxStatus) -> Self { match item { PayboxStatus::Cancelled => Self::Voided, PayboxStatus::Authorised => Self::Authorized, PayboxStatus::Captured | PayboxStatus::Refunded => Self::Charged, PayboxStatus::Rejected => Self::Failure, } } } fn get_status_of_request(item: String) -> bool { item == *SUCCESS_CODE } impl<F> TryFrom<&PayboxRouterData<&types::RefundsRouterData<F>>> for PayboxRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PayboxRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let currency = enums::Currency::iso_4217(item.router_data.request.currency).to_string(); let format_time = common_utils::date_time::format_date( common_utils::date_time::now(), DateFormat::DDMMYYYYHHmmss, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let paybox_meta_data: PayboxMeta = utils::to_connector_meta(item.router_data.request.connector_metadata.clone())?; Ok(Self { date: format_time.clone(), transaction_type: REFUND_REQUEST.to_string(), paybox_request_number: get_paybox_request_number()?, version: VERSION_PAYBOX.to_string(), currency, site: auth_data.site, rank: auth_data.rang, key: auth_data.cle, transaction_number: paybox_meta_data.connector_request_id, paybox_order_id: item.router_data.request.connector_transaction_id.clone(), amount: item.amount, }) } } impl TryFrom<RefundsResponseRouterData<RSync, PayboxSyncResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, PayboxSyncResponse>, ) -> Result<Self, Self::Error> { let status = get_status_of_request(item.response.response_code.clone()); match status { true => Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction_number, refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }), false => Ok(Self { response: Err(ErrorResponse { code: item.response.response_code.clone(), message: item.response.response_message.clone(), reason: Some(item.response.response_message), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transaction_number), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } impl TryFrom<RefundsResponseRouterData<Execute, TransactionResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, TransactionResponse>, ) -> Result<Self, Self::Error> { let status = get_status_of_request(item.response.response_code.clone()); match status { true => Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction_number, refund_status: common_enums::RefundStatus::Pending, }), ..item.data }), false => Ok(Self { response: Err(ErrorResponse { code: item.response.response_code.clone(), message: item.response.response_message.clone(), reason: Some(item.response.response_message), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transaction_number), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct PayboxErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, } impl<F> TryFrom<ResponseRouterData<F, TransactionResponse, CompleteAuthorizeData, PaymentsResponseData>> for RouterData<F, CompleteAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, TransactionResponse, CompleteAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response = item.response.clone(); let status = get_status_of_request(response.response_code.clone()); match status { true => Ok(Self { status: match ( item.data.request.is_auto_capture()?, item.data.request.is_cit_mandate_payment(), ) { (_, true) | (false, false) => enums::AttemptStatus::Authorized, (true, false) => enums::AttemptStatus::Charged, }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response.paybox_order_id), redirection_data: Box::new(None), mandate_reference: Box::new(response.carrier_id.as_ref().map(|pm| { MandateReference { connector_mandate_id: Some(pm.clone().expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: response .customer_id .map(|secret| secret.expose()), } })), connector_metadata: Some(serde_json::json!(PayboxMeta { connector_request_id: response.transaction_number.clone() })), network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), false => Ok(Self { response: Err(ErrorResponse { code: response.response_code.clone(), message: response.response_message.clone(), reason: Some(response.response_message), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(response.transaction_number), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } #[derive(Debug, Serialize, Deserialize)] pub struct RedirectionAuthResponse { #[serde(rename = "ID3D")] three_ds_data: Option<Secret<String>>, } impl TryFrom<&PayboxRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for PaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PayboxRouterData<&types::PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let redirect_response = item.router_data.request.redirect_response.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "redirect_response", }, )?; let redirect_payload: RedirectionAuthResponse = redirect_response .payload .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.payload", })? .peek() .clone() .parse_value("RedirectionAuthResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; match item.router_data.request.payment_method_data.clone() { Some(PaymentMethodData::Card(req_card)) => { let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let transaction_type = get_transaction_type( item.router_data.request.capture_method, item.router_data.request.is_mandate_payment(), )?; let currency = enums::Currency::iso_4217(item.router_data.request.currency).to_string(); let expiration_date = req_card.get_card_expiry_month_year_2_digit_with_delimiter("".to_owned())?; let format_time = common_utils::date_time::format_date( common_utils::date_time::now(), DateFormat::DDMMYYYYHHmmss, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Self { date: format_time.clone(), transaction_type, paybox_request_number: get_paybox_request_number()?, amount: item.router_data.request.minor_amount, description_reference: item.router_data.connector_request_reference_id.clone(), version: VERSION_PAYBOX.to_string(), currency, card_number: req_card.card_number, expiration_date, cvv: req_card.card_cvc, activity: PAY_ORIGIN_INTERNET.to_string(), site: auth_data.site, rank: auth_data.rang, key: auth_data.cle, three_ds_data: redirect_payload.three_ds_data.map_or_else( || Some(Secret::new(THREE_DS_FAIL_CODE.to_string())), |data| Some(data.clone()), ), customer_id: match item.router_data.request.is_mandate_payment() { true => { let reference_id = item .router_data .connector_mandate_request_reference_id .clone() .ok_or_else(|| errors::ConnectorError::MissingRequiredField { field_name: "connector_mandate_request_reference_id", })?; Some(Secret::new(reference_id)) } false => None, }, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } #[derive(Debug, Serialize)] pub struct MandatePaymentRequest { #[serde(rename = "DATEQ")] pub date: String, #[serde(rename = "TYPE")] pub transaction_type: String, #[serde(rename = "NUMQUESTION")] pub paybox_request_number: String, #[serde(rename = "MONTANT")] pub amount: MinorUnit, #[serde(rename = "REFERENCE")] pub description_reference: String, #[serde(rename = "VERSION")] pub version: String, #[serde(rename = "DEVISE")] pub currency: String, #[serde(rename = "ACTIVITE")] pub activity: String, #[serde(rename = "SITE")] pub site: Secret<String>, #[serde(rename = "RANG")] pub rank: Secret<String>, #[serde(rename = "CLE")] pub key: Secret<String>, #[serde(rename = "DATEVAL")] pub cc_exp_date: Secret<String>, #[serde(rename = "REFABONNE")] pub customer_id: Secret<String>, #[serde(rename = "PORTEUR")] pub carrier_id: Secret<String>, } impl TryFrom<( &PayboxRouterData<&types::PaymentsAuthorizeRouterData>, CardMandateInfo, )> for MandatePaymentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (item, card_mandate_info): ( &PayboxRouterData<&types::PaymentsAuthorizeRouterData>, CardMandateInfo, ), ) -> Result<Self, Self::Error> { let auth_data: PayboxAuthType = PayboxAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let transaction_type = match item.router_data.request.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => { Ok(MANDATE_AUTH_AND_CAPTURE_ONLY.to_string()) } Some(enums::CaptureMethod::Manual) => Ok(MANDATE_AUTH_ONLY.to_string()), _ => Err(errors::ConnectorError::CaptureMethodNotSupported), }?; let currency = enums::Currency::iso_4217(item.router_data.request.currency).to_string(); let format_time = common_utils::date_time::format_date( common_utils::date_time::now(), DateFormat::DDMMYYYYHHmmss, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Self { date: format_time.clone(), transaction_type, paybox_request_number: get_paybox_request_number()?, amount: item.router_data.request.minor_amount, description_reference: item.router_data.connector_request_reference_id.clone(), version: VERSION_PAYBOX.to_string(), currency, activity: RECURRING_ORIGIN.to_string(), site: auth_data.site, rank: auth_data.rang, key: auth_data.cle, customer_id: Secret::new( item.router_data .request .get_connector_mandate_request_reference_id()?, ), carrier_id: Secret::new(item.router_data.request.get_connector_mandate_id()?), cc_exp_date: get_card_expiry_month_year_2_digit( card_mandate_info.card_exp_month.clone(), card_mandate_info.card_exp_year.clone(), )?, }) } } fn get_card_expiry_month_year_2_digit( card_exp_month: Secret<String>, card_exp_year: Secret<String>, ) -> Result<Secret<String>, errors::ConnectorError> { Ok(Secret::new(format!( "{}{}", card_exp_month.peek(), card_exp_year .peek() .get(card_exp_year.peek().len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? ))) }
crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs
hyperswitch_connectors::src::connectors::paybox::transformers
9,410
true
// File: crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs // Module: hyperswitch_connectors::src::connectors::flexiti::transformers use common_enums::enums; use common_utils::{pii::Email, request::Method, types::FloatMajorUnit}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{self, RefundsResponseRouterData, ResponseRouterData}, utils::{ self, AddressDetailsData, BrowserInformationData, PaymentsAuthorizeRequestData, RouterData as _, }, }; pub struct FlexitiRouterData<T> { pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for FlexitiRouterData<T> { fn from((amount, item): (FloatMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Serialize)] pub struct FlexitiPaymentsRequest { merchant_order_id: Option<String>, lang: String, flow: FlexitiFlow, amount_requested: FloatMajorUnit, email: Option<Email>, fname: Secret<String>, billing_information: BillingInformation, shipping_information: ShippingInformation, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum FlexitiFlow { #[serde(rename = "apply/buy")] ApplyAndBuy, Apply, Buy, } #[derive(Debug, Serialize)] pub struct BillingInformation { first_name: Secret<String>, last_name: Secret<String>, address_1: Secret<String>, address_2: Secret<String>, city: Secret<String>, postal_code: Secret<String>, province: Secret<String>, } #[derive(Debug, Serialize)] pub struct ShippingInformation { first_name: Secret<String>, last_name: Secret<String>, address_1: Secret<String>, address_2: Secret<String>, city: Secret<String>, postal_code: Secret<String>, province: Secret<String>, } impl TryFrom<&FlexitiRouterData<&PaymentsAuthorizeRouterData>> for FlexitiPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &FlexitiRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { hyperswitch_domain_models::payment_method_data::PayLaterData::FlexitiRedirect { } => { let shipping_address = item.router_data.get_shipping_address()?; let shipping_information = ShippingInformation { first_name: shipping_address.get_first_name()?.to_owned(), last_name: shipping_address.get_last_name()?.to_owned(), address_1: shipping_address.get_line1()?.to_owned(), address_2: shipping_address.get_line2()?.to_owned(), city: shipping_address.get_city()?.to_owned().into(), postal_code: shipping_address.get_zip()?.to_owned(), province: shipping_address.to_state_code()?, }; let billing_information = BillingInformation { first_name: item.router_data.get_billing_first_name()?, last_name: item.router_data.get_billing_last_name()?, address_1: item.router_data.get_billing_line1()?, address_2: item.router_data.get_billing_line2()?, city: item.router_data.get_billing_city()?.into(), postal_code: item.router_data.get_billing_zip()?, province: item.router_data.get_billing_state_code()?, }; Ok(Self { merchant_order_id: item.router_data.request.merchant_order_reference_id.to_owned(), lang: item.router_data.request.get_browser_info()?.get_language()?, flow: FlexitiFlow::ApplyAndBuy, amount_requested: item.amount.to_owned(), email: item.router_data.get_optional_billing_email(), fname: item.router_data.get_billing_first_name()?, billing_information, shipping_information, }) }, hyperswitch_domain_models::payment_method_data::PayLaterData::KlarnaRedirect { } | hyperswitch_domain_models::payment_method_data::PayLaterData::KlarnaSdk { .. } | hyperswitch_domain_models::payment_method_data::PayLaterData::AffirmRedirect { } | hyperswitch_domain_models::payment_method_data::PayLaterData::BreadpayRedirect { } | hyperswitch_domain_models::payment_method_data::PayLaterData::AfterpayClearpayRedirect { } | hyperswitch_domain_models::payment_method_data::PayLaterData::PayBrightRedirect { } | hyperswitch_domain_models::payment_method_data::PayLaterData::WalleyRedirect { } | hyperswitch_domain_models::payment_method_data::PayLaterData::AlmaRedirect { } | hyperswitch_domain_models::payment_method_data::PayLaterData::AtomeRedirect { } => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("flexiti"), )) }?, } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } #[derive(Debug, Serialize)] pub struct FlexitiAccessTokenRequest { client_id: Secret<String>, client_secret: Secret<String>, grant_type: FlexitiGranttype, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum FlexitiGranttype { Password, RefreshToken, ClientCredentials, } impl TryFrom<&types::RefreshTokenRouterData> for FlexitiAccessTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> { let auth_details = FlexitiAuthType::try_from(&item.connector_auth_type)?; Ok(Self { client_id: auth_details.client_id, client_secret: auth_details.client_secret, grant_type: FlexitiGranttype::ClientCredentials, }) } } impl<F, T> TryFrom<ResponseRouterData<F, FlexitiAccessTokenResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, FlexitiAccessTokenResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(AccessToken { token: item.response.access_token, expires: item.response.expires_in, }), ..item.data }) } } // Auth Struct pub struct FlexitiAuthType { pub(super) client_id: Secret<String>, pub(super) client_secret: Secret<String>, } impl TryFrom<&ConnectorAuthType> for FlexitiAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { client_id: api_key.to_owned(), client_secret: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Serialize, Deserialize)] pub struct FlexitiAccessTokenResponse { access_token: Secret<String>, expires_in: i64, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FlexitiPaymentsResponse { redirection_url: url::Url, online_order_id: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FlexitiSyncResponse { transaction_id: String, purchase: FlexitiPurchase, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FlexitiPurchase { status: FlexitiPurchaseStatus, } // Since this is an alpha integration, we don't have access to all the status mapping. This needs to be updated. #[derive(Debug, Clone, Serialize, Deserialize)] pub enum FlexitiPurchaseStatus { Success, Failed, } // Since this is an alpha integration, we don't have access to all the status mapping. This needs to be updated. impl From<FlexitiPurchaseStatus> for common_enums::AttemptStatus { fn from(item: FlexitiPurchaseStatus) -> Self { match item { FlexitiPurchaseStatus::Success => Self::Authorized, FlexitiPurchaseStatus::Failed => Self::Failure, } } } impl<F, T> TryFrom<ResponseRouterData<F, FlexitiSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, FlexitiSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.purchase.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.to_owned(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl<F, T> TryFrom<ResponseRouterData<F, FlexitiPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, FlexitiPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.online_order_id.to_owned(), ), redirection_data: Box::new(Some(RedirectForm::from(( item.response.redirection_url, Method::Get, )))), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } //TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct FlexitiRefundRequest { pub amount: FloatMajorUnit, } impl<F> TryFrom<&FlexitiRouterData<&RefundsRouterData<F>>> for FlexitiRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &FlexitiRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize)] pub struct FlexitiErrorResponse { pub message: String, pub error: String, }
crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs
hyperswitch_connectors::src::connectors::flexiti::transformers
2,924
true
// File: crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs // Module: hyperswitch_connectors::src::connectors::mifinity::transformers use common_enums::enums; use common_utils::{ pii::{self, Email}, types::StringMajorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, RouterData}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm}, types, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use time::Date; use crate::{ types::ResponseRouterData, utils::{self, PaymentsAuthorizeRequestData, PhoneDetailsData, RouterData as _}, }; pub struct MifinityRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for MifinityRouterData<T> { fn from((amount, router_data): (StringMajorUnit, T)) -> Self { Self { amount, router_data, } } } pub mod auth_headers { pub const API_VERSION: &str = "api-version"; } #[derive(Debug, Default, Serialize, Deserialize)] pub struct MifinityConnectorMetadataObject { pub brand_id: Secret<String>, pub destination_account_number: Secret<String>, } impl TryFrom<&Option<pii::SecretSerdeValue>> for MifinityConnectorMetadataObject { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "merchant_connector_account.metadata", })?; Ok(metadata) } } #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MifinityPaymentsRequest { money: Money, client: MifinityClient, address: MifinityAddress, validation_key: String, client_reference: common_utils::id_type::CustomerId, trace_id: String, description: String, destination_account_number: Secret<String>, brand_id: Secret<String>, return_url: String, #[serde(skip_serializing_if = "Option::is_none")] language_preference: Option<String>, } #[derive(Debug, Serialize, PartialEq)] pub struct Money { amount: StringMajorUnit, currency: String, } #[derive(Debug, Clone, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MifinityClient { first_name: Secret<String>, last_name: Secret<String>, phone: Secret<String>, dialing_code: String, nationality: api_models::enums::CountryAlpha2, email_address: Email, dob: Secret<Date>, } #[derive(Default, Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MifinityAddress { address_line1: Secret<String>, country_code: api_models::enums::CountryAlpha2, city: String, } impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for MifinityPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &MifinityRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let metadata: MifinityConnectorMetadataObject = utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "merchant_connector_account.metadata", })?; match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::Mifinity(data) => { let money = Money { amount: item.amount.clone(), currency: item.router_data.request.currency.to_string(), }; let phone_details = item.router_data.get_billing_phone()?; let client = MifinityClient { first_name: item.router_data.get_billing_first_name()?, last_name: item.router_data.get_billing_last_name()?, phone: phone_details.get_number()?, dialing_code: phone_details.get_country_code()?, nationality: item.router_data.get_billing_country()?, email_address: item.router_data.get_billing_email()?, dob: data.date_of_birth.clone(), }; let address = MifinityAddress { address_line1: item.router_data.get_billing_line1()?, country_code: item.router_data.get_billing_country()?, city: item.router_data.get_billing_city()?, }; let validation_key = format!( "payment_validation_key_{}_{}", item.router_data.merchant_id.get_string_repr(), item.router_data.connector_request_reference_id.clone() ); let client_reference = item.router_data.customer_id.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "client_reference", }, )?; let destination_account_number = metadata.destination_account_number; let trace_id = item.router_data.connector_request_reference_id.clone(); let brand_id = metadata.brand_id; let language_preference = data.language_preference; Ok(Self { money, client, address, validation_key, client_reference, trace_id: trace_id.clone(), description: trace_id.clone(), //Connector recommend to use the traceId for a better experience in the BackOffice application later. destination_account_number, brand_id, return_url: item.router_data.request.get_router_return_url()?, language_preference, }) } WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePay(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePay(_) | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Mifinity"), ) .into()), }, PaymentMethodData::Card(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Mifinity"), ) .into()) } } } } // Auth Struct pub struct MifinityAuthType { pub(super) key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for MifinityAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MifinityPaymentsResponse { payload: Vec<MifinityPayload>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MifinityPayload { trace_id: String, initialization_token: String, } impl<F, T> TryFrom<ResponseRouterData<F, MifinityPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, MifinityPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let payload = item.response.payload.first(); match payload { Some(payload) => { let trace_id = payload.trace_id.clone(); let initialization_token = payload.initialization_token.clone(); Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(trace_id.clone()), redirection_data: Box::new(Some(RedirectForm::Mifinity { initialization_token, })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(trace_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } None => Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MifinityPsyncResponse { payload: Vec<MifinityPsyncPayload>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MifinityPsyncPayload { status: MifinityPaymentStatus, payment_response: Option<PaymentResponse>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentResponse { trace_id: Option<String>, client_reference: Option<String>, validation_key: Option<String>, transaction_reference: String, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum MifinityPaymentStatus { Successful, Pending, Failed, NotCompleted, } impl<F, T> TryFrom<ResponseRouterData<F, MifinityPsyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, MifinityPsyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let payload = item.response.payload.first(); match payload { Some(payload) => { let status = payload.to_owned().status.clone(); let payment_response = payload.payment_response.clone(); match payment_response { Some(payment_response) => { let transaction_reference = payment_response.transaction_reference.clone(); Ok(Self { status: enums::AttemptStatus::from(status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( transaction_reference, ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } None => Ok(Self { status: enums::AttemptStatus::from(status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), } } None => Ok(Self { status: item.data.status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), } } } impl From<MifinityPaymentStatus> for enums::AttemptStatus { fn from(item: MifinityPaymentStatus) -> Self { match item { MifinityPaymentStatus::Successful => Self::Charged, MifinityPaymentStatus::Failed => Self::Failure, MifinityPaymentStatus::NotCompleted => Self::AuthenticationPending, MifinityPaymentStatus::Pending => Self::Pending, } } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct MifinityErrorResponse { pub errors: Vec<MifinityErrorList>, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MifinityErrorList { #[serde(rename = "type")] pub error_type: String, pub error_code: String, pub message: String, pub field: Option<String>, }
crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs
hyperswitch_connectors::src::connectors::mifinity::transformers
3,224
true
// File: crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs // Module: hyperswitch_connectors::src::connectors::stripebilling::transformers #[cfg(feature = "v2")] use std::str::FromStr; use common_enums::enums; #[cfg(all(feature = "revenue_recovery", feature = "v2"))] use common_utils::id_type; use common_utils::{errors::CustomResult, ext_traits::ByteSliceExt, types::StringMinorUnit}; use error_stack::ResultExt; #[cfg(all(feature = "revenue_recovery", feature = "v2"))] use hyperswitch_domain_models::revenue_recovery; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::{ router_flow_types::revenue_recovery as recovery_router_flows, router_request_types::revenue_recovery as recovery_request_types, router_response_types::revenue_recovery as recovery_response_types, types as recovery_router_data_types, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{convert_uppercase, PaymentsAuthorizeRequestData}, }; pub mod auth_headers { pub const STRIPE_API_VERSION: &str = "stripe-version"; pub const STRIPE_VERSION: &str = "2022-11-15"; } //TODO: Fill the struct with respective fields pub struct StripebillingRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for StripebillingRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { //Todo : use utils to convert the amount to the type of amount that a connector accepts Self { amount, router_data: item, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] pub struct StripebillingPaymentsRequest { amount: StringMinorUnit, card: StripebillingCard, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct StripebillingCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } impl TryFrom<&StripebillingRouterData<&PaymentsAuthorizeRouterData>> for StripebillingPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &StripebillingRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let card = StripebillingCard { number: req_card.card_number, expiry_month: req_card.card_exp_month, expiry_year: req_card.card_exp_year, cvc: req_card.card_cvc, complete: item.router_data.request.is_auto_capture()?, }; Ok(Self { amount: item.amount.clone(), card, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } //TODO: Fill the struct with respective fields // Auth Struct pub struct StripebillingAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for StripebillingAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse //TODO: Append the remaining status flags #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Copy)] #[serde(rename_all = "lowercase")] pub enum StripebillingPaymentStatus { Succeeded, Failed, #[default] Processing, } impl From<StripebillingPaymentStatus> for common_enums::AttemptStatus { fn from(item: StripebillingPaymentStatus) -> Self { match item { StripebillingPaymentStatus::Succeeded => Self::Charged, StripebillingPaymentStatus::Failed => Self::Failure, StripebillingPaymentStatus::Processing => Self::Authorizing, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct StripebillingPaymentsResponse { status: StripebillingPaymentStatus, id: String, } impl<F, T> TryFrom<ResponseRouterData<F, StripebillingPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, StripebillingPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } //TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct StripebillingRefundRequest { pub amount: StringMinorUnit, } impl<F> TryFrom<&StripebillingRouterData<&RefundsRouterData<F>>> for StripebillingRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &StripebillingRouterData<&RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone, Copy)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct StripebillingErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct StripebillingWebhookBody { #[serde(rename = "type")] pub event_type: StripebillingEventType, pub data: StripebillingWebhookData, } #[derive(Debug, Serialize, Deserialize)] pub struct StripebillingInvoiceBody { #[serde(rename = "type")] pub event_type: StripebillingEventType, pub data: StripebillingInvoiceData, } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum StripebillingEventType { #[serde(rename = "invoice.paid")] PaymentSucceeded, #[serde(rename = "invoice.payment_failed")] PaymentFailed, #[serde(rename = "invoice.voided")] InvoiceDeleted, } #[derive(Serialize, Deserialize, Debug)] pub struct StripebillingWebhookData { pub object: StripebillingWebhookObject, } #[derive(Serialize, Deserialize, Debug)] pub struct StripebillingInvoiceData { pub object: StripebillingWebhookObject, } #[derive(Serialize, Deserialize, Debug)] pub struct StripebillingWebhookObject { #[serde(rename = "id")] pub invoice_id: String, #[serde(deserialize_with = "convert_uppercase")] pub currency: enums::Currency, pub customer: String, #[serde(rename = "amount_remaining")] pub amount: common_utils::types::MinorUnit, pub charge: String, pub payment_intent: String, pub customer_address: Option<StripebillingInvoiceBillingAddress>, pub attempt_count: u16, pub lines: StripebillingWebhookLinesObject, } #[derive(Serialize, Deserialize, Debug)] pub struct StripebillingWebhookLinesObject { pub data: Vec<StripebillingWebhookLinesData>, } #[derive(Serialize, Deserialize, Debug)] pub struct StripebillingWebhookLinesData { pub period: StripebillingWebhookLineDataPeriod, } #[derive(Serialize, Deserialize, Debug)] pub struct StripebillingWebhookLineDataPeriod { #[serde(with = "common_utils::custom_serde::timestamp")] pub end: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::timestamp")] pub start: PrimitiveDateTime, } #[derive(Serialize, Deserialize, Debug)] pub struct StripebillingInvoiceBillingAddress { pub country: Option<enums::CountryAlpha2>, pub city: Option<String>, pub address_line1: Option<Secret<String>>, pub address_line2: Option<Secret<String>>, pub zip_code: Option<Secret<String>>, pub state: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize)] pub struct StripebillingInvoiceObject { #[serde(rename = "id")] pub invoice_id: String, #[serde(deserialize_with = "convert_uppercase")] pub currency: enums::Currency, #[serde(rename = "amount_remaining")] pub amount: common_utils::types::MinorUnit, pub attempt_count: Option<u16>, } impl StripebillingWebhookBody { pub fn get_webhook_object_from_body(body: &[u8]) -> CustomResult<Self, errors::ConnectorError> { let webhook_body: Self = body .parse_struct::<Self>("StripebillingWebhookBody") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(webhook_body) } } impl StripebillingInvoiceBody { pub fn get_invoice_webhook_data_from_body( body: &[u8], ) -> CustomResult<Self, errors::ConnectorError> { let webhook_body = body .parse_struct::<Self>("StripebillingInvoiceBody") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(webhook_body) } } impl From<StripebillingInvoiceBillingAddress> for api_models::payments::Address { fn from(item: StripebillingInvoiceBillingAddress) -> Self { Self { address: Some(api_models::payments::AddressDetails::from(item)), phone: None, email: None, } } } impl From<StripebillingInvoiceBillingAddress> for api_models::payments::AddressDetails { fn from(item: StripebillingInvoiceBillingAddress) -> Self { Self { city: item.city, state: item.state, country: item.country, zip: item.zip_code, line1: item.address_line1, line2: item.address_line2, line3: None, first_name: None, last_name: None, origin_zip: None, } } } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] impl TryFrom<StripebillingInvoiceBody> for revenue_recovery::RevenueRecoveryInvoiceData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: StripebillingInvoiceBody) -> Result<Self, Self::Error> { let merchant_reference_id = id_type::PaymentReferenceId::from_str(&item.data.object.invoice_id) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let next_billing_at = item .data .object .lines .data .first() .map(|linedata| linedata.period.end); let billing_started_at = item .data .object .lines .data .first() .map(|linedata| linedata.period.start); Ok(Self { amount: item.data.object.amount, currency: item.data.object.currency, merchant_reference_id, billing_address: item .data .object .customer_address .map(api_models::payments::Address::from), retry_count: Some(item.data.object.attempt_count), next_billing_at, billing_started_at, metadata: None, // TODO! This field should be handled for billing connnector integrations enable_partial_authorization: None, }) } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct StripebillingRecoveryDetailsData { #[serde(rename = "id")] pub charge_id: String, pub status: StripebillingChargeStatus, pub amount: common_utils::types::MinorUnit, #[serde(deserialize_with = "convert_uppercase")] pub currency: enums::Currency, pub customer: String, pub payment_method: String, pub failure_code: Option<String>, pub failure_message: Option<String>, #[serde(with = "common_utils::custom_serde::timestamp")] pub created: PrimitiveDateTime, pub payment_method_details: StripePaymentMethodDetails, #[serde(rename = "invoice")] pub invoice_id: String, pub payment_intent: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct StripePaymentMethodDetails { #[serde(rename = "type")] pub type_of_payment_method: StripebillingPaymentMethod, #[serde(rename = "card")] pub card_details: StripeBillingCardDetails, } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum StripebillingPaymentMethod { Card, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct StripeBillingCardDetails { pub network: StripebillingCardNetwork, pub funding: StripebillingFundingTypes, } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum StripebillingCardNetwork { Visa, Mastercard, AmericanExpress, JCB, DinersClub, Discover, CartesBancaires, UnionPay, Interac, RuPay, Maestro, Star, Pulse, Accel, Nyce, } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] #[serde(rename = "snake_case")] pub enum StripebillingFundingTypes { #[serde(rename = "credit")] Credit, #[serde(rename = "debit")] Debit, } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum StripebillingChargeStatus { Succeeded, Failed, } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] // This is the default hard coded mca Id to find the stripe account associated with the stripe biliing // Context : Since we dont have the concept of connector_reference_id in stripebilling because payments always go through stripe. // While creating stripebilling we will hard code the stripe account id to string "stripebilling" in mca featrue metadata. So we have to pass the same as account_reference_id here in response. const MCA_ID_IDENTIFIER_FOR_STRIPE_IN_STRIPEBILLING_MCA_FEAATURE_METADATA: &str = "stripebilling"; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl TryFrom< ResponseRouterData< recovery_router_flows::BillingConnectorPaymentsSync, StripebillingRecoveryDetailsData, recovery_request_types::BillingConnectorPaymentsSyncRequest, recovery_response_types::BillingConnectorPaymentsSyncResponse, >, > for recovery_router_data_types::BillingConnectorPaymentsSyncRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< recovery_router_flows::BillingConnectorPaymentsSync, StripebillingRecoveryDetailsData, recovery_request_types::BillingConnectorPaymentsSyncRequest, recovery_response_types::BillingConnectorPaymentsSyncResponse, >, ) -> Result<Self, Self::Error> { let charge_details = item.response; let merchant_reference_id = id_type::PaymentReferenceId::from_str(charge_details.invoice_id.as_str()) .change_context(errors::ConnectorError::MissingRequiredField { field_name: "invoice_id", })?; let connector_transaction_id = Some(common_utils::types::ConnectorTransactionId::from( charge_details.payment_intent, )); Ok(Self { response: Ok( recovery_response_types::BillingConnectorPaymentsSyncResponse { status: charge_details.status.into(), amount: charge_details.amount, currency: charge_details.currency, merchant_reference_id, connector_account_reference_id: MCA_ID_IDENTIFIER_FOR_STRIPE_IN_STRIPEBILLING_MCA_FEAATURE_METADATA .to_string(), connector_transaction_id, error_code: charge_details.failure_code, error_message: charge_details.failure_message, processor_payment_method_token: charge_details.payment_method, connector_customer_id: charge_details.customer, transaction_created_at: Some(charge_details.created), payment_method_sub_type: common_enums::PaymentMethodType::from( charge_details.payment_method_details.card_details.funding, ), payment_method_type: common_enums::PaymentMethod::from( charge_details.payment_method_details.type_of_payment_method, ), // Todo: Fetch Card issuer details. Generally in the other billing connector we are getting card_issuer using the card bin info. But stripe dosent provide any such details. We should find a way for stripe billing case charge_id: Some(charge_details.charge_id.clone()), // Need to populate these card info field card_info: api_models::payments::AdditionalCardInfo { card_network: Some(common_enums::CardNetwork::from( charge_details.payment_method_details.card_details.network, )), card_isin: None, card_issuer: None, card_type: None, card_issuing_country: None, bank_code: None, last4: None, card_extended_bin: None, card_exp_month: None, card_exp_year: None, card_holder_name: None, payment_checks: None, authentication_data: None, is_regulated: None, signature_network: None, }, }, ), ..item.data }) } } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl From<StripebillingChargeStatus> for enums::AttemptStatus { fn from(status: StripebillingChargeStatus) -> Self { match status { StripebillingChargeStatus::Succeeded => Self::Charged, StripebillingChargeStatus::Failed => Self::Failure, } } } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl From<StripebillingFundingTypes> for common_enums::PaymentMethodType { fn from(funding: StripebillingFundingTypes) -> Self { match funding { StripebillingFundingTypes::Credit => Self::Credit, StripebillingFundingTypes::Debit => Self::Debit, } } } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl From<StripebillingPaymentMethod> for common_enums::PaymentMethod { fn from(method: StripebillingPaymentMethod) -> Self { match method { StripebillingPaymentMethod::Card => Self::Card, } } } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct StripebillingRecordBackResponse { pub id: String, } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl TryFrom< ResponseRouterData< recovery_router_flows::InvoiceRecordBack, StripebillingRecordBackResponse, recovery_request_types::InvoiceRecordBackRequest, recovery_response_types::InvoiceRecordBackResponse, >, > for recovery_router_data_types::InvoiceRecordBackRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< recovery_router_flows::InvoiceRecordBack, StripebillingRecordBackResponse, recovery_request_types::InvoiceRecordBackRequest, recovery_response_types::InvoiceRecordBackResponse, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(recovery_response_types::InvoiceRecordBackResponse { merchant_reference_id: id_type::PaymentReferenceId::from_str( item.response.id.as_str(), ) .change_context(errors::ConnectorError::MissingRequiredField { field_name: "invoice_id in the response", })?, }), ..item.data }) } } impl From<StripebillingCardNetwork> for enums::CardNetwork { fn from(item: StripebillingCardNetwork) -> Self { match item { StripebillingCardNetwork::Visa => Self::Visa, StripebillingCardNetwork::Mastercard => Self::Mastercard, StripebillingCardNetwork::AmericanExpress => Self::AmericanExpress, StripebillingCardNetwork::JCB => Self::JCB, StripebillingCardNetwork::DinersClub => Self::DinersClub, StripebillingCardNetwork::Discover => Self::Discover, StripebillingCardNetwork::CartesBancaires => Self::CartesBancaires, StripebillingCardNetwork::UnionPay => Self::UnionPay, StripebillingCardNetwork::Interac => Self::Interac, StripebillingCardNetwork::RuPay => Self::RuPay, StripebillingCardNetwork::Maestro => Self::Maestro, StripebillingCardNetwork::Star => Self::Star, StripebillingCardNetwork::Pulse => Self::Pulse, StripebillingCardNetwork::Accel => Self::Accel, StripebillingCardNetwork::Nyce => Self::Nyce, } } }
crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs
hyperswitch_connectors::src::connectors::stripebilling::transformers
5,198
true
// File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs // Module: hyperswitch_connectors::src::connectors::paysafe::transformers use std::collections::HashMap; use base64::Engine; use cards::CardNumber; use common_enums::{enums, Currency}; use common_types::payments::{ApplePayPaymentData, ApplePayPredecryptData}; use common_utils::{ ext_traits::ValueExt, id_type, pii::{Email, IpAddress, SecretSerdeValue}, request::Method, types::MinorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{ ApplePayWalletData, BankRedirectData, GiftCardData, PaymentMethodData, WalletData, }, router_data::{ConnectorAuthType, PaymentMethodToken, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsPreProcessingData, PaymentsSyncData, ResponseId, }, router_response_types::{ ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types::{ ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{consts, errors}; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, missing_field_err, to_connector_meta, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, RouterData as RouterDataUtils, }, }; const MAX_ID_LENGTH: usize = 36; pub struct PaysafeRouterData<T> { pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(MinorUnit, T)> for PaysafeRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Default, Serialize, Deserialize)] pub struct PaysafeConnectorMetadataObject { pub account_id: PaysafePaymentMethodDetails, } #[derive(Debug, Default, Serialize, Deserialize)] pub struct PaysafePaymentMethodDetails { pub apple_pay: Option<HashMap<Currency, ApplePayAccountDetails>>, pub card: Option<HashMap<Currency, CardAccountId>>, pub interac: Option<HashMap<Currency, RedirectAccountId>>, pub pay_safe_card: Option<HashMap<Currency, RedirectAccountId>>, pub skrill: Option<HashMap<Currency, RedirectAccountId>>, } #[derive(Debug, Default, Serialize, Deserialize)] pub struct CardAccountId { no_three_ds: Option<Secret<String>>, three_ds: Option<Secret<String>>, } #[derive(Debug, Default, Serialize, Deserialize)] pub struct ApplePayAccountDetails { encrypt: Option<Secret<String>>, decrypt: Option<Secret<String>>, } #[derive(Debug, Default, Serialize, Deserialize)] pub struct RedirectAccountId { three_ds: Option<Secret<String>>, } impl TryFrom<&Option<SecretSerdeValue>> for PaysafeConnectorMetadataObject { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(meta_data: &Option<SecretSerdeValue>) -> Result<Self, Self::Error> { let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "merchant_connector_account.metadata", })?; Ok(metadata) } } impl TryFrom<&ConnectorCustomerRouterData> for PaysafeCustomerDetails { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(customer_data: &ConnectorCustomerRouterData) -> Result<Self, Self::Error> { let merchant_customer_id = match customer_data.customer_id.as_ref() { Some(customer_id) if customer_id.get_string_repr().len() <= MAX_ID_LENGTH => { Ok(customer_id.get_string_repr().to_string()) } Some(customer_id) => Err(errors::ConnectorError::MaxFieldLengthViolated { connector: "Paysafe".to_string(), field_name: "customer_id".to_string(), max_length: MAX_ID_LENGTH, received_length: customer_id.get_string_repr().len(), }), None => Err(errors::ConnectorError::MissingRequiredField { field_name: "customer_id", }), }?; Ok(Self { merchant_customer_id, first_name: customer_data.get_optional_billing_first_name(), last_name: customer_data.get_optional_billing_last_name(), email: customer_data.get_optional_billing_email(), phone: customer_data.get_optional_billing_phone_number(), }) } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeCustomerDetails { pub merchant_customer_id: String, pub first_name: Option<Secret<String>>, pub last_name: Option<Secret<String>>, pub email: Option<Email>, pub phone: Option<Secret<String>>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeDs { pub merchant_url: String, pub device_channel: DeviceChannel, pub message_category: ThreeDsMessageCategory, pub authentication_purpose: ThreeDsAuthenticationPurpose, pub requestor_challenge_preference: ThreeDsChallengePreference, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum DeviceChannel { Browser, Sdk, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum ThreeDsMessageCategory { Payment, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum ThreeDsAuthenticationPurpose { PaymentTransaction, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum ThreeDsChallengePreference { ChallengeMandated, NoPreference, NoChallengeRequested, ChallengeRequested, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafePaymentHandleRequest { pub merchant_ref_num: String, pub amount: MinorUnit, pub settle_with_auth: bool, #[serde(flatten)] pub payment_method: PaysafePaymentMethod, pub currency_code: Currency, pub payment_type: PaysafePaymentType, pub transaction_type: TransactionType, pub return_links: Vec<ReturnLink>, pub account_id: Secret<String>, pub three_ds: Option<ThreeDs>, pub profile: Option<PaysafeProfile>, pub billing_details: Option<PaysafeBillingDetails>, } #[derive(Debug, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaysafeBillingDetails { pub nick_name: Option<Secret<String>>, pub street: Option<Secret<String>>, pub street2: Option<Secret<String>>, pub city: Option<String>, pub state: Secret<String>, pub zip: Secret<String>, pub country: api_models::enums::CountryAlpha2, } #[derive(Debug, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaysafeProfile { pub first_name: Secret<String>, pub last_name: Secret<String>, pub email: Email, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] #[serde(untagged)] pub enum PaysafePaymentMethod { ApplePay { #[serde(rename = "applePay")] apple_pay: Box<PaysafeApplepayPayment>, }, Card { card: PaysafeCard, }, Interac { #[serde(rename = "interacEtransfer")] interac_etransfer: InteracBankRedirect, }, PaysafeCard { #[serde(rename = "paysafecard")] pay_safe_card: PaysafeGiftCard, }, Skrill { skrill: SkrillWallet, }, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeApplepayPayment { pub label: Option<String>, pub request_billing_address: Option<bool>, #[serde(rename = "applePayPaymentToken")] pub apple_pay_payment_token: PaysafeApplePayPaymentToken, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeApplePayPaymentToken { pub token: PaysafeApplePayToken, #[serde(skip_serializing_if = "Option::is_none")] pub billing_contact: Option<PaysafeApplePayBillingContact>, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeApplePayToken { pub payment_data: PaysafeApplePayPaymentData, pub payment_method: PaysafeApplePayPaymentMethod, pub transaction_identifier: String, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum PaysafeApplePayPaymentData { Encrypted(PaysafeApplePayEncryptedData), Decrypted(PaysafeApplePayDecryptedDataWrapper), } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeApplePayEncryptedData { pub data: Secret<String>, pub signature: Secret<String>, pub header: PaysafeApplePayHeader, pub version: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeApplePayDecryptedDataWrapper { pub decrypted_data: PaysafeApplePayDecryptedData, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeApplePayDecryptedData { pub application_primary_account_number: CardNumber, pub application_expiration_date: Secret<String>, pub currency_code: String, pub transaction_amount: Option<MinorUnit>, pub cardholder_name: Option<Secret<String>>, pub device_manufacturer_identifier: Option<String>, pub payment_data_type: Option<String>, pub payment_data: PaysafeApplePayDecryptedPaymentData, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeApplePayDecryptedPaymentData { pub online_payment_cryptogram: Secret<String>, pub eci_indicator: Option<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeApplePayHeader { pub public_key_hash: String, pub ephemeral_public_key: String, pub transaction_id: String, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeApplePayPaymentMethod { pub display_name: Secret<String>, pub network: Secret<String>, #[serde(rename = "type")] pub method_type: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeApplePayBillingContact { pub address_lines: Vec<Option<Secret<String>>>, #[serde(skip_serializing_if = "Option::is_none")] pub administrative_area: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub country: Option<String>, pub country_code: api_models::enums::CountryAlpha2, #[serde(skip_serializing_if = "Option::is_none")] pub family_name: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub given_name: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub locality: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub phonetic_family_name: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub phonetic_given_name: Option<Secret<String>>, pub postal_code: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub sub_administrative_area: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub sub_locality: Option<Secret<String>>, } #[derive(Debug, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SkrillWallet { pub consumer_id: Email, pub country_code: Option<api_models::enums::CountryAlpha2>, } #[derive(Debug, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct InteracBankRedirect { pub consumer_id: Email, } #[derive(Debug, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaysafeGiftCard { pub consumer_id: id_type::CustomerId, } #[derive(Debug, Serialize)] pub struct ReturnLink { pub rel: LinkType, pub href: String, pub method: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum LinkType { OnCompleted, OnFailed, OnCancelled, Default, } #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaysafePaymentType { // For Apple Pay and Google Pay, paymentType is 'CARD' as per Paysafe docs and is not reserved for card payments only Card, Skrill, InteracEtransfer, Paysafecard, } #[derive(Debug, Serialize)] pub enum TransactionType { #[serde(rename = "PAYMENT")] Payment, } impl PaysafePaymentMethodDetails { pub fn get_applepay_encrypt_account_id( &self, currency: Currency, ) -> Result<Secret<String>, errors::ConnectorError> { self.apple_pay .as_ref() .and_then(|apple_pay| apple_pay.get(&currency)) .and_then(|flow| flow.encrypt.clone()) .ok_or_else(|| errors::ConnectorError::InvalidConnectorConfig { config: "Missing ApplePay encrypt account_id", }) } pub fn get_applepay_decrypt_account_id( &self, currency: Currency, ) -> Result<Secret<String>, errors::ConnectorError> { self.apple_pay .as_ref() .and_then(|apple_pay| apple_pay.get(&currency)) .and_then(|flow| flow.decrypt.clone()) .ok_or_else(|| errors::ConnectorError::InvalidConnectorConfig { config: "Missing ApplePay decrypt account_id", }) } pub fn get_no_three_ds_account_id( &self, currency: Currency, ) -> Result<Secret<String>, errors::ConnectorError> { self.card .as_ref() .and_then(|cards| cards.get(&currency)) .and_then(|card| card.no_three_ds.clone()) .ok_or(errors::ConnectorError::InvalidConnectorConfig { config: "Missing no_3ds account_id", }) } pub fn get_three_ds_account_id( &self, currency: Currency, ) -> Result<Secret<String>, errors::ConnectorError> { self.card .as_ref() .and_then(|cards| cards.get(&currency)) .and_then(|card| card.three_ds.clone()) .ok_or(errors::ConnectorError::InvalidConnectorConfig { config: "Missing 3ds account_id", }) } pub fn get_skrill_account_id( &self, currency: Currency, ) -> Result<Secret<String>, errors::ConnectorError> { self.skrill .as_ref() .and_then(|wallets| wallets.get(&currency)) .and_then(|skrill| skrill.three_ds.clone()) .ok_or(errors::ConnectorError::InvalidConnectorConfig { config: "Missing skrill account_id", }) } pub fn get_interac_account_id( &self, currency: Currency, ) -> Result<Secret<String>, errors::ConnectorError> { self.interac .as_ref() .and_then(|redirects| redirects.get(&currency)) .and_then(|interac| interac.three_ds.clone()) .ok_or(errors::ConnectorError::InvalidConnectorConfig { config: "Missing interac account_id", }) } pub fn get_paysafe_gift_card_account_id( &self, currency: Currency, ) -> Result<Secret<String>, errors::ConnectorError> { self.pay_safe_card .as_ref() .and_then(|gift_cards| gift_cards.get(&currency)) .and_then(|pay_safe_card| pay_safe_card.three_ds.clone()) .ok_or(errors::ConnectorError::InvalidConnectorConfig { config: "Missing paysafe gift card account_id", }) } } fn create_paysafe_billing_details<T>( is_customer_initiated_mandate_payment: bool, item: &T, ) -> Result<Option<PaysafeBillingDetails>, error_stack::Report<errors::ConnectorError>> where T: RouterDataUtils, { // For customer-initiated mandate payments, zip, country and state fields are mandatory if is_customer_initiated_mandate_payment { Ok(Some(PaysafeBillingDetails { nick_name: item.get_optional_billing_first_name(), street: item.get_optional_billing_line1(), street2: item.get_optional_billing_line2(), city: item.get_optional_billing_city(), zip: item.get_billing_zip()?, country: item.get_billing_country()?, state: item.get_billing_state_code()?, })) } // For normal payments, only send billing details if billing mandatory fields are available else if let (Some(zip), Some(country), Some(state)) = ( item.get_optional_billing_zip(), item.get_optional_billing_country(), item.get_optional_billing_state_code(), ) { Ok(Some(PaysafeBillingDetails { nick_name: item.get_optional_billing_first_name(), street: item.get_optional_billing_line1(), street2: item.get_optional_billing_line2(), city: item.get_optional_billing_city(), zip, country, state, })) } else { Ok(None) } } impl TryFrom<&PaysafeRouterData<&PaymentsPreProcessingRouterData>> for PaysafePaymentHandleRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaysafeRouterData<&PaymentsPreProcessingRouterData>, ) -> Result<Self, Self::Error> { let metadata: PaysafeConnectorMetadataObject = utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "merchant_connector_account.metadata", })?; let amount = item.amount; let currency_code = item.router_data.request.get_currency()?; let redirect_url = item.router_data.request.get_router_return_url()?; let return_links = vec![ ReturnLink { rel: LinkType::Default, href: redirect_url.clone(), method: Method::Get.to_string(), }, ReturnLink { rel: LinkType::OnCompleted, href: redirect_url.clone(), method: Method::Get.to_string(), }, ReturnLink { rel: LinkType::OnFailed, href: redirect_url.clone(), method: Method::Get.to_string(), }, ReturnLink { rel: LinkType::OnCancelled, href: redirect_url.clone(), method: Method::Get.to_string(), }, ]; let settle_with_auth = matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None ); let transaction_type = TransactionType::Payment; let billing_details = create_paysafe_billing_details( item.router_data .request .is_customer_initiated_mandate_payment(), item.router_data, )?; let (payment_method, payment_type, account_id) = match item.router_data.request.get_payment_method_data()?.clone() { PaymentMethodData::Card(req_card) => { let card = PaysafeCard { card_num: req_card.card_number.clone(), card_expiry: PaysafeCardExpiry { month: req_card.card_exp_month.clone(), year: req_card.get_expiry_year_4_digit(), }, cvv: if req_card.card_cvc.clone().expose().is_empty() { None } else { Some(req_card.card_cvc.clone()) }, holder_name: item.router_data.get_optional_billing_full_name(), }; let payment_method = PaysafePaymentMethod::Card { card: card.clone() }; let payment_type = PaysafePaymentType::Card; let account_id = metadata .account_id .get_no_three_ds_account_id(currency_code)?; (payment_method, payment_type, account_id) } PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::ApplePay(applepay_data) => { let is_encrypted = matches!( applepay_data.payment_data, ApplePayPaymentData::Encrypted(_) ); let account_id = if is_encrypted { metadata .account_id .get_applepay_encrypt_account_id(currency_code)? } else { metadata .account_id .get_applepay_decrypt_account_id(currency_code)? }; let applepay_payment = PaysafeApplepayPayment::try_from((&applepay_data, item))?; let payment_method = PaysafePaymentMethod::ApplePay { apple_pay: Box::new(applepay_payment), }; let payment_type = PaysafePaymentType::Card; (payment_method, payment_type, account_id) } WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePay(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalSdk(_) | WalletData::PaypalRedirect(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayRedirect(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::WeChatPayQr(_) | WalletData::RevolutPay(_) | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paysafe"), ))?, }, _ => Err(errors::ConnectorError::NotImplemented( "Payment Method".to_string(), ))?, }; Ok(Self { merchant_ref_num: item.router_data.connector_request_reference_id.clone(), amount, settle_with_auth, payment_method, currency_code, payment_type, transaction_type, return_links, account_id, three_ds: None, profile: None, billing_details, }) } } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaysafeUsage { SingleUse, MultiUse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaysafePaymentHandleResponse { pub id: String, pub merchant_ref_num: String, pub payment_handle_token: Secret<String>, pub usage: Option<PaysafeUsage>, pub status: PaysafePaymentHandleStatus, pub links: Option<Vec<PaymentLink>>, pub error: Option<Error>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentLink { pub rel: String, pub href: String, } #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum PaysafePaymentHandleStatus { Initiated, Payable, #[default] Processing, Failed, Expired, Completed, Error, } impl TryFrom<PaysafePaymentHandleStatus> for common_enums::AttemptStatus { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: PaysafePaymentHandleStatus) -> Result<Self, Self::Error> { match item { PaysafePaymentHandleStatus::Completed => Ok(Self::Authorized), PaysafePaymentHandleStatus::Failed | PaysafePaymentHandleStatus::Expired | PaysafePaymentHandleStatus::Error => Ok(Self::Failure), // We get an `Initiated` status, with a redirection link from the connector, which indicates that further action is required by the customer, PaysafePaymentHandleStatus::Initiated => Ok(Self::AuthenticationPending), PaysafePaymentHandleStatus::Payable | PaysafePaymentHandleStatus::Processing => { Ok(Self::Pending) } } } } #[derive(Debug, Serialize, Deserialize)] pub struct PaysafeMeta { pub payment_handle_token: Secret<String>, } impl<F> TryFrom< ResponseRouterData< F, PaysafePaymentHandleResponse, PaymentsPreProcessingData, PaymentsResponseData, >, > for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, PaysafePaymentHandleResponse, PaymentsPreProcessingData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::try_from(item.response.status)?, preprocessing_id: Some( item.response .payment_handle_token .to_owned() .peek() .to_string(), ), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl<F> TryFrom< ResponseRouterData<F, PaysafePaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData>, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, PaysafePaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let mandate_reference = item .response .payment_handle_token .map(|payment_handle_token| payment_handle_token.expose()) .map(|mandate_id| MandateReference { connector_mandate_id: Some(mandate_id), payment_method_id: None, mandate_metadata: Some(Secret::new(serde_json::json!(PaysafeMandateMetadata { initial_transaction_id: item.response.id.clone() }))), connector_mandate_request_reference_id: None, }); Ok(Self { status: get_paysafe_payment_status( item.response.status, item.data.request.capture_method, ), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl<F> TryFrom< ResponseRouterData< F, PaysafePaymentHandleResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, PaysafePaymentHandleResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let redirection_data = item .response .links .as_ref() .and_then(|links| links.first()) .map(|link| RedirectForm::Form { endpoint: link.href.clone(), method: Method::Get, form_fields: Default::default(), }); let connector_metadata = serde_json::json!(PaysafeMeta { payment_handle_token: item.response.payment_handle_token.clone(), }); Ok(Self { status: common_enums::AttemptStatus::try_from(item.response.status)?, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: Some(connector_metadata), network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaysafePaymentsRequest { pub merchant_ref_num: String, pub amount: MinorUnit, pub settle_with_auth: bool, pub payment_handle_token: Secret<String>, pub currency_code: Currency, pub customer_ip: Option<Secret<String, IpAddress>>, pub stored_credential: Option<PaysafeStoredCredential>, #[serde(skip_serializing_if = "Option::is_none")] pub account_id: Option<Secret<String>>, } #[derive(Debug, Serialize, Clone, PartialEq, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeStoredCredential { #[serde(rename = "type")] stored_credential_type: PaysafeStoredCredentialType, occurrence: MandateOccurence, #[serde(skip_serializing_if = "Option::is_none")] initial_transaction_id: Option<String>, } impl PaysafeStoredCredential { fn new_customer_initiated_transaction() -> Self { Self { stored_credential_type: PaysafeStoredCredentialType::Adhoc, occurrence: MandateOccurence::Initial, initial_transaction_id: None, } } fn new_merchant_initiated_transaction(initial_transaction_id: String) -> Self { Self { stored_credential_type: PaysafeStoredCredentialType::Topup, occurrence: MandateOccurence::Subsequent, initial_transaction_id: Some(initial_transaction_id), } } } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum MandateOccurence { Initial, Subsequent, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum PaysafeStoredCredentialType { Adhoc, Topup, } #[derive(Debug, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaysafeCard { pub card_num: CardNumber, pub card_expiry: PaysafeCardExpiry, #[serde(skip_serializing_if = "Option::is_none")] pub cvv: Option<Secret<String>>, pub holder_name: Option<Secret<String>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PaysafeCardExpiry { pub month: Secret<String>, pub year: Secret<String>, } #[derive(Debug, Deserialize)] struct DecryptedApplePayTokenData { data: Secret<String>, signature: Secret<String>, header: DecryptedApplePayTokenHeader, version: Secret<String>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct DecryptedApplePayTokenHeader { public_key_hash: String, ephemeral_public_key: String, transaction_id: String, } fn get_apple_pay_decrypt_data( apple_pay_predecrypt_data: &ApplePayPredecryptData, item: &PaysafeRouterData<&PaymentsPreProcessingRouterData>, ) -> Result<PaysafeApplePayDecryptedData, error_stack::Report<errors::ConnectorError>> { Ok(PaysafeApplePayDecryptedData { application_primary_account_number: apple_pay_predecrypt_data .application_primary_account_number .clone(), application_expiration_date: apple_pay_predecrypt_data .get_expiry_date_as_yymm() .change_context(errors::ConnectorError::InvalidDataFormat { field_name: "application_expiration_date", })?, currency_code: Currency::iso_4217( item.router_data .request .currency .ok_or_else(missing_field_err("currency"))?, ) .to_string(), transaction_amount: Some(item.amount), cardholder_name: None, device_manufacturer_identifier: Some("Apple".to_string()), payment_data_type: Some("3DSecure".to_string()), payment_data: PaysafeApplePayDecryptedPaymentData { online_payment_cryptogram: apple_pay_predecrypt_data .payment_data .online_payment_cryptogram .clone(), eci_indicator: apple_pay_predecrypt_data.payment_data.eci_indicator.clone(), }, }) } impl TryFrom<( &ApplePayWalletData, &PaysafeRouterData<&PaymentsPreProcessingRouterData>, )> for PaysafeApplepayPayment { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (wallet_data, item): ( &ApplePayWalletData, &PaysafeRouterData<&PaymentsPreProcessingRouterData>, ), ) -> Result<Self, Self::Error> { let apple_pay_payment_token = PaysafeApplePayPaymentToken { token: PaysafeApplePayToken { payment_data: if let Ok(PaymentMethodToken::ApplePayDecrypt(ref token)) = item.router_data.get_payment_method_token() { PaysafeApplePayPaymentData::Decrypted(PaysafeApplePayDecryptedDataWrapper { decrypted_data: get_apple_pay_decrypt_data(token, item)?, }) } else { match &wallet_data.payment_data { ApplePayPaymentData::Decrypted(applepay_predecrypt_data) => { PaysafeApplePayPaymentData::Decrypted( PaysafeApplePayDecryptedDataWrapper { decrypted_data: get_apple_pay_decrypt_data( applepay_predecrypt_data, item, )?, }, ) } ApplePayPaymentData::Encrypted(applepay_encrypt_data) => { let decoded_data = base64::prelude::BASE64_STANDARD .decode(applepay_encrypt_data) .change_context(errors::ConnectorError::InvalidDataFormat { field_name: "apple_pay_encrypted_data", })?; let apple_pay_token: DecryptedApplePayTokenData = serde_json::from_slice(&decoded_data).change_context( errors::ConnectorError::InvalidDataFormat { field_name: "apple_pay_token_json", }, )?; PaysafeApplePayPaymentData::Encrypted(PaysafeApplePayEncryptedData { data: apple_pay_token.data, signature: apple_pay_token.signature, header: PaysafeApplePayHeader { public_key_hash: apple_pay_token.header.public_key_hash, ephemeral_public_key: apple_pay_token .header .ephemeral_public_key, transaction_id: apple_pay_token.header.transaction_id, }, version: apple_pay_token.version, }) } } }, payment_method: PaysafeApplePayPaymentMethod { display_name: Secret::new(wallet_data.payment_method.display_name.clone()), network: Secret::new(wallet_data.payment_method.network.clone()), method_type: Secret::new(wallet_data.payment_method.pm_type.clone()), }, transaction_identifier: wallet_data.transaction_identifier.clone(), }, billing_contact: Some(PaysafeApplePayBillingContact { address_lines: vec![ item.router_data.get_optional_billing_line1(), item.router_data.get_optional_billing_line2(), ], postal_code: item.router_data.get_billing_zip()?, country_code: item.router_data.get_billing_country()?, country: None, family_name: None, given_name: None, locality: None, phonetic_family_name: None, phonetic_given_name: None, sub_administrative_area: None, administrative_area: None, sub_locality: None, }), }; Ok(Self { label: None, request_billing_address: Some(false), apple_pay_payment_token, }) } } #[derive(Debug, Clone)] pub struct PaysafeMandateData { stored_credential: Option<PaysafeStoredCredential>, payment_token: Secret<String>, } impl TryFrom<&PaymentsAuthorizeRouterData> for PaysafeMandateData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { match ( item.request.is_cit_mandate_payment(), item.request.get_connector_mandate_data(), ) { (true, _) => Ok(Self { stored_credential: Some( PaysafeStoredCredential::new_customer_initiated_transaction(), ), payment_token: item.get_preprocessing_id()?.into(), }), (false, Some(mandate_data)) => { let mandate_id = mandate_data .get_connector_mandate_id() .ok_or(errors::ConnectorError::MissingConnectorMandateID)?; let mandate_metadata: PaysafeMandateMetadata = mandate_data .get_mandate_metadata() .ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)? .clone() .parse_value("PaysafeMandateMetadata") .change_context(errors::ConnectorError::ParsingFailed)?; Ok(Self { stored_credential: Some( PaysafeStoredCredential::new_merchant_initiated_transaction( mandate_metadata.initial_transaction_id, ), ), payment_token: mandate_id.into(), }) } _ => Ok(Self { stored_credential: None, payment_token: item.get_preprocessing_id()?.into(), }), } } } impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaysafeRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let amount = item.amount; let customer_ip = Some( item.router_data .request .get_browser_info()? .get_ip_address()?, ); let metadata: PaysafeConnectorMetadataObject = utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "merchant_connector_account.metadata", })?; let account_id = match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment => { if item.router_data.is_three_ds() { Some( metadata .account_id .get_three_ds_account_id(item.router_data.request.currency)?, ) } else { Some( metadata .account_id .get_no_three_ds_account_id(item.router_data.request.currency)?, ) } } _ => None, }; let mandate_data = PaysafeMandateData::try_from(item.router_data)?; Ok(Self { merchant_ref_num: item.router_data.connector_request_reference_id.clone(), payment_handle_token: mandate_data.payment_token, amount, settle_with_auth: item.router_data.request.is_auto_capture()?, currency_code: item.router_data.request.currency, customer_ip, stored_credential: mandate_data.stored_credential, account_id, }) } } impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymentHandleRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaysafeRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { if item .router_data .request .is_customer_initiated_mandate_payment() { Err(errors::ConnectorError::NotSupported { message: format!( "Mandate Payment with {} {}", item.router_data.payment_method, item.router_data.auth_type ), connector: "Paysafe", })? }; let metadata: PaysafeConnectorMetadataObject = utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "merchant_connector_account.metadata", })?; let redirect_url_success = item.router_data.request.get_complete_authorize_url()?; let redirect_url = item.router_data.request.get_router_return_url()?; let return_links = vec![ ReturnLink { rel: LinkType::Default, href: redirect_url.clone(), method: Method::Get.to_string(), }, ReturnLink { rel: LinkType::OnCompleted, href: redirect_url_success.clone(), method: Method::Get.to_string(), }, ReturnLink { rel: LinkType::OnFailed, href: redirect_url.clone(), method: Method::Get.to_string(), }, ReturnLink { rel: LinkType::OnCancelled, href: redirect_url.clone(), method: Method::Get.to_string(), }, ]; let amount = item.amount; let currency_code = item.router_data.request.currency; let settle_with_auth = matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None ); let transaction_type = TransactionType::Payment; let (payment_method, payment_type, account_id, three_ds, profile) = match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let card = PaysafeCard { card_num: req_card.card_number.clone(), card_expiry: PaysafeCardExpiry { month: req_card.card_exp_month.clone(), year: req_card.get_expiry_year_4_digit(), }, cvv: if req_card.card_cvc.clone().expose().is_empty() { None } else { Some(req_card.card_cvc.clone()) }, holder_name: item.router_data.get_optional_billing_full_name(), }; let payment_method = PaysafePaymentMethod::Card { card: card.clone() }; let payment_type = PaysafePaymentType::Card; let headers = item.router_data.header_payload.clone(); let platform = headers.as_ref().and_then(|h| h.x_client_platform.clone()); let device_channel = match platform { Some(common_enums::ClientPlatform::Web) | Some(common_enums::ClientPlatform::Unknown) | None => DeviceChannel::Browser, Some(common_enums::ClientPlatform::Ios) | Some(common_enums::ClientPlatform::Android) => DeviceChannel::Sdk, }; let account_id = metadata.account_id.get_three_ds_account_id(currency_code)?; let three_ds = Some(ThreeDs { merchant_url: item.router_data.request.get_router_return_url()?, device_channel, message_category: ThreeDsMessageCategory::Payment, authentication_purpose: ThreeDsAuthenticationPurpose::PaymentTransaction, requestor_challenge_preference: ThreeDsChallengePreference::ChallengeMandated, }); (payment_method, payment_type, account_id, three_ds, None) } PaymentMethodData::Wallet(WalletData::Skrill(_)) => { let payment_method = PaysafePaymentMethod::Skrill { skrill: SkrillWallet { consumer_id: item.router_data.get_billing_email()?, country_code: item.router_data.get_optional_billing_country(), }, }; let payment_type = PaysafePaymentType::Skrill; let account_id = metadata.account_id.get_skrill_account_id(currency_code)?; (payment_method, payment_type, account_id, None, None) } PaymentMethodData::Wallet(_) => Err(errors::ConnectorError::NotImplemented( "Payment Method".to_string(), ))?, PaymentMethodData::BankRedirect(BankRedirectData::Interac { .. }) => { let payment_method = PaysafePaymentMethod::Interac { interac_etransfer: InteracBankRedirect { consumer_id: item.router_data.get_billing_email()?, }, }; let payment_type = PaysafePaymentType::InteracEtransfer; let account_id = metadata.account_id.get_interac_account_id(currency_code)?; let profile = Some(PaysafeProfile { first_name: item.router_data.get_billing_first_name()?, last_name: item.router_data.get_billing_last_name()?, email: item.router_data.get_billing_email()?, }); (payment_method, payment_type, account_id, None, profile) } PaymentMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotImplemented( "Payment Method".to_string(), ))?, PaymentMethodData::GiftCard(gift_card_data) => match gift_card_data.as_ref() { GiftCardData::PaySafeCard {} => { let payment_method = PaysafePaymentMethod::PaysafeCard { pay_safe_card: PaysafeGiftCard { consumer_id: item.router_data.get_customer_id()?, }, }; let payment_type = PaysafePaymentType::Paysafecard; let account_id = metadata .account_id .get_paysafe_gift_card_account_id(currency_code)?; (payment_method, payment_type, account_id, None, None) } _ => Err(errors::ConnectorError::NotImplemented( "Payment Method".to_string(), ))?, }, _ => Err(errors::ConnectorError::NotImplemented( "Payment Method".to_string(), ))?, }; let billing_details = create_paysafe_billing_details( item.router_data .request .is_customer_initiated_mandate_payment(), item.router_data, )?; Ok(Self { merchant_ref_num: item.router_data.connector_request_reference_id.clone(), amount, settle_with_auth, payment_method, currency_code, payment_type, transaction_type, return_links, account_id, three_ds, profile, billing_details, }) } } impl TryFrom<&PaysafeRouterData<&PaymentsCompleteAuthorizeRouterData>> for PaysafePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PaysafeRouterData<&PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let paysafe_meta: PaysafeMeta = to_connector_meta( item.router_data.request.connector_meta.clone(), ) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "connector_metadata", })?; let payment_handle_token = paysafe_meta.payment_handle_token; let amount = item.amount; let customer_ip = Some( item.router_data .request .get_browser_info()? .get_ip_address()?, ); Ok(Self { merchant_ref_num: item.router_data.connector_request_reference_id.clone(), payment_handle_token, amount, settle_with_auth: item.router_data.request.is_auto_capture()?, currency_code: item.router_data.request.currency, customer_ip, stored_credential: None, account_id: None, }) } } impl<F> TryFrom< ResponseRouterData<F, PaysafePaymentsResponse, CompleteAuthorizeData, PaymentsResponseData>, > for RouterData<F, CompleteAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, PaysafePaymentsResponse, CompleteAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { status: get_paysafe_payment_status( item.response.status, item.data.request.capture_method, ), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } pub struct PaysafeAuthType { pub(super) username: Secret<String>, pub(super) password: Secret<String>, } impl TryFrom<&ConnectorAuthType> for PaysafeAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { username: api_key.to_owned(), password: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // Paysafe Payment Status #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum PaysafePaymentStatus { Received, Completed, Held, Failed, #[default] Pending, Cancelled, Processing, } pub fn get_paysafe_payment_status( status: PaysafePaymentStatus, capture_method: Option<common_enums::CaptureMethod>, ) -> common_enums::AttemptStatus { match status { PaysafePaymentStatus::Completed => match capture_method { Some(common_enums::CaptureMethod::Manual) => common_enums::AttemptStatus::Authorized, Some(common_enums::CaptureMethod::Automatic) | None => { common_enums::AttemptStatus::Charged } Some(common_enums::CaptureMethod::SequentialAutomatic) | Some(common_enums::CaptureMethod::ManualMultiple) | Some(common_enums::CaptureMethod::Scheduled) => { common_enums::AttemptStatus::Unresolved } }, PaysafePaymentStatus::Failed => common_enums::AttemptStatus::Failure, PaysafePaymentStatus::Pending | PaysafePaymentStatus::Processing | PaysafePaymentStatus::Received | PaysafePaymentStatus::Held => common_enums::AttemptStatus::Pending, PaysafePaymentStatus::Cancelled => common_enums::AttemptStatus::Voided, } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum PaysafeSyncResponse { Payments(PaysafePaymentsSyncResponse), PaymentHandles(PaysafePaymentHandlesSyncResponse), } // Paysafe Payments Response Structure #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaysafePaymentsSyncResponse { pub payments: Vec<PaysafePaymentsResponse>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaysafePaymentHandlesSyncResponse { pub payment_handles: Vec<PaysafePaymentHandleResponse>, } // Paysafe Payments Response Structure #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaysafePaymentsResponse { pub id: String, pub payment_handle_token: Option<Secret<String>>, pub merchant_ref_num: Option<String>, pub status: PaysafePaymentStatus, pub error: Option<Error>, } // Paysafe Mandate Metadata #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct PaysafeMandateMetadata { pub initial_transaction_id: String, } // Paysafe Customer Response Structure #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeCustomerResponse { pub id: String, pub status: Option<String>, pub merchant_customer_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaysafeSettlementResponse { pub merchant_ref_num: Option<String>, pub id: String, pub status: PaysafeSettlementStatus, } impl<F, T> TryFrom<ResponseRouterData<F, PaysafeCustomerResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaysafeCustomerResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PaymentsResponseData::ConnectorCustomerResponse( ConnectorCustomerResponseData::new_with_customer_id(item.response.id), )), ..item.data }) } } impl<F> TryFrom<ResponseRouterData<F, PaysafeSyncResponse, PaymentsSyncData, PaymentsResponseData>> for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaysafeSyncResponse, PaymentsSyncData, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let status = match &item.response { PaysafeSyncResponse::Payments(sync_response) => { let payment_response = sync_response .payments .first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; get_paysafe_payment_status( payment_response.status, item.data.request.capture_method, ) } PaysafeSyncResponse::PaymentHandles(sync_response) => { let payment_handle_response = sync_response .payment_handles .first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; common_enums::AttemptStatus::try_from(payment_handle_response.status)? } }; let response = if utils::is_payment_failure(status) { let (code, message, reason, connector_transaction_id) = match &item.response { PaysafeSyncResponse::Payments(sync_response) => { let payment_response = sync_response .payments .first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; match &payment_response.error { Some(err) => ( err.code.clone(), err.message.clone(), err.details .as_ref() .and_then(|d| d.first().cloned()) .or_else(|| Some(err.message.clone())), payment_response.id.clone(), ), None => ( consts::NO_ERROR_CODE.to_string(), consts::NO_ERROR_MESSAGE.to_string(), None, payment_response.id.clone(), ), } } PaysafeSyncResponse::PaymentHandles(sync_response) => { let payment_handle_response = sync_response .payment_handles .first() .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; match &payment_handle_response.error { Some(err) => ( err.code.clone(), err.message.clone(), err.details .as_ref() .and_then(|d| d.first().cloned()) .or_else(|| Some(err.message.clone())), payment_handle_response.id.clone(), ), None => ( consts::NO_ERROR_CODE.to_string(), consts::NO_ERROR_MESSAGE.to_string(), None, payment_handle_response.id.clone(), ), } } }; Err(hyperswitch_domain_models::router_data::ErrorResponse { code, message, reason, attempt_status: None, connector_transaction_id: Some(connector_transaction_id), status_code: item.http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }) }; Ok(Self { status, response, ..item.data }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeCaptureRequest { pub merchant_ref_num: String, #[serde(skip_serializing_if = "Option::is_none")] pub amount: Option<MinorUnit>, } impl TryFrom<&PaysafeRouterData<&PaymentsCaptureRouterData>> for PaysafeCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaysafeRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { let amount = Some(item.amount); Ok(Self { merchant_ref_num: item.router_data.connector_request_reference_id.clone(), amount, }) } } #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum PaysafeSettlementStatus { Received, Initiated, Completed, Expired, Failed, #[default] Pending, Cancelled, } impl From<PaysafeSettlementStatus> for common_enums::AttemptStatus { fn from(item: PaysafeSettlementStatus) -> Self { match item { PaysafeSettlementStatus::Completed | PaysafeSettlementStatus::Pending | PaysafeSettlementStatus::Received => Self::Charged, PaysafeSettlementStatus::Failed | PaysafeSettlementStatus::Expired => Self::Failure, PaysafeSettlementStatus::Cancelled => Self::Voided, PaysafeSettlementStatus::Initiated => Self::Pending, } } } impl<F, T> TryFrom<ResponseRouterData<F, PaysafeSettlementResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, PaysafeSettlementResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } impl TryFrom<&PaysafeRouterData<&PaymentsCancelRouterData>> for PaysafeCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaysafeRouterData<&PaymentsCancelRouterData>) -> Result<Self, Self::Error> { let amount = Some(item.amount); Ok(Self { merchant_ref_num: item.router_data.connector_request_reference_id.clone(), amount, }) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct VoidResponse { pub merchant_ref_num: Option<String>, pub id: String, pub status: PaysafeVoidStatus, } #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum PaysafeVoidStatus { Received, Completed, Held, Failed, #[default] Pending, Cancelled, } impl From<PaysafeVoidStatus> for common_enums::AttemptStatus { fn from(item: PaysafeVoidStatus) -> Self { match item { PaysafeVoidStatus::Completed | PaysafeVoidStatus::Pending | PaysafeVoidStatus::Received => Self::Voided, PaysafeVoidStatus::Failed | PaysafeVoidStatus::Held => Self::Failure, PaysafeVoidStatus::Cancelled => Self::Voided, } } } impl<F, T> TryFrom<ResponseRouterData<F, VoidResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, VoidResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PaysafeRefundRequest { pub merchant_ref_num: String, pub amount: MinorUnit, } impl<F> TryFrom<&PaysafeRouterData<&RefundsRouterData<F>>> for PaysafeRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaysafeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let amount = item.amount; Ok(Self { merchant_ref_num: item.router_data.request.refund_id.clone(), amount, }) } } // Type definition for Refund Response #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] #[serde(rename_all = "UPPERCASE")] pub enum RefundStatus { Received, Initiated, Completed, Expired, Failed, #[default] Pending, Cancelled, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Received | RefundStatus::Completed => Self::Success, RefundStatus::Failed | RefundStatus::Cancelled | RefundStatus::Expired => Self::Failure, RefundStatus::Pending | RefundStatus::Initiated => Self::Pending, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Debug, Serialize, Deserialize)] pub struct PaysafeErrorResponse { pub error: Error, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Error { pub code: String, pub message: String, pub details: Option<Vec<String>>, #[serde(rename = "fieldErrors")] pub field_errors: Option<Vec<FieldError>>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FieldError { pub field: Option<String>, pub error: String, }
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
hyperswitch_connectors::src::connectors::paysafe::transformers
14,137
true
// File: crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs // Module: hyperswitch_connectors::src::connectors::multisafepay::transformers use common_enums::{enums, AttemptStatus, BankNames}; use common_utils::{ errors::ParsingError, pii::{Email, IpAddress}, request::Method, types::{FloatMajorUnit, MinorUnit}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankRedirectData, PayLaterData, PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types::{self}, }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors, }; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self, AddressDetailsData, CardData as _, PaymentsAuthorizeRequestData, RouterData as _, }, }; #[derive(Debug, Serialize)] pub struct MultisafepayRouterData<T> { amount: MinorUnit, router_data: T, } impl<T> From<(MinorUnit, T)> for MultisafepayRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum Type { Direct, Redirect, } #[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum Gateway { Amex, CreditCard, Discover, Maestro, MasterCard, Visa, Klarna, Googlepay, Paypal, Ideal, Giropay, Trustly, Alipay, #[serde(rename = "WECHAT")] WeChatPay, Eps, MbWay, #[serde(rename = "DIRECTBANK")] Sofort, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct Coupons { pub allow: Option<Vec<Secret<String>>>, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct Mistercash { pub mobile_pay_button_position: Option<String>, pub disable_mobile_pay_button: Option<String>, pub qr_only: Option<String>, pub qr_size: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "UPPERCASE")] pub struct Gateways { pub mistercash: Option<Mistercash>, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct Settings { pub coupons: Option<Coupons>, pub gateways: Option<Gateways>, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct PaymentOptions { pub notification_url: Option<String>, pub notification_method: Option<String>, pub redirect_url: String, pub cancel_url: String, pub close_window: Option<bool>, pub settings: Option<Settings>, pub template_id: Option<String>, pub allowed_countries: Option<Vec<String>>, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct Browser { pub javascript_enabled: Option<bool>, pub java_enabled: Option<bool>, pub cookies_enabled: Option<bool>, pub language: Option<String>, pub screen_color_depth: Option<i32>, pub screen_height: Option<i32>, pub screen_width: Option<i32>, pub time_zone: Option<i32>, pub user_agent: Option<String>, pub platform: Option<String>, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct Customer { pub browser: Option<Browser>, pub locale: Option<String>, pub ip_address: Option<Secret<String, IpAddress>>, pub forward_ip: Option<Secret<String, IpAddress>>, pub first_name: Option<Secret<String>>, pub last_name: Option<Secret<String>>, pub gender: Option<Secret<String>>, pub birthday: Option<Secret<String>>, pub address1: Option<Secret<String>>, pub address2: Option<Secret<String>>, pub house_number: Option<Secret<String>>, pub zip_code: Option<Secret<String>>, pub city: Option<String>, pub state: Option<String>, pub country: Option<String>, pub phone: Option<Secret<String>>, pub email: Option<Email>, pub user_agent: Option<String>, pub referrer: Option<String>, pub reference: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct CardInfo { pub card_number: Option<cards::CardNumber>, pub card_holder_name: Option<Secret<String>>, pub card_expiry_date: Option<Secret<i32>>, pub card_cvc: Option<Secret<String>>, pub flexible_3d: Option<bool>, pub moto: Option<bool>, pub term_url: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct GpayInfo { pub payment_token: Option<Secret<String>>, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct PayLaterInfo { pub email: Option<Email>, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum GatewayInfo { Card(CardInfo), Wallet(WalletInfo), PayLater(PayLaterInfo), BankRedirect(BankRedirectInfo), } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum WalletInfo { GooglePay(GpayInfo), Alipay(AlipayInfo), WeChatPay(WeChatPayInfo), MbWay(MbWayInfo), } #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct MbWayInfo {} #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct WeChatPayInfo {} #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct AlipayInfo {} #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum BankRedirectInfo { Ideal(IdealInfo), Trustly(TrustlyInfo), Eps(EpsInfo), Sofort(SofortInfo), } #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct SofortInfo {} #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct EpsInfo {} #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct TrustlyInfo {} #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub struct IdealInfo { pub issuer_id: MultisafepayBankNames, } #[derive(Debug, Clone, Serialize, Eq, PartialEq)] pub enum MultisafepayBankNames { #[serde(rename = "0031")] AbnAmro, #[serde(rename = "0761")] AsnBank, #[serde(rename = "4371")] Bunq, #[serde(rename = "0721")] Ing, #[serde(rename = "0801")] Knab, #[serde(rename = "9926")] N26, #[serde(rename = "9927")] NationaleNederlanden, #[serde(rename = "0021")] Rabobank, #[serde(rename = "0771")] Regiobank, #[serde(rename = "1099")] Revolut, #[serde(rename = "0751")] SnsBank, #[serde(rename = "0511")] TriodosBank, #[serde(rename = "0161")] VanLanschot, #[serde(rename = "0806")] Yoursafe, #[serde(rename = "1235")] Handelsbanken, } impl TryFrom<&BankNames> for MultisafepayBankNames { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(bank: &BankNames) -> Result<Self, Self::Error> { match bank { BankNames::AbnAmro => Ok(Self::AbnAmro), BankNames::AsnBank => Ok(Self::AsnBank), BankNames::Bunq => Ok(Self::Bunq), BankNames::Ing => Ok(Self::Ing), BankNames::Knab => Ok(Self::Knab), BankNames::N26 => Ok(Self::N26), BankNames::NationaleNederlanden => Ok(Self::NationaleNederlanden), BankNames::Rabobank => Ok(Self::Rabobank), BankNames::Regiobank => Ok(Self::Regiobank), BankNames::Revolut => Ok(Self::Revolut), BankNames::SnsBank => Ok(Self::SnsBank), BankNames::TriodosBank => Ok(Self::TriodosBank), BankNames::VanLanschot => Ok(Self::VanLanschot), BankNames::Yoursafe => Ok(Self::Yoursafe), BankNames::Handelsbanken => Ok(Self::Handelsbanken), BankNames::AmericanExpress | BankNames::AffinBank | BankNames::AgroBank | BankNames::AllianceBank | BankNames::AmBank | BankNames::BankOfAmerica | BankNames::BankOfChina | BankNames::BankIslam | BankNames::BankMuamalat | BankNames::BankRakyat | BankNames::BankSimpananNasional | BankNames::Barclays | BankNames::BlikPSP | BankNames::CapitalOne | BankNames::Chase | BankNames::Citi | BankNames::CimbBank | BankNames::Discover | BankNames::NavyFederalCreditUnion | BankNames::PentagonFederalCreditUnion | BankNames::SynchronyBank | BankNames::WellsFargo | BankNames::HongLeongBank | BankNames::HsbcBank | BankNames::KuwaitFinanceHouse | BankNames::Moneyou | BankNames::ArzteUndApothekerBank | BankNames::AustrianAnadiBankAg | BankNames::BankAustria | BankNames::Bank99Ag | BankNames::BankhausCarlSpangler | BankNames::BankhausSchelhammerUndSchatteraAg | BankNames::BankMillennium | BankNames::BankPEKAOSA | BankNames::BawagPskAg | BankNames::BksBankAg | BankNames::BrullKallmusBankAg | BankNames::BtvVierLanderBank | BankNames::CapitalBankGraweGruppeAg | BankNames::CeskaSporitelna | BankNames::Dolomitenbank | BankNames::EasybankAg | BankNames::EPlatbyVUB | BankNames::ErsteBankUndSparkassen | BankNames::FrieslandBank | BankNames::HypoAlpeadriabankInternationalAg | BankNames::HypoNoeLbFurNiederosterreichUWien | BankNames::HypoOberosterreichSalzburgSteiermark | BankNames::HypoTirolBankAg | BankNames::HypoVorarlbergBankAg | BankNames::HypoBankBurgenlandAktiengesellschaft | BankNames::KomercniBanka | BankNames::MBank | BankNames::MarchfelderBank | BankNames::Maybank | BankNames::OberbankAg | BankNames::OsterreichischeArzteUndApothekerbank | BankNames::OcbcBank | BankNames::PayWithING | BankNames::PlaceZIPKO | BankNames::PlatnoscOnlineKartaPlatnicza | BankNames::PosojilnicaBankEGen | BankNames::PostovaBanka | BankNames::PublicBank | BankNames::RaiffeisenBankengruppeOsterreich | BankNames::RhbBank | BankNames::SchelhammerCapitalBankAg | BankNames::StandardCharteredBank | BankNames::SchoellerbankAg | BankNames::SpardaBankWien | BankNames::SporoPay | BankNames::SantanderPrzelew24 | BankNames::TatraPay | BankNames::Viamo | BankNames::VolksbankGruppe | BankNames::VolkskreditbankAg | BankNames::VrBankBraunau | BankNames::UobBank | BankNames::PayWithAliorBank | BankNames::BankiSpoldzielcze | BankNames::PayWithInteligo | BankNames::BNPParibasPoland | BankNames::BankNowySA | BankNames::CreditAgricole | BankNames::PayWithBOS | BankNames::PayWithCitiHandlowy | BankNames::PayWithPlusBank | BankNames::ToyotaBank | BankNames::VeloBank | BankNames::ETransferPocztowy24 | BankNames::PlusBank | BankNames::EtransferPocztowy24 | BankNames::BankiSpbdzielcze | BankNames::BankNowyBfgSa | BankNames::GetinBank | BankNames::Blik | BankNames::NoblePay | BankNames::IdeaBank | BankNames::EnveloBank | BankNames::NestPrzelew | BankNames::MbankMtransfer | BankNames::Inteligo | BankNames::PbacZIpko | BankNames::BnpParibas | BankNames::BankPekaoSa | BankNames::VolkswagenBank | BankNames::AliorBank | BankNames::Boz | BankNames::BangkokBank | BankNames::KrungsriBank | BankNames::KrungThaiBank | BankNames::TheSiamCommercialBank | BankNames::KasikornBank | BankNames::OpenBankSuccess | BankNames::OpenBankFailure | BankNames::OpenBankCancelled | BankNames::Aib | BankNames::BankOfScotland | BankNames::DanskeBank | BankNames::FirstDirect | BankNames::FirstTrust | BankNames::Halifax | BankNames::Lloyds | BankNames::Monzo | BankNames::NatWest | BankNames::NationwideBank | BankNames::RoyalBankOfScotland | BankNames::Starling | BankNames::TsbBank | BankNames::TescoBank | BankNames::UlsterBank => Err(Into::into(errors::ConnectorError::NotSupported { message: String::from("BankRedirect"), connector: "Multisafepay", })), } } } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct DeliveryObject { first_name: Secret<String>, last_name: Secret<String>, address1: Secret<String>, house_number: Secret<String>, zip_code: Secret<String>, city: String, country: api_models::enums::CountryAlpha2, } #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct DefaultObject { shipping_taxed: bool, rate: f64, } #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct TaxObject { pub default: DefaultObject, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct CheckoutOptions { pub validate_cart: Option<bool>, pub tax_tables: TaxObject, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct Item { pub name: String, pub unit_price: FloatMajorUnit, pub description: Option<String>, pub quantity: i64, } #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct ShoppingCart { pub items: Vec<Item>, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, PartialEq, Serialize)] pub struct MultisafepayPaymentsRequest { #[serde(rename = "type")] pub payment_type: Type, pub gateway: Option<Gateway>, pub order_id: String, pub currency: String, pub amount: MinorUnit, pub description: String, pub payment_options: Option<PaymentOptions>, pub customer: Option<Customer>, pub gateway_info: Option<GatewayInfo>, pub delivery: Option<DeliveryObject>, pub checkout_options: Option<CheckoutOptions>, pub shopping_cart: Option<ShoppingCart>, pub items: Option<String>, pub recurring_model: Option<MandateType>, pub recurring_id: Option<Secret<String>>, pub capture: Option<String>, pub days_active: Option<i32>, pub seconds_active: Option<i32>, pub var1: Option<String>, pub var2: Option<String>, pub var3: Option<String>, } impl TryFrom<utils::CardIssuer> for Gateway { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> { match issuer { utils::CardIssuer::AmericanExpress => Ok(Self::Amex), utils::CardIssuer::Master => Ok(Self::MasterCard), utils::CardIssuer::Maestro => Ok(Self::Maestro), utils::CardIssuer::Discover => Ok(Self::Discover), utils::CardIssuer::Visa => Ok(Self::Visa), utils::CardIssuer::DinersClub | utils::CardIssuer::JCB | utils::CardIssuer::CarteBlanche | utils::CardIssuer::UnionPay | utils::CardIssuer::CartesBancaires => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Multisafe pay"), ) .into()), } } } impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> for MultisafepayPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let payment_type = match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref _ccard) => Type::Direct, PaymentMethodData::MandatePayment => Type::Direct, PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { WalletData::GooglePay(_) => Type::Direct, WalletData::PaypalRedirect(_) => Type::Redirect, WalletData::AliPayRedirect(_) => Type::Redirect, WalletData::WeChatPayRedirect(_) => Type::Redirect, WalletData::MbWayRedirect(_) => Type::Redirect, WalletData::AliPayQr(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePay(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }, PaymentMethodData::BankRedirect(ref bank_data) => match bank_data { BankRedirectData::Giropay { .. } => Type::Redirect, BankRedirectData::Ideal { .. } => Type::Direct, BankRedirectData::Trustly { .. } => Type::Redirect, BankRedirectData::Eps { .. } => Type::Redirect, BankRedirectData::Sofort { .. } => Type::Redirect, BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::LocalBankRedirect {} => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))? } }, PaymentMethodData::PayLater(ref _paylater) => Type::Redirect, _ => Type::Redirect, }; let gateway = match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref ccard) => { Some(Gateway::try_from(ccard.get_card_issuer()?)?) } PaymentMethodData::Wallet(ref wallet_data) => Some(match wallet_data { WalletData::GooglePay(_) => Gateway::Googlepay, WalletData::PaypalRedirect(_) => Gateway::Paypal, WalletData::AliPayRedirect(_) => Gateway::Alipay, WalletData::WeChatPayRedirect(_) => Gateway::WeChatPay, WalletData::MbWayRedirect(_) => Gateway::MbWay, WalletData::AliPayQr(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePay(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }), PaymentMethodData::BankRedirect(ref bank_data) => Some(match bank_data { BankRedirectData::Giropay { .. } => Gateway::Giropay, BankRedirectData::Ideal { .. } => Gateway::Ideal, BankRedirectData::Trustly { .. } => Gateway::Trustly, BankRedirectData::Eps { .. } => Gateway::Eps, BankRedirectData::Sofort { .. } => Gateway::Sofort, BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::LocalBankRedirect {} => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))? } }), PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect {}) => Some(Gateway::Klarna), PaymentMethodData::MandatePayment => None, PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))? } }; let description = item.router_data.get_description()?; let payment_options = PaymentOptions { notification_url: None, redirect_url: item.router_data.request.get_router_return_url()?, cancel_url: item.router_data.request.get_router_return_url()?, close_window: None, notification_method: None, settings: None, template_id: None, allowed_countries: None, }; let customer = Customer { browser: None, locale: None, ip_address: None, forward_ip: None, first_name: None, last_name: None, gender: None, birthday: None, address1: None, address2: None, house_number: None, zip_code: None, city: None, state: None, country: None, phone: None, email: item.router_data.request.email.clone(), user_agent: None, referrer: None, reference: Some(item.router_data.connector_request_reference_id.clone()), }; let billing_address = item .router_data .get_billing()? .address .as_ref() .ok_or_else(utils::missing_field_err("billing.address"))?; let first_name = billing_address.get_first_name()?; let delivery = DeliveryObject { first_name: first_name.clone(), last_name: billing_address .get_last_name() .unwrap_or(first_name) .clone(), address1: billing_address.get_line1()?.to_owned(), house_number: billing_address.get_line2()?.to_owned(), zip_code: billing_address.get_zip()?.to_owned(), city: billing_address.get_city()?.to_owned(), country: billing_address.get_country()?.to_owned(), }; let gateway_info = match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref ccard) => Some(GatewayInfo::Card(CardInfo { card_number: Some(ccard.card_number.clone()), card_expiry_date: Some(Secret::new( (format!( "{}{}", ccard.get_card_expiry_year_2_digit()?.expose(), ccard.card_exp_month.clone().expose() )) .parse::<i32>() .unwrap_or_default(), )), card_cvc: Some(ccard.card_cvc.clone()), card_holder_name: None, flexible_3d: None, moto: None, term_url: None, })), PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { WalletData::GooglePay(ref google_pay) => { Some(GatewayInfo::Wallet(WalletInfo::GooglePay({ GpayInfo { payment_token: Some(Secret::new( google_pay .tokenization_data .get_encrypted_google_pay_token() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "google_pay_token", })? .clone(), )), } }))) } WalletData::AliPayRedirect(_) => { Some(GatewayInfo::Wallet(WalletInfo::Alipay(AlipayInfo {}))) } WalletData::PaypalRedirect(_) => None, WalletData::WeChatPayRedirect(_) => { Some(GatewayInfo::Wallet(WalletInfo::WeChatPay(WeChatPayInfo {}))) } WalletData::MbWayRedirect(_) => { Some(GatewayInfo::Wallet(WalletInfo::MbWay(MbWayInfo {}))) } WalletData::AliPayQr(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPay(_) | WalletData::AmazonPayRedirect(_) | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::BluecodeRedirect {} | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePay(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MobilePayRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }, PaymentMethodData::PayLater(ref paylater) => { Some(GatewayInfo::PayLater(PayLaterInfo { email: Some(match paylater { PayLaterData::KlarnaRedirect {} => item.router_data.get_billing_email()?, PayLaterData::KlarnaSdk { token: _ } | PayLaterData::AffirmRedirect {} | PayLaterData::FlexitiRedirect {} | PayLaterData::AfterpayClearpayRedirect {} | PayLaterData::PayBrightRedirect {} | PayLaterData::WalleyRedirect {} | PayLaterData::AlmaRedirect {} | PayLaterData::AtomeRedirect {} | PayLaterData::BreadpayRedirect {} => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message( "multisafepay", ), ))? } }), })) } PaymentMethodData::BankRedirect(ref bank_redirect_data) => match bank_redirect_data { BankRedirectData::Ideal { bank_name, .. } => Some(GatewayInfo::BankRedirect( BankRedirectInfo::Ideal(IdealInfo { issuer_id: MultisafepayBankNames::try_from(&bank_name.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "ideal.bank_name", }, )?)?, }), )), BankRedirectData::Trustly { .. } => Some(GatewayInfo::BankRedirect( BankRedirectInfo::Trustly(TrustlyInfo {}), )), BankRedirectData::Eps { .. } => { Some(GatewayInfo::BankRedirect(BankRedirectInfo::Eps(EpsInfo {}))) } BankRedirectData::Sofort { .. } => Some(GatewayInfo::BankRedirect( BankRedirectInfo::Sofort(SofortInfo {}), )), BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } | BankRedirectData::Eft { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::LocalBankRedirect {} => None, }, PaymentMethodData::MandatePayment => None, PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))? } }; Ok(Self { payment_type, gateway, order_id: item.router_data.connector_request_reference_id.to_string(), currency: item.router_data.request.currency.to_string(), amount: item.amount, description, payment_options: Some(payment_options), customer: Some(customer), delivery: Some(delivery), gateway_info, checkout_options: None, shopping_cart: None, capture: None, items: None, recurring_model: if item.router_data.request.is_mandate_payment() { Some(MandateType::Unscheduled) } else { None }, recurring_id: item .router_data .request .mandate_id .clone() .and_then(|mandate_ids| match mandate_ids.mandate_reference_id { Some(api_models::payments::MandateReferenceId::ConnectorMandateId( connector_mandate_ids, )) => connector_mandate_ids .get_connector_mandate_id() .map(Secret::new), _ => None, }), days_active: Some(30), seconds_active: Some(259200), var1: None, var2: None, var3: None, }) } } // Auth Struct pub struct MultisafepayAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for MultisafepayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::HeaderKey { api_key } = auth_type { Ok(Self { api_key: api_key.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } } } // PaymentsResponse #[derive(Debug, Clone, Default, Eq, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum MultisafepayPaymentStatus { Completed, Declined, #[default] Initialized, Void, Uncleared, } #[derive(Debug, Clone, Eq, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum MandateType { Unscheduled, } impl From<MultisafepayPaymentStatus> for AttemptStatus { fn from(item: MultisafepayPaymentStatus) -> Self { match item { MultisafepayPaymentStatus::Completed => Self::Charged, MultisafepayPaymentStatus::Declined => Self::Failure, MultisafepayPaymentStatus::Initialized => Self::AuthenticationPending, MultisafepayPaymentStatus::Uncleared => Self::Pending, MultisafepayPaymentStatus::Void => Self::Voided, } } } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct Data { #[serde(rename = "type")] pub payment_type: Option<String>, pub order_id: String, pub currency: Option<String>, pub amount: Option<MinorUnit>, pub description: Option<String>, pub capture: Option<String>, pub payment_url: Option<Url>, pub status: Option<MultisafepayPaymentStatus>, pub reason: Option<String>, pub reason_code: Option<String>, pub payment_details: Option<MultisafepayPaymentDetails>, } #[derive(Default, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] pub struct MultisafepayPaymentDetails { pub account_holder_name: Option<Secret<String>>, pub account_id: Option<Secret<String>>, pub card_expiry_date: Option<Secret<String>>, pub external_transaction_id: Option<serde_json::Value>, pub last4: Option<Secret<String>>, pub recurring_flow: Option<String>, pub recurring_id: Option<Secret<String>>, pub recurring_model: Option<String>, #[serde(rename = "type")] pub payment_type: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct MultisafepayPaymentsResponse { pub success: bool, pub data: Data, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] #[serde(untagged)] pub enum MultisafepayAuthResponse { ErrorResponse(MultisafepayErrorResponse), PaymentResponse(Box<MultisafepayPaymentsResponse>), } impl<F, T> TryFrom<ResponseRouterData<F, MultisafepayAuthResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<ParsingError>; fn try_from( item: ResponseRouterData<F, MultisafepayAuthResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response { MultisafepayAuthResponse::PaymentResponse(payment_response) => { let redirection_data = payment_response .data .payment_url .clone() .map(|url| RedirectForm::from((url, Method::Get))); let default_status = if payment_response.success { MultisafepayPaymentStatus::Initialized } else { MultisafepayPaymentStatus::Declined }; let status = AttemptStatus::from(payment_response.data.status.unwrap_or(default_status)); Ok(Self { status, response: if utils::is_payment_failure(status) { Err(populate_error_reason( payment_response.data.reason_code, payment_response.data.reason.clone(), payment_response.data.reason, item.http_code, Some(status), Some(payment_response.data.order_id), )) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( payment_response.data.order_id.clone(), ), redirection_data: Box::new(redirection_data), mandate_reference: Box::new( payment_response .data .payment_details .and_then(|payment_details| payment_details.recurring_id) .map(|id| MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }), ), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( payment_response.data.order_id.clone(), ), incremental_authorization_allowed: None, charges: None, }) }, ..item.data }) } MultisafepayAuthResponse::ErrorResponse(error_response) => { let attempt_status = Option::<AttemptStatus>::from(error_response.clone()); Ok(Self { response: Err(populate_error_reason( Some(error_response.error_code.to_string()), Some(error_response.error_info.clone()), Some(error_response.error_info), item.http_code, attempt_status, None, )), ..item.data }) } } } } pub fn populate_error_reason( code: Option<String>, message: Option<String>, reason: Option<String>, http_code: u16, attempt_status: Option<AttemptStatus>, connector_transaction_id: Option<String>, ) -> ErrorResponse { ErrorResponse { code: code.unwrap_or(NO_ERROR_CODE.to_string()), message: message.clone().unwrap_or(NO_ERROR_MESSAGE.to_string()), reason, status_code: http_code, attempt_status, connector_transaction_id, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, } } // REFUND : // Type definition for RefundRequest #[derive(Debug, Serialize)] pub struct MultisafepayRefundRequest { pub currency: enums::Currency, pub amount: MinorUnit, pub description: Option<String>, pub refund_order_id: Option<String>, pub checkout_data: Option<ShoppingCart>, } impl<F> TryFrom<&MultisafepayRouterData<&types::RefundsRouterData<F>>> for MultisafepayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &MultisafepayRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { currency: item.router_data.request.currency, amount: item.amount, description: item.router_data.description.clone(), refund_order_id: Some(item.router_data.request.refund_id.clone()), checkout_data: None, }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundData { pub transaction_id: i64, pub refund_id: i64, pub order_id: Option<String>, pub error_code: Option<i32>, pub error_info: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { pub success: bool, pub data: RefundData, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum MultisafepayRefundResponse { ErrorResponse(MultisafepayErrorResponse), RefundResponse(RefundResponse), } impl TryFrom<RefundsResponseRouterData<Execute, MultisafepayRefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<ParsingError>; fn try_from( item: RefundsResponseRouterData<Execute, MultisafepayRefundResponse>, ) -> Result<Self, Self::Error> { match item.response { MultisafepayRefundResponse::RefundResponse(refund_data) => { let refund_status = if refund_data.success { RefundStatus::Succeeded } else { RefundStatus::Failed }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: refund_data.data.refund_id.to_string(), refund_status: enums::RefundStatus::from(refund_status), }), ..item.data }) } MultisafepayRefundResponse::ErrorResponse(error_response) => { let attempt_status = Option::<AttemptStatus>::from(error_response.clone()); Ok(Self { response: Err(ErrorResponse { code: error_response.error_code.to_string(), message: error_response.error_info.clone(), reason: Some(error_response.error_info), status_code: item.http_code, attempt_status, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } } impl TryFrom<RefundsResponseRouterData<RSync, MultisafepayRefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<ParsingError>; fn try_from( item: RefundsResponseRouterData<RSync, MultisafepayRefundResponse>, ) -> Result<Self, Self::Error> { match item.response { MultisafepayRefundResponse::RefundResponse(refund_data) => { let refund_status = if refund_data.success { RefundStatus::Succeeded } else { RefundStatus::Failed }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: refund_data.data.refund_id.to_string(), refund_status: enums::RefundStatus::from(refund_status), }), ..item.data }) } MultisafepayRefundResponse::ErrorResponse(error_response) => Ok(Self { response: Err(populate_error_reason( Some(error_response.error_code.to_string()), Some(error_response.error_info.clone()), Some(error_response.error_info), item.http_code, None, None, )), ..item.data }), } } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct MultisafepayErrorResponse { pub error_code: i32, pub error_info: String, } impl From<MultisafepayErrorResponse> for Option<AttemptStatus> { fn from(error_data: MultisafepayErrorResponse) -> Self { match error_data.error_code { 10001 // InvalidAmount | 1002 // InvalidCurrency | 1003 // InvalidAccountID | 1004 // InvalidSiteID | 1005 // InvalidSecurityCode | 1006 // InvalidTransactionID | 1007 // InvalidIPAddress | 1008 // InvalidDescription | 1010 // InvalidVariable | 1011 // InvalidCustomerAccountID | 1012 // InvalidCustomerSecurityCode | 1013 // InvalidSignature | 1015 //UnknownAccountID | 1016 // MissingData | 1018 // InvalidCountryCode | 1025 // MultisafepayErrorCodes::IncorrectCustomerIPAddress | 1026 // MultisafepayErrorCodes::MultipleCurrenciesInCart | 1027 // MultisafepayErrorCodes::CartCurrencyDifferentToOrderCurrency | 1028 // IncorrectCustomTaxRate | 1029 // IncorrectItemTaxRate | 1030 // IncorrectItemCurrency | 1031 // IncorrectItemPrice | 1035 // InvalidSignatureRefund | 1036 // InvalidIdealIssuerID | 5001 // CartDataNotValidated | 1032 // InvalidAPIKey => { Some(AttemptStatus::AuthenticationFailed) } 1034 // CannotRefundTransaction | 1022 // CannotInitiateTransaction | 1024 //TransactionDeclined => Some(AttemptStatus::Failure), 1017 // InsufficientFunds => Some(AttemptStatus::AuthorizationFailed), _ => None, } } }
crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
hyperswitch_connectors::src::connectors::multisafepay::transformers
11,142
true
// File: crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs // Module: hyperswitch_connectors::src::connectors::payeezy::transformers use cards::CardNumber; use common_enums::{enums, AttemptStatus, CaptureMethod, Currency, PaymentMethod}; use common_utils::{errors::ParsingError, ext_traits::Encode}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::Execute, router_request_types::ResponseId, router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{api::CurrencyUnit, errors::ConnectorError}; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ get_amount_as_string, get_unimplemented_payment_method_error_message, to_connector_meta, CardData, CardIssuer, RouterData as _, }, }; #[derive(Debug, Serialize)] pub struct PayeezyRouterData<T> { pub amount: String, pub router_data: T, } impl<T> TryFrom<(&CurrencyUnit, Currency, i64, T)> for PayeezyRouterData<T> { type Error = error_stack::Report<ConnectorError>; fn try_from( (currency_unit, currency, amount, router_data): (&CurrencyUnit, Currency, i64, T), ) -> Result<Self, Self::Error> { let amount = get_amount_as_string(currency_unit, amount, currency)?; Ok(Self { amount, router_data, }) } } #[derive(Serialize, Debug)] pub struct PayeezyCard { #[serde(rename = "type")] pub card_type: PayeezyCardType, pub cardholder_name: Secret<String>, pub card_number: CardNumber, pub exp_date: Secret<String>, pub cvv: Secret<String>, } #[derive(Serialize, Debug)] pub enum PayeezyCardType { #[serde(rename = "American Express")] AmericanExpress, Visa, Mastercard, Discover, } impl TryFrom<CardIssuer> for PayeezyCardType { type Error = error_stack::Report<ConnectorError>; fn try_from(issuer: CardIssuer) -> Result<Self, Self::Error> { match issuer { CardIssuer::AmericanExpress => Ok(Self::AmericanExpress), CardIssuer::Master => Ok(Self::Mastercard), CardIssuer::Discover => Ok(Self::Discover), CardIssuer::Visa => Ok(Self::Visa), CardIssuer::Maestro | CardIssuer::DinersClub | CardIssuer::JCB | CardIssuer::CarteBlanche | CardIssuer::UnionPay | CardIssuer::CartesBancaires => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Payeezy"), ))?, } } } #[derive(Serialize, Debug)] #[serde(untagged)] pub enum PayeezyPaymentMethod { PayeezyCard(PayeezyCard), } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum PayeezyPaymentMethodType { CreditCard, } #[derive(Serialize, Debug)] pub struct PayeezyPaymentsRequest { pub merchant_ref: String, pub transaction_type: PayeezyTransactionType, pub method: PayeezyPaymentMethodType, pub amount: String, pub currency_code: String, pub credit_card: PayeezyPaymentMethod, pub stored_credentials: Option<StoredCredentials>, pub reference: String, } #[derive(Serialize, Debug)] pub struct StoredCredentials { pub sequence: Sequence, pub initiator: Initiator, pub is_scheduled: bool, pub cardbrand_original_transaction_id: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum Sequence { First, Subsequent, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum Initiator { Merchant, CardHolder, } impl TryFrom<&PayeezyRouterData<&PaymentsAuthorizeRouterData>> for PayeezyPaymentsRequest { type Error = error_stack::Report<ConnectorError>; fn try_from( item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.payment_method { PaymentMethod::Card => get_card_specific_payment_data(item), PaymentMethod::CardRedirect | PaymentMethod::PayLater | PaymentMethod::Wallet | PaymentMethod::BankRedirect | PaymentMethod::BankTransfer | PaymentMethod::Crypto | PaymentMethod::BankDebit | PaymentMethod::Reward | PaymentMethod::RealTimePayment | PaymentMethod::MobilePayment | PaymentMethod::Upi | PaymentMethod::Voucher | PaymentMethod::OpenBanking | PaymentMethod::GiftCard => { Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()) } } } } fn get_card_specific_payment_data( item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<PayeezyPaymentsRequest, error_stack::Report<ConnectorError>> { let merchant_ref = item.router_data.attempt_id.to_string(); let method = PayeezyPaymentMethodType::CreditCard; let amount = item.amount.clone(); let currency_code = item.router_data.request.currency.to_string(); let credit_card = get_payment_method_data(item)?; let (transaction_type, stored_credentials) = get_transaction_type_and_stored_creds(item.router_data)?; Ok(PayeezyPaymentsRequest { merchant_ref, transaction_type, method, amount, currency_code, credit_card, stored_credentials, reference: item.router_data.connector_request_reference_id.clone(), }) } fn get_transaction_type_and_stored_creds( item: &PaymentsAuthorizeRouterData, ) -> Result<(PayeezyTransactionType, Option<StoredCredentials>), error_stack::Report<ConnectorError>> { let connector_mandate_id = item.request.mandate_id.as_ref().and_then(|mandate_ids| { match mandate_ids.mandate_reference_id.clone() { Some(api_models::payments::MandateReferenceId::ConnectorMandateId( connector_mandate_ids, )) => connector_mandate_ids.get_connector_mandate_id(), _ => None, } }); let (transaction_type, stored_credentials) = if is_mandate_payment(item, connector_mandate_id.as_ref()) { // Mandate payment ( PayeezyTransactionType::Recurring, Some(StoredCredentials { // connector_mandate_id is not present then it is a First payment, else it is a Subsequent mandate payment sequence: match connector_mandate_id.is_some() { true => Sequence::Subsequent, false => Sequence::First, }, // off_session true denotes the customer not present during the checkout process. In other cases customer present at the checkout. initiator: match item.request.off_session { Some(true) => Initiator::Merchant, _ => Initiator::CardHolder, }, is_scheduled: true, // In case of first mandate payment connector_mandate_id would be None, otherwise holds some value cardbrand_original_transaction_id: connector_mandate_id.map(Secret::new), }), ) } else { match item.request.capture_method { Some(CaptureMethod::Manual) => Ok((PayeezyTransactionType::Authorize, None)), Some(CaptureMethod::SequentialAutomatic) | Some(CaptureMethod::Automatic) => { Ok((PayeezyTransactionType::Purchase, None)) } Some(CaptureMethod::ManualMultiple) | Some(CaptureMethod::Scheduled) | None => { Err(ConnectorError::FlowNotSupported { flow: item.request.capture_method.unwrap_or_default().to_string(), connector: "Payeezy".to_string(), }) } }? }; Ok((transaction_type, stored_credentials)) } fn is_mandate_payment( item: &PaymentsAuthorizeRouterData, connector_mandate_id: Option<&String>, ) -> bool { item.request.setup_mandate_details.is_some() || connector_mandate_id.is_some() } fn get_payment_method_data( item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<PayeezyPaymentMethod, error_stack::Report<ConnectorError>> { match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref card) => { let card_type = PayeezyCardType::try_from(card.get_card_issuer()?)?; let payeezy_card = PayeezyCard { card_type, cardholder_name: item .router_data .get_optional_billing_full_name() .unwrap_or(Secret::new("".to_string())), card_number: card.card_number.clone(), exp_date: card.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?, cvv: card.card_cvc.clone(), }; Ok(PayeezyPaymentMethod::PayeezyCard(payeezy_card)) } PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Payeezy"), ))? } } } // Auth Struct pub struct PayeezyAuthType { pub(super) api_key: Secret<String>, pub(super) api_secret: Secret<String>, pub(super) merchant_token: Secret<String>, } impl TryFrom<&ConnectorAuthType> for PayeezyAuthType { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } = item { Ok(Self { api_key: api_key.to_owned(), api_secret: api_secret.to_owned(), merchant_token: key1.to_owned(), }) } else { Err(ConnectorError::FailedToObtainAuthType.into()) } } } // PaymentsResponse #[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum PayeezyPaymentStatus { Approved, Declined, #[default] #[serde(rename = "Not Processed")] NotProcessed, } #[derive(Debug, Deserialize, Serialize)] pub struct PayeezyPaymentsResponse { pub correlation_id: String, pub transaction_status: PayeezyPaymentStatus, pub validation_status: String, pub transaction_type: PayeezyTransactionType, pub transaction_id: String, pub transaction_tag: Option<String>, pub method: Option<String>, pub amount: String, pub currency: String, pub bank_resp_code: String, pub bank_message: String, pub gateway_resp_code: String, pub gateway_message: String, pub stored_credentials: Option<PaymentsStoredCredentials>, pub reference: Option<String>, } #[derive(Debug, Deserialize, Serialize)] pub struct PaymentsStoredCredentials { cardbrand_original_transaction_id: Secret<String>, } #[derive(Debug, Serialize)] pub struct PayeezyCaptureOrVoidRequest { transaction_tag: String, transaction_type: PayeezyTransactionType, amount: String, currency_code: String, } impl TryFrom<&PayeezyRouterData<&PaymentsCaptureRouterData>> for PayeezyCaptureOrVoidRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &PayeezyRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { let metadata: PayeezyPaymentsMetadata = to_connector_meta(item.router_data.request.connector_meta.clone()) .change_context(ConnectorError::RequestEncodingFailed)?; Ok(Self { transaction_type: PayeezyTransactionType::Capture, amount: item.amount.clone(), currency_code: item.router_data.request.currency.to_string(), transaction_tag: metadata.transaction_tag, }) } } impl TryFrom<&PaymentsCancelRouterData> for PayeezyCaptureOrVoidRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let metadata: PayeezyPaymentsMetadata = to_connector_meta(item.request.connector_meta.clone()) .change_context(ConnectorError::RequestEncodingFailed)?; Ok(Self { transaction_type: PayeezyTransactionType::Void, amount: item .request .amount .ok_or(ConnectorError::RequestEncodingFailed)? .to_string(), currency_code: item.request.currency.unwrap_or_default().to_string(), transaction_tag: metadata.transaction_tag, }) } } #[derive(Debug, Deserialize, Serialize, Default)] #[serde(rename_all = "lowercase")] pub enum PayeezyTransactionType { Authorize, Capture, Purchase, Recurring, Void, Refund, #[default] Pending, } #[derive(Debug, Serialize, Deserialize)] pub struct PayeezyPaymentsMetadata { transaction_tag: String, } impl<F, T> TryFrom<ResponseRouterData<F, PayeezyPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, PayeezyPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let metadata = item .response .transaction_tag .map(|txn_tag| construct_payeezy_payments_metadata(txn_tag).encode_to_value()) .transpose() .change_context(ConnectorError::ResponseHandlingFailed)?; let mandate_reference = item .response .stored_credentials .map(|credentials| credentials.cardbrand_original_transaction_id) .map(|id| MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }); let status = get_status( item.response.transaction_status, item.response.transaction_type, ); Ok(Self { status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference), connector_metadata: metadata, network_txn_id: None, connector_response_reference_id: Some( item.response .reference .unwrap_or(item.response.transaction_id), ), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } fn get_status(status: PayeezyPaymentStatus, method: PayeezyTransactionType) -> AttemptStatus { match status { PayeezyPaymentStatus::Approved => match method { PayeezyTransactionType::Authorize => AttemptStatus::Authorized, PayeezyTransactionType::Capture | PayeezyTransactionType::Purchase | PayeezyTransactionType::Recurring => AttemptStatus::Charged, PayeezyTransactionType::Void => AttemptStatus::Voided, PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => { AttemptStatus::Pending } }, PayeezyPaymentStatus::Declined | PayeezyPaymentStatus::NotProcessed => match method { PayeezyTransactionType::Capture => AttemptStatus::CaptureFailed, PayeezyTransactionType::Authorize | PayeezyTransactionType::Purchase | PayeezyTransactionType::Recurring => AttemptStatus::AuthorizationFailed, PayeezyTransactionType::Void => AttemptStatus::VoidFailed, PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => { AttemptStatus::Pending } }, } } // REFUND : // Type definition for RefundRequest #[derive(Debug, Serialize)] pub struct PayeezyRefundRequest { transaction_tag: String, transaction_type: PayeezyTransactionType, amount: String, currency_code: String, } impl<F> TryFrom<&PayeezyRouterData<&RefundsRouterData<F>>> for PayeezyRefundRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &PayeezyRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let metadata: PayeezyPaymentsMetadata = to_connector_meta(item.router_data.request.connector_metadata.clone()) .change_context(ConnectorError::RequestEncodingFailed)?; Ok(Self { transaction_type: PayeezyTransactionType::Refund, amount: item.amount.clone(), currency_code: item.router_data.request.currency.to_string(), transaction_tag: metadata.transaction_tag, }) } } // Type definition for Refund Response #[derive(Debug, Deserialize, Default, Serialize)] #[serde(rename_all = "lowercase")] pub enum RefundStatus { Approved, Declined, #[default] #[serde(rename = "Not Processed")] NotProcessed, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Approved => Self::Success, RefundStatus::Declined => Self::Failure, RefundStatus::NotProcessed => Self::Pending, } } } #[derive(Deserialize, Debug, Serialize)] pub struct RefundResponse { pub correlation_id: String, pub transaction_status: RefundStatus, pub validation_status: String, pub transaction_type: String, pub transaction_id: String, pub transaction_tag: Option<String>, pub method: Option<String>, pub amount: String, pub currency: String, pub bank_resp_code: String, pub bank_message: String, pub gateway_resp_code: String, pub gateway_message: String, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<ParsingError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction_id, refund_status: enums::RefundStatus::from(item.response.transaction_status), }), ..item.data }) } } #[derive(Debug, Deserialize, Serialize)] pub struct Message { pub code: String, pub description: String, } #[derive(Debug, Deserialize, Serialize)] pub struct PayeezyError { pub messages: Vec<Message>, } #[derive(Debug, Deserialize, Serialize)] pub struct PayeezyErrorResponse { pub transaction_status: String, #[serde(rename = "Error")] pub error: PayeezyError, } fn construct_payeezy_payments_metadata(transaction_tag: String) -> PayeezyPaymentsMetadata { PayeezyPaymentsMetadata { transaction_tag } }
crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
hyperswitch_connectors::src::connectors::payeezy::transformers
4,390
true
// File: crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs // Module: hyperswitch_connectors::src::connectors::stripe::transformers use std::{collections::HashMap, fmt::Debug, ops::Deref}; use api_models::{self, enums as api_enums, payments}; use common_enums::{enums, AttemptStatus, PaymentChargeType, StripeChargeType}; use common_types::{ payments::{AcceptanceType, SplitPaymentsRequest}, primitive_wrappers, }; use common_utils::{ collect_missing_value_keys, errors::CustomResult, ext_traits::{ByteSliceExt, Encode, OptionExt as _}, pii::{self, Email}, request::{Method, RequestContent}, types::MinorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{ self, BankRedirectData, Card, CardRedirectData, GiftCardData, GooglePayWalletData, PayLaterData, PaymentMethodData, VoucherData, WalletData, }, router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, ExtendedAuthorizationResponseData, PaymentMethodToken, RouterData, }, router_flow_types::{Execute, RSync}, router_request_types::{ BrowserInformation, ChargeRefundsOptions, DestinationChargeRefund, DirectChargeRefund, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, ResponseId, SplitRefundsRequest, }, router_response_types::{ ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, PreprocessingResponseId, RedirectForm, RefundsResponseData, }, types::{ ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsUpdateMetadataRouterData, RefundsRouterData, SetupMandateRouterData, TokenizationRouterData, }, }; use hyperswitch_interfaces::{consts, errors::ConnectorError}; use masking::{ExposeInterface, Mask, Maskable, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; use time::PrimitiveDateTime; use url::Url; use crate::{ constants::headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT, utils::{ convert_uppercase, deserialize_zero_minor_amount_as_none, ApplePay, RouterData as OtherRouterData, }, }; #[cfg(feature = "payouts")] pub mod connect; #[cfg(feature = "payouts")] pub use self::connect::*; use crate::{ types::{ RefundsResponseRouterData, ResponseRouterData, SubmitEvidenceRouterData, UploadFileRouterData, }, utils::{ get_unimplemented_payment_method_error_message, is_payment_failure, is_refund_failure, PaymentsAuthorizeRequestData, SplitPaymentData, }, }; pub mod auth_headers { pub const STRIPE_API_VERSION: &str = "stripe-version"; pub const STRIPE_VERSION: &str = "2022-11-15"; } trait GetRequestIncrementalAuthorization { fn get_request_incremental_authorization(&self) -> Option<bool>; } impl GetRequestIncrementalAuthorization for PaymentsAuthorizeData { fn get_request_incremental_authorization(&self) -> Option<bool> { Some(self.request_incremental_authorization) } } impl GetRequestIncrementalAuthorization for PaymentsCaptureData { fn get_request_incremental_authorization(&self) -> Option<bool> { None } } impl GetRequestIncrementalAuthorization for PaymentsCancelData { fn get_request_incremental_authorization(&self) -> Option<bool> { None } } pub struct StripeAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for StripeAuthType { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::HeaderKey { api_key } = item { Ok(Self { api_key: api_key.to_owned(), }) } else { Err(ConnectorError::FailedToObtainAuthType.into()) } } } #[derive(Debug, Default, Eq, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] pub enum StripeCaptureMethod { Manual, #[default] Automatic, } impl From<Option<enums::CaptureMethod>> for StripeCaptureMethod { fn from(item: Option<enums::CaptureMethod>) -> Self { match item { Some(p) => match p { enums::CaptureMethod::ManualMultiple => Self::Manual, enums::CaptureMethod::Manual => Self::Manual, enums::CaptureMethod::Automatic | enums::CaptureMethod::SequentialAutomatic => { Self::Automatic } enums::CaptureMethod::Scheduled => Self::Manual, }, None => Self::Automatic, } } } #[derive(Debug, Default, Eq, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] pub enum Auth3ds { #[default] Automatic, Any, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum StripeCardNetwork { CartesBancaires, Mastercard, Visa, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde( rename_all = "snake_case", tag = "mandate_data[customer_acceptance][type]" )] pub enum StripeMandateType { Online { #[serde(rename = "mandate_data[customer_acceptance][online][ip_address]")] ip_address: Secret<String, pii::IpAddress>, #[serde(rename = "mandate_data[customer_acceptance][online][user_agent]")] user_agent: String, }, Offline, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeMandateRequest { #[serde(flatten)] mandate_type: StripeMandateType, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum ExpandableObjects { LatestCharge, Customer, LatestAttempt, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeBrowserInformation { #[serde(rename = "payment_method_data[ip]")] pub ip_address: Option<Secret<String, pii::IpAddress>>, #[serde(rename = "payment_method_data[user_agent]")] pub user_agent: Option<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct PaymentIntentRequest { pub amount: MinorUnit, //amount in cents, hence passed as integer pub currency: String, pub statement_descriptor_suffix: Option<String>, pub statement_descriptor: Option<String>, #[serde(flatten)] pub meta_data: HashMap<String, String>, pub return_url: String, pub confirm: bool, pub payment_method: Option<Secret<String>>, pub customer: Option<Secret<String>>, #[serde(flatten)] pub setup_mandate_details: Option<StripeMandateRequest>, pub description: Option<String>, #[serde(flatten)] pub shipping: Option<StripeShippingAddress>, #[serde(flatten)] pub billing: StripeBillingAddress, #[serde(flatten)] pub payment_data: Option<StripePaymentMethodData>, pub capture_method: StripeCaptureMethod, #[serde(flatten)] pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated pub setup_future_usage: Option<enums::FutureUsage>, pub off_session: Option<bool>, #[serde(rename = "payment_method_types[0]")] pub payment_method_types: Option<StripePaymentMethodType>, #[serde(rename = "expand[0]")] pub expand: Option<ExpandableObjects>, #[serde(flatten)] pub browser_info: Option<StripeBrowserInformation>, #[serde(flatten)] pub charges: Option<IntentCharges>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct IntentCharges { pub application_fee_amount: Option<MinorUnit>, #[serde( rename = "transfer_data[destination]", skip_serializing_if = "Option::is_none" )] pub destination_account_id: Option<String>, } // Field rename is required only in case of serialization as it is passed in the request to the connector. // Deserialization is happening only in case of webhooks, where fields name should be used as defined in the struct. // Whenever adding new fields, Please ensure it doesn't break the webhook flow #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] pub struct StripeMetadata { // merchant_reference_id #[serde(rename(serialize = "metadata[order_id]"))] pub order_id: Option<String>, // to check whether the order_id is refund_id or payment_id // before deployment, order id is set to payment_id in refunds but now it is set as refund_id // it is set as string instead of bool because stripe pass it as string even if we set it as bool #[serde(rename(serialize = "metadata[is_refund_id_as_reference]"))] pub is_refund_id_as_reference: Option<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct SetupIntentRequest { pub confirm: bool, pub usage: Option<enums::FutureUsage>, pub customer: Option<Secret<String>>, pub off_session: Option<bool>, pub return_url: Option<String>, #[serde(flatten)] pub payment_data: StripePaymentMethodData, pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated #[serde(flatten)] pub meta_data: Option<HashMap<String, String>>, #[serde(rename = "payment_method_types[0]")] pub payment_method_types: Option<StripePaymentMethodType>, #[serde(rename = "expand[0]")] pub expand: Option<ExpandableObjects>, #[serde(flatten)] pub browser_info: Option<StripeBrowserInformation>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeCardData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_data[card][number]")] pub payment_method_data_card_number: cards::CardNumber, #[serde(rename = "payment_method_data[card][exp_month]")] pub payment_method_data_card_exp_month: Secret<String>, #[serde(rename = "payment_method_data[card][exp_year]")] pub payment_method_data_card_exp_year: Secret<String>, #[serde(rename = "payment_method_data[card][cvc]")] pub payment_method_data_card_cvc: Option<Secret<String>>, #[serde(rename = "payment_method_options[card][request_three_d_secure]")] pub payment_method_auth_type: Option<Auth3ds>, #[serde(rename = "payment_method_options[card][network]")] pub payment_method_data_card_preferred_network: Option<StripeCardNetwork>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "payment_method_options[card][request_incremental_authorization]")] pub request_incremental_authorization: Option<StripeRequestIncrementalAuthorization>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "payment_method_options[card][request_extended_authorization]")] request_extended_authorization: Option<StripeRequestExtendedAuthorization>, #[serde(rename = "payment_method_options[card][request_overcapture]")] pub request_overcapture: Option<StripeRequestOvercaptureBool>, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum StripeRequestIncrementalAuthorization { IfAvailable, Never, } #[derive(Debug, Eq, PartialEq, Serialize, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripeRequestExtendedAuthorization { IfAvailable, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum StripeRequestOvercaptureBool { IfAvailable, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripePayLaterData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct TokenRequest { #[serde(flatten)] pub token_data: StripePaymentMethodData, } #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeTokenResponse { pub id: Secret<String>, pub object: String, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct CustomerRequest { pub description: Option<String>, pub email: Option<Email>, pub phone: Option<Secret<String>>, pub name: Option<Secret<String>>, pub source: Option<Secret<String>>, } #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeCustomerResponse { pub id: String, pub description: Option<String>, pub email: Option<Email>, pub phone: Option<Secret<String>>, pub name: Option<Secret<String>>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct ChargesRequest { pub amount: MinorUnit, pub currency: String, pub customer: Secret<String>, pub source: Secret<String>, #[serde(flatten)] pub meta_data: Option<HashMap<String, String>>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct ChargesResponse { pub id: String, pub amount: MinorUnit, pub amount_captured: MinorUnit, pub currency: String, pub status: StripePaymentStatus, pub source: StripeSourceResponse, pub failure_code: Option<String>, pub failure_message: Option<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripeBankName { Eps { #[serde(rename = "payment_method_data[eps][bank]")] bank_name: Option<StripeBankNames>, }, Ideal { #[serde(rename = "payment_method_data[ideal][bank]")] ideal_bank_name: Option<StripeBankNames>, }, Przelewy24 { #[serde(rename = "payment_method_data[p24][bank]")] bank_name: Option<StripeBankNames>, }, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripeBankRedirectData { StripeGiropay(Box<StripeGiropay>), StripeIdeal(Box<StripeIdeal>), StripeBancontactCard(Box<StripeBancontactCard>), StripePrezelewy24(Box<StripePrezelewy24>), StripeEps(Box<StripeEps>), StripeBlik(Box<StripeBlik>), StripeOnlineBankingFpx(Box<StripeOnlineBankingFpx>), } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeGiropay { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeIdeal { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_data[ideal][bank]")] ideal_bank_name: Option<StripeBankNames>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeBancontactCard { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripePrezelewy24 { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_data[p24][bank]")] bank_name: Option<StripeBankNames>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeEps { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_data[eps][bank]")] bank_name: Option<StripeBankNames>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeBlik { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[blik][code]")] pub code: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeOnlineBankingFpx { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct AchTransferData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[customer_balance][bank_transfer][type]")] pub bank_transfer_type: StripeCreditTransferTypes, #[serde(rename = "payment_method_types[0]")] pub payment_method_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[customer_balance][funding_type]")] pub balance_funding_type: BankTransferType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct MultibancoTransferData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripeCreditTransferTypes, #[serde(rename = "payment_method_types[0]")] pub payment_method_type: StripeCreditTransferTypes, #[serde(rename = "payment_method_data[billing_details][email]")] pub email: Email, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct BacsBankTransferData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[customer_balance][bank_transfer][type]")] pub bank_transfer_type: BankTransferType, #[serde(rename = "payment_method_options[customer_balance][funding_type]")] pub balance_funding_type: BankTransferType, #[serde(rename = "payment_method_types[0]")] pub payment_method_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct SepaBankTransferData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[customer_balance][bank_transfer][type]")] pub bank_transfer_type: BankTransferType, #[serde(rename = "payment_method_options[customer_balance][funding_type]")] pub balance_funding_type: BankTransferType, #[serde(rename = "payment_method_types[0]")] pub payment_method_type: StripePaymentMethodType, #[serde( rename = "payment_method_options[customer_balance][bank_transfer][eu_bank_transfer][country]" )] pub country: enums::CountryAlpha2, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripeCreditTransferSourceRequest { AchBankTansfer(AchCreditTransferSourceRequest), MultibancoBankTansfer(MultibancoCreditTransferSourceRequest), } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct AchCreditTransferSourceRequest { #[serde(rename = "type")] pub transfer_type: StripeCreditTransferTypes, #[serde(flatten)] pub payment_method_data: AchTransferData, pub currency: enums::Currency, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct MultibancoCreditTransferSourceRequest { #[serde(rename = "type")] pub transfer_type: StripeCreditTransferTypes, #[serde(flatten)] pub payment_method_data: MultibancoTransferData, pub currency: enums::Currency, pub amount: Option<MinorUnit>, #[serde(rename = "redirect[return_url]")] pub return_url: Option<String>, } // Remove untagged when Deserialize is added #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripePaymentMethodData { CardToken(StripeCardToken), Card(StripeCardData), PayLater(StripePayLaterData), Wallet(StripeWallet), BankRedirect(StripeBankRedirectData), BankDebit(StripeBankDebitData), BankTransfer(StripeBankTransferData), } #[derive(Debug, Clone, Default, Eq, PartialEq, Serialize)] pub struct StripeBillingAddressCardToken { #[serde(rename = "billing_details[name]")] pub name: Option<Secret<String>>, #[serde(rename = "billing_details[email]")] pub email: Option<Email>, #[serde(rename = "billing_details[phone]")] pub phone: Option<Secret<String>>, #[serde(rename = "billing_details[address][line1]")] pub address_line1: Option<Secret<String>>, #[serde(rename = "billing_details[address][line2]")] pub address_line2: Option<Secret<String>>, #[serde(rename = "billing_details[address][state]")] pub state: Option<Secret<String>>, #[serde(rename = "billing_details[address][city]")] pub city: Option<String>, } // Struct to call the Stripe tokens API to create a PSP token for the card details provided #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeCardToken { #[serde(rename = "type")] pub payment_method_type: Option<StripePaymentMethodType>, #[serde(rename = "card[number]")] pub token_card_number: cards::CardNumber, #[serde(rename = "card[exp_month]")] pub token_card_exp_month: Secret<String>, #[serde(rename = "card[exp_year]")] pub token_card_exp_year: Secret<String>, #[serde(rename = "card[cvc]")] pub token_card_cvc: Secret<String>, #[serde(flatten)] pub billing: StripeBillingAddressCardToken, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(tag = "payment_method_data[type]")] pub enum BankDebitData { #[serde(rename = "us_bank_account")] Ach { #[serde(rename = "payment_method_data[us_bank_account][account_holder_type]")] account_holder_type: String, #[serde(rename = "payment_method_data[us_bank_account][account_number]")] account_number: Secret<String>, #[serde(rename = "payment_method_data[us_bank_account][routing_number]")] routing_number: Secret<String>, }, #[serde(rename = "sepa_debit")] Sepa { #[serde(rename = "payment_method_data[sepa_debit][iban]")] iban: Secret<String>, }, #[serde(rename = "au_becs_debit")] Becs { #[serde(rename = "payment_method_data[au_becs_debit][account_number]")] account_number: Secret<String>, #[serde(rename = "payment_method_data[au_becs_debit][bsb_number]")] bsb_number: Secret<String>, }, #[serde(rename = "bacs_debit")] Bacs { #[serde(rename = "payment_method_data[bacs_debit][account_number]")] account_number: Secret<String>, #[serde(rename = "payment_method_data[bacs_debit][sort_code]")] sort_code: Secret<String>, }, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeBankDebitData { #[serde(flatten)] pub bank_specific_data: Option<BankDebitData>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct BankTransferData { pub email: Email, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripeBankTransferData { AchBankTransfer(Box<AchTransferData>), SepaBankTransfer(Box<SepaBankTransferData>), BacsBankTransfers(Box<BacsBankTransferData>), MultibancoBankTransfers(Box<MultibancoTransferData>), } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripeWallet { ApplepayToken(StripeApplePay), GooglepayToken(GooglePayToken), ApplepayPayment(ApplepayPayment), AmazonpayPayment(AmazonpayPayment), WechatpayPayment(WechatpayPayment), AlipayPayment(AlipayPayment), Cashapp(CashappPayment), RevolutPay(RevolutpayPayment), ApplePayPredecryptToken(Box<StripeApplePayPredecrypt>), } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeApplePayPredecrypt { #[serde(rename = "card[number]")] number: cards::CardNumber, #[serde(rename = "card[exp_year]")] exp_year: Secret<String>, #[serde(rename = "card[exp_month]")] exp_month: Secret<String>, #[serde(rename = "card[cryptogram]")] cryptogram: Secret<String>, #[serde(rename = "card[eci]")] eci: Option<String>, #[serde(rename = "card[tokenization_method]")] tokenization_method: String, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeApplePay { pub pk_token: Secret<String>, pub pk_token_instrument_name: String, pub pk_token_payment_network: String, pub pk_token_transaction_id: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct GooglePayToken { #[serde(rename = "payment_method_data[type]")] pub payment_type: StripePaymentMethodType, #[serde(rename = "payment_method_data[card][token]")] pub token: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct ApplepayPayment { #[serde(rename = "payment_method_data[card][token]")] pub token: Secret<String>, #[serde(rename = "payment_method_data[type]")] pub payment_method_types: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct AmazonpayPayment { #[serde(rename = "payment_method_data[type]")] pub payment_method_types: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct RevolutpayPayment { #[serde(rename = "payment_method_data[type]")] pub payment_method_types: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct AlipayPayment { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct CashappPayment { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct WechatpayPayment { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[wechat_pay][client]")] pub client: WechatClient, } #[derive(Debug, Eq, PartialEq, Serialize, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum WechatClient { Web, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct GooglepayPayment { #[serde(rename = "payment_method_data[card][token]")] pub token: Secret<String>, #[serde(rename = "payment_method_data[type]")] pub payment_method_types: StripePaymentMethodType, } // All supported payment_method_types in stripe // This enum goes in payment_method_types[] field in stripe request body // https://stripe.com/docs/api/payment_intents/create#create_payment_intent-payment_method_types #[derive(Eq, PartialEq, Serialize, Clone, Debug, Copy)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodType { Affirm, AfterpayClearpay, Alipay, #[serde(rename = "amazon_pay")] AmazonPay, #[serde(rename = "au_becs_debit")] Becs, #[serde(rename = "bacs_debit")] Bacs, Bancontact, Blik, Card, CustomerBalance, Eps, Giropay, Ideal, Klarna, #[serde(rename = "p24")] Przelewy24, #[serde(rename = "sepa_debit")] Sepa, Sofort, #[serde(rename = "us_bank_account")] Ach, #[serde(rename = "wechat_pay")] Wechatpay, #[serde(rename = "cashapp")] Cashapp, RevolutPay, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] #[allow(dead_code)] pub enum StripeCreditTransferTypes { #[serde(rename = "us_bank_transfer")] AchCreditTransfer, Multibanco, Blik, } impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { type Error = error_stack::Report<ConnectorError>; fn try_from(value: enums::PaymentMethodType) -> Result<Self, Self::Error> { match value { enums::PaymentMethodType::Credit => Ok(Self::Card), enums::PaymentMethodType::Debit => Ok(Self::Card), #[cfg(feature = "v2")] enums::PaymentMethodType::Card => Ok(Self::Card), enums::PaymentMethodType::Klarna => Ok(Self::Klarna), enums::PaymentMethodType::Affirm => Ok(Self::Affirm), enums::PaymentMethodType::AfterpayClearpay => Ok(Self::AfterpayClearpay), enums::PaymentMethodType::Eps => Ok(Self::Eps), enums::PaymentMethodType::Giropay => Ok(Self::Giropay), enums::PaymentMethodType::Ideal => Ok(Self::Ideal), enums::PaymentMethodType::Sofort => Ok(Self::Sofort), enums::PaymentMethodType::AmazonPay => Ok(Self::AmazonPay), enums::PaymentMethodType::ApplePay => Ok(Self::Card), enums::PaymentMethodType::Ach => Ok(Self::Ach), enums::PaymentMethodType::Sepa => Ok(Self::Sepa), enums::PaymentMethodType::Becs => Ok(Self::Becs), enums::PaymentMethodType::Bacs => Ok(Self::Bacs), enums::PaymentMethodType::BancontactCard => Ok(Self::Bancontact), enums::PaymentMethodType::WeChatPay => Ok(Self::Wechatpay), enums::PaymentMethodType::Blik => Ok(Self::Blik), enums::PaymentMethodType::AliPay => Ok(Self::Alipay), enums::PaymentMethodType::Przelewy24 => Ok(Self::Przelewy24), enums::PaymentMethodType::RevolutPay => Ok(Self::RevolutPay), // Stripe expects PMT as Card for Recurring Mandates Payments enums::PaymentMethodType::GooglePay => Ok(Self::Card), enums::PaymentMethodType::Boleto | enums::PaymentMethodType::Paysera | enums::PaymentMethodType::Skrill | enums::PaymentMethodType::CardRedirect | enums::PaymentMethodType::CryptoCurrency | enums::PaymentMethodType::Multibanco | enums::PaymentMethodType::OnlineBankingFpx | enums::PaymentMethodType::Paypal | enums::PaymentMethodType::BhnCardNetwork | enums::PaymentMethodType::Pix | enums::PaymentMethodType::UpiCollect | enums::PaymentMethodType::UpiIntent | enums::PaymentMethodType::Cashapp | enums::PaymentMethodType::Bluecode | enums::PaymentMethodType::SepaGuarenteedDebit | enums::PaymentMethodType::Oxxo => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ) .into()), enums::PaymentMethodType::AliPayHk | enums::PaymentMethodType::Atome | enums::PaymentMethodType::Bizum | enums::PaymentMethodType::Alma | enums::PaymentMethodType::ClassicReward | enums::PaymentMethodType::Dana | enums::PaymentMethodType::DirectCarrierBilling | enums::PaymentMethodType::Efecty | enums::PaymentMethodType::Eft | enums::PaymentMethodType::Evoucher | enums::PaymentMethodType::GoPay | enums::PaymentMethodType::Gcash | enums::PaymentMethodType::Interac | enums::PaymentMethodType::KakaoPay | enums::PaymentMethodType::LocalBankRedirect | enums::PaymentMethodType::MbWay | enums::PaymentMethodType::MobilePay | enums::PaymentMethodType::Momo | enums::PaymentMethodType::MomoAtm | enums::PaymentMethodType::OnlineBankingThailand | enums::PaymentMethodType::OnlineBankingCzechRepublic | enums::PaymentMethodType::OnlineBankingFinland | enums::PaymentMethodType::OnlineBankingPoland | enums::PaymentMethodType::OnlineBankingSlovakia | enums::PaymentMethodType::OpenBankingUk | enums::PaymentMethodType::OpenBankingPIS | enums::PaymentMethodType::PagoEfectivo | enums::PaymentMethodType::PayBright | enums::PaymentMethodType::Pse | enums::PaymentMethodType::RedCompra | enums::PaymentMethodType::RedPagos | enums::PaymentMethodType::SamsungPay | enums::PaymentMethodType::Swish | enums::PaymentMethodType::TouchNGo | enums::PaymentMethodType::Trustly | enums::PaymentMethodType::Twint | enums::PaymentMethodType::Vipps | enums::PaymentMethodType::Venmo | enums::PaymentMethodType::Alfamart | enums::PaymentMethodType::BcaBankTransfer | enums::PaymentMethodType::BniVa | enums::PaymentMethodType::CimbVa | enums::PaymentMethodType::BriVa | enums::PaymentMethodType::DanamonVa | enums::PaymentMethodType::Indomaret | enums::PaymentMethodType::MandiriVa | enums::PaymentMethodType::PermataBankTransfer | enums::PaymentMethodType::PaySafeCard | enums::PaymentMethodType::Paze | enums::PaymentMethodType::Givex | enums::PaymentMethodType::Benefit | enums::PaymentMethodType::Knet | enums::PaymentMethodType::SevenEleven | enums::PaymentMethodType::Lawson | enums::PaymentMethodType::MiniStop | enums::PaymentMethodType::FamilyMart | enums::PaymentMethodType::Seicomart | enums::PaymentMethodType::PayEasy | enums::PaymentMethodType::LocalBankTransfer | enums::PaymentMethodType::InstantBankTransfer | enums::PaymentMethodType::InstantBankTransferFinland | enums::PaymentMethodType::InstantBankTransferPoland | enums::PaymentMethodType::SepaBankTransfer | enums::PaymentMethodType::Walley | enums::PaymentMethodType::Fps | enums::PaymentMethodType::DuitNow | enums::PaymentMethodType::PromptPay | enums::PaymentMethodType::VietQr | enums::PaymentMethodType::IndonesianBankTransfer | enums::PaymentMethodType::Flexiti | enums::PaymentMethodType::Mifinity | enums::PaymentMethodType::Breadpay | enums::PaymentMethodType::UpiQr => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ) .into()), } } } #[derive(Debug, Eq, PartialEq, Serialize, Clone)] #[serde(rename_all = "snake_case")] pub enum BankTransferType { GbBankTransfer, EuBankTransfer, #[serde(rename = "bank_transfer")] BankTransfers, } #[derive(Debug, Eq, PartialEq, Serialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripeBankNames { AbnAmro, ArzteUndApothekerBank, AsnBank, AustrianAnadiBankAg, BankAustria, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, Bunq, CapitalBankGraweGruppeAg, CitiHandlowy, Dolomitenbank, EasybankAg, ErsteBankUndSparkassen, Handelsbanken, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, Ing, Knab, MarchfelderBank, OberbankAg, RaiffeisenBankengruppeOsterreich, SchoellerbankAg, SpardaBankWien, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, #[serde(rename = "ideabank")] IdeaBank, #[serde(rename = "envelobank")] EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, } // This is used only for Disputes impl From<WebhookEventStatus> for api_models::webhooks::IncomingWebhookEvent { fn from(value: WebhookEventStatus) -> Self { match value { WebhookEventStatus::WarningNeedsResponse => Self::DisputeOpened, WebhookEventStatus::WarningClosed => Self::DisputeCancelled, WebhookEventStatus::WarningUnderReview => Self::DisputeChallenged, WebhookEventStatus::Won => Self::DisputeWon, WebhookEventStatus::Lost => Self::DisputeLost, WebhookEventStatus::NeedsResponse | WebhookEventStatus::UnderReview | WebhookEventStatus::ChargeRefunded | WebhookEventStatus::Succeeded | WebhookEventStatus::RequiresPaymentMethod | WebhookEventStatus::RequiresConfirmation | WebhookEventStatus::RequiresAction | WebhookEventStatus::Processing | WebhookEventStatus::RequiresCapture | WebhookEventStatus::Canceled | WebhookEventStatus::Chargeable | WebhookEventStatus::Failed | WebhookEventStatus::Unknown => Self::EventNotSupported, } } } impl TryFrom<&enums::BankNames> for StripeBankNames { type Error = ConnectorError; fn try_from(bank: &enums::BankNames) -> Result<Self, Self::Error> { Ok(match bank { enums::BankNames::AbnAmro => Self::AbnAmro, enums::BankNames::ArzteUndApothekerBank => Self::ArzteUndApothekerBank, enums::BankNames::AsnBank => Self::AsnBank, enums::BankNames::AustrianAnadiBankAg => Self::AustrianAnadiBankAg, enums::BankNames::BankAustria => Self::BankAustria, enums::BankNames::BankhausCarlSpangler => Self::BankhausCarlSpangler, enums::BankNames::BankhausSchelhammerUndSchatteraAg => { Self::BankhausSchelhammerUndSchatteraAg } enums::BankNames::BawagPskAg => Self::BawagPskAg, enums::BankNames::BksBankAg => Self::BksBankAg, enums::BankNames::BrullKallmusBankAg => Self::BrullKallmusBankAg, enums::BankNames::BtvVierLanderBank => Self::BtvVierLanderBank, enums::BankNames::Bunq => Self::Bunq, enums::BankNames::CapitalBankGraweGruppeAg => Self::CapitalBankGraweGruppeAg, enums::BankNames::Citi => Self::CitiHandlowy, enums::BankNames::Dolomitenbank => Self::Dolomitenbank, enums::BankNames::EasybankAg => Self::EasybankAg, enums::BankNames::ErsteBankUndSparkassen => Self::ErsteBankUndSparkassen, enums::BankNames::Handelsbanken => Self::Handelsbanken, enums::BankNames::HypoAlpeadriabankInternationalAg => { Self::HypoAlpeadriabankInternationalAg } enums::BankNames::HypoNoeLbFurNiederosterreichUWien => { Self::HypoNoeLbFurNiederosterreichUWien } enums::BankNames::HypoOberosterreichSalzburgSteiermark => { Self::HypoOberosterreichSalzburgSteiermark } enums::BankNames::HypoTirolBankAg => Self::HypoTirolBankAg, enums::BankNames::HypoVorarlbergBankAg => Self::HypoVorarlbergBankAg, enums::BankNames::HypoBankBurgenlandAktiengesellschaft => { Self::HypoBankBurgenlandAktiengesellschaft } enums::BankNames::Ing => Self::Ing, enums::BankNames::Knab => Self::Knab, enums::BankNames::MarchfelderBank => Self::MarchfelderBank, enums::BankNames::OberbankAg => Self::OberbankAg, enums::BankNames::RaiffeisenBankengruppeOsterreich => { Self::RaiffeisenBankengruppeOsterreich } enums::BankNames::Rabobank => Self::Rabobank, enums::BankNames::Regiobank => Self::Regiobank, enums::BankNames::Revolut => Self::Revolut, enums::BankNames::SnsBank => Self::SnsBank, enums::BankNames::TriodosBank => Self::TriodosBank, enums::BankNames::VanLanschot => Self::VanLanschot, enums::BankNames::Moneyou => Self::Moneyou, enums::BankNames::SchoellerbankAg => Self::SchoellerbankAg, enums::BankNames::SpardaBankWien => Self::SpardaBankWien, enums::BankNames::VolksbankGruppe => Self::VolksbankGruppe, enums::BankNames::VolkskreditbankAg => Self::VolkskreditbankAg, enums::BankNames::VrBankBraunau => Self::VrBankBraunau, enums::BankNames::PlusBank => Self::PlusBank, enums::BankNames::EtransferPocztowy24 => Self::EtransferPocztowy24, enums::BankNames::BankiSpbdzielcze => Self::BankiSpbdzielcze, enums::BankNames::BankNowyBfgSa => Self::BankNowyBfgSa, enums::BankNames::GetinBank => Self::GetinBank, enums::BankNames::Blik => Self::Blik, enums::BankNames::NoblePay => Self::NoblePay, enums::BankNames::IdeaBank => Self::IdeaBank, enums::BankNames::EnveloBank => Self::EnveloBank, enums::BankNames::NestPrzelew => Self::NestPrzelew, enums::BankNames::MbankMtransfer => Self::MbankMtransfer, enums::BankNames::Inteligo => Self::Inteligo, enums::BankNames::PbacZIpko => Self::PbacZIpko, enums::BankNames::BnpParibas => Self::BnpParibas, enums::BankNames::BankPekaoSa => Self::BankPekaoSa, enums::BankNames::VolkswagenBank => Self::VolkswagenBank, enums::BankNames::AliorBank => Self::AliorBank, enums::BankNames::Boz => Self::Boz, _ => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ))?, }) } } fn validate_shipping_address_against_payment_method( shipping_address: &Option<StripeShippingAddress>, payment_method: Option<&StripePaymentMethodType>, ) -> Result<(), error_stack::Report<ConnectorError>> { match payment_method { Some(StripePaymentMethodType::AfterpayClearpay) => match shipping_address { Some(address) => { let missing_fields = collect_missing_value_keys!( ("shipping.address.line1", address.line1), ("shipping.address.country", address.country), ("shipping.address.zip", address.zip) ); if !missing_fields.is_empty() { return Err(ConnectorError::MissingRequiredFields { field_names: missing_fields, } .into()); } Ok(()) } None => Err(ConnectorError::MissingRequiredField { field_name: "shipping.address", } .into()), }, _ => Ok(()), } } impl TryFrom<&PayLaterData> for StripePaymentMethodType { type Error = ConnectorError; fn try_from(pay_later_data: &PayLaterData) -> Result<Self, Self::Error> { match pay_later_data { PayLaterData::KlarnaRedirect { .. } => Ok(Self::Klarna), PayLaterData::AffirmRedirect {} => Ok(Self::Affirm), PayLaterData::AfterpayClearpayRedirect { .. } => Ok(Self::AfterpayClearpay), PayLaterData::KlarnaSdk { .. } | PayLaterData::PayBrightRedirect {} | PayLaterData::WalleyRedirect {} | PayLaterData::AlmaRedirect {} | PayLaterData::FlexitiRedirect { .. } | PayLaterData::AtomeRedirect {} | PayLaterData::BreadpayRedirect {} => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), )), } } } impl TryFrom<&BankRedirectData> for StripePaymentMethodType { type Error = ConnectorError; fn try_from(bank_redirect_data: &BankRedirectData) -> Result<Self, Self::Error> { match bank_redirect_data { BankRedirectData::Giropay { .. } => Ok(Self::Giropay), BankRedirectData::Ideal { .. } => Ok(Self::Ideal), BankRedirectData::Sofort { .. } => Ok(Self::Sofort), BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact), BankRedirectData::Przelewy24 { .. } => Ok(Self::Przelewy24), BankRedirectData::Eps { .. } => Ok(Self::Eps), BankRedirectData::Blik { .. } => Ok(Self::Blik), BankRedirectData::OnlineBankingFpx { .. } => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), )), BankRedirectData::Bizum {} | BankRedirectData::Interac { .. } | BankRedirectData::Eft { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::Trustly { .. } | BankRedirectData::LocalBankRedirect {} => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), )), } } } fn get_stripe_payment_method_type_from_wallet_data( wallet_data: &WalletData, ) -> Result<Option<StripePaymentMethodType>, ConnectorError> { match wallet_data { WalletData::AliPayRedirect(_) => Ok(Some(StripePaymentMethodType::Alipay)), WalletData::ApplePay(_) => Ok(None), WalletData::GooglePay(_) => Ok(Some(StripePaymentMethodType::Card)), WalletData::WeChatPayQr(_) => Ok(Some(StripePaymentMethodType::Wechatpay)), WalletData::CashappQr(_) => Ok(Some(StripePaymentMethodType::Cashapp)), WalletData::AmazonPayRedirect(_) => Ok(Some(StripePaymentMethodType::AmazonPay)), WalletData::RevolutPay(_) => Ok(Some(StripePaymentMethodType::RevolutPay)), WalletData::MobilePayRedirect(_) => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), )), WalletData::PaypalRedirect(_) | WalletData::AliPayQr(_) | WalletData::BluecodeRedirect {} | WalletData::Paysera(_) | WalletData::Skrill(_) | WalletData::AmazonPay(_) | WalletData::AliPayHkRedirect(_) | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::SwishQr(_) | WalletData::WeChatPayRedirect(_) | WalletData::Mifinity(_) => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), )), } } impl TryFrom<&payment_method_data::BankDebitData> for StripePaymentMethodType { type Error = ConnectorError; fn try_from(bank_debit_data: &payment_method_data::BankDebitData) -> Result<Self, Self::Error> { match bank_debit_data { payment_method_data::BankDebitData::AchBankDebit { .. } => Ok(Self::Ach), payment_method_data::BankDebitData::SepaBankDebit { .. } => Ok(Self::Sepa), payment_method_data::BankDebitData::BecsBankDebit { .. } => Ok(Self::Becs), payment_method_data::BankDebitData::BacsBankDebit { .. } => Ok(Self::Bacs), payment_method_data::BankDebitData::SepaGuarenteedBankDebit { .. } => { Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), )) } } } } fn get_bank_debit_data( bank_debit_data: &payment_method_data::BankDebitData, ) -> (Option<StripePaymentMethodType>, Option<BankDebitData>) { match bank_debit_data { payment_method_data::BankDebitData::AchBankDebit { account_number, routing_number, .. } => { let ach_data = BankDebitData::Ach { account_holder_type: "individual".to_string(), account_number: account_number.to_owned(), routing_number: routing_number.to_owned(), }; (Some(StripePaymentMethodType::Ach), Some(ach_data)) } payment_method_data::BankDebitData::SepaBankDebit { iban, .. } => { let sepa_data: BankDebitData = BankDebitData::Sepa { iban: iban.to_owned(), }; (Some(StripePaymentMethodType::Sepa), Some(sepa_data)) } payment_method_data::BankDebitData::BecsBankDebit { account_number, bsb_number, .. } => { let becs_data = BankDebitData::Becs { account_number: account_number.to_owned(), bsb_number: bsb_number.to_owned(), }; (Some(StripePaymentMethodType::Becs), Some(becs_data)) } payment_method_data::BankDebitData::BacsBankDebit { account_number, sort_code, .. } => { let bacs_data = BankDebitData::Bacs { account_number: account_number.to_owned(), sort_code: Secret::new(sort_code.clone().expose().replace('-', "")), }; (Some(StripePaymentMethodType::Bacs), Some(bacs_data)) } _ => (None, None), } } pub struct PaymentRequestDetails { pub auth_type: enums::AuthenticationType, pub payment_method_token: Option<PaymentMethodToken>, pub is_customer_initiated_mandate_payment: Option<bool>, pub billing_address: StripeBillingAddress, pub request_incremental_authorization: bool, pub request_extended_authorization: Option<primitive_wrappers::RequestExtendedAuthorizationBool>, pub request_overcapture: Option<StripeRequestOvercaptureBool>, } fn create_stripe_payment_method( payment_method_data: &PaymentMethodData, payment_request_details: PaymentRequestDetails, ) -> Result< ( StripePaymentMethodData, Option<StripePaymentMethodType>, StripeBillingAddress, ), error_stack::Report<ConnectorError>, > { match payment_method_data { PaymentMethodData::Card(card_details) => { let payment_method_auth_type = match payment_request_details.auth_type { enums::AuthenticationType::ThreeDs => Auth3ds::Any, enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, }; Ok(( StripePaymentMethodData::try_from(( card_details, payment_method_auth_type, payment_request_details.request_incremental_authorization, payment_request_details.request_extended_authorization, payment_request_details.request_overcapture, ))?, Some(StripePaymentMethodType::Card), payment_request_details.billing_address, )) } PaymentMethodData::PayLater(pay_later_data) => { let stripe_pm_type = StripePaymentMethodType::try_from(pay_later_data)?; Ok(( StripePaymentMethodData::PayLater(StripePayLaterData { payment_method_data_type: stripe_pm_type, }), Some(stripe_pm_type), payment_request_details.billing_address, )) } PaymentMethodData::BankRedirect(bank_redirect_data) => { let billing_address = if payment_request_details.is_customer_initiated_mandate_payment == Some(true) { mandatory_parameters_for_sepa_bank_debit_mandates( &Some(payment_request_details.billing_address.to_owned()), payment_request_details.is_customer_initiated_mandate_payment, )? } else { payment_request_details.billing_address }; let pm_type = StripePaymentMethodType::try_from(bank_redirect_data)?; let bank_redirect_data = StripePaymentMethodData::try_from(bank_redirect_data)?; Ok((bank_redirect_data, Some(pm_type), billing_address)) } PaymentMethodData::Wallet(wallet_data) => { let pm_type = get_stripe_payment_method_type_from_wallet_data(wallet_data)?; let wallet_specific_data = StripePaymentMethodData::try_from(( wallet_data, payment_request_details.payment_method_token, ))?; Ok(( wallet_specific_data, pm_type, StripeBillingAddress::default(), )) } PaymentMethodData::BankDebit(bank_debit_data) => { let (pm_type, bank_debit_data) = get_bank_debit_data(bank_debit_data); let pm_data = StripePaymentMethodData::BankDebit(StripeBankDebitData { bank_specific_data: bank_debit_data, }); Ok((pm_data, pm_type, payment_request_details.billing_address)) } PaymentMethodData::BankTransfer(bank_transfer_data) => match bank_transfer_data.deref() { payment_method_data::BankTransferData::AchBankTransfer {} => Ok(( StripePaymentMethodData::BankTransfer(StripeBankTransferData::AchBankTransfer( Box::new(AchTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: StripeCreditTransferTypes::AchCreditTransfer, payment_method_type: StripePaymentMethodType::CustomerBalance, balance_funding_type: BankTransferType::BankTransfers, }), )), None, StripeBillingAddress::default(), )), payment_method_data::BankTransferData::MultibancoBankTransfer {} => Ok(( StripePaymentMethodData::BankTransfer( StripeBankTransferData::MultibancoBankTransfers(Box::new( MultibancoTransferData { payment_method_data_type: StripeCreditTransferTypes::Multibanco, payment_method_type: StripeCreditTransferTypes::Multibanco, email: payment_request_details.billing_address.email.ok_or( ConnectorError::MissingRequiredField { field_name: "billing_address.email", }, )?, }, )), ), None, StripeBillingAddress::default(), )), payment_method_data::BankTransferData::SepaBankTransfer {} => Ok(( StripePaymentMethodData::BankTransfer(StripeBankTransferData::SepaBankTransfer( Box::new(SepaBankTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: BankTransferType::EuBankTransfer, balance_funding_type: BankTransferType::BankTransfers, payment_method_type: StripePaymentMethodType::CustomerBalance, country: payment_request_details.billing_address.country.ok_or( ConnectorError::MissingRequiredField { field_name: "billing_address.country", }, )?, }), )), Some(StripePaymentMethodType::CustomerBalance), payment_request_details.billing_address, )), payment_method_data::BankTransferData::BacsBankTransfer {} => Ok(( StripePaymentMethodData::BankTransfer(StripeBankTransferData::BacsBankTransfers( Box::new(BacsBankTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: BankTransferType::GbBankTransfer, balance_funding_type: BankTransferType::BankTransfers, payment_method_type: StripePaymentMethodType::CustomerBalance, }), )), Some(StripePaymentMethodType::CustomerBalance), payment_request_details.billing_address, )), payment_method_data::BankTransferData::Pix { .. } => Err( ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( "stripe", )) .into(), ), payment_method_data::BankTransferData::Pse {} | payment_method_data::BankTransferData::LocalBankTransfer { .. } | payment_method_data::BankTransferData::InstantBankTransfer {} | payment_method_data::BankTransferData::InstantBankTransferFinland { .. } | payment_method_data::BankTransferData::InstantBankTransferPoland { .. } | payment_method_data::BankTransferData::PermataBankTransfer { .. } | payment_method_data::BankTransferData::BcaBankTransfer { .. } | payment_method_data::BankTransferData::BniVaBankTransfer { .. } | payment_method_data::BankTransferData::BriVaBankTransfer { .. } | payment_method_data::BankTransferData::CimbVaBankTransfer { .. } | payment_method_data::BankTransferData::DanamonVaBankTransfer { .. } | payment_method_data::BankTransferData::IndonesianBankTransfer { .. } | payment_method_data::BankTransferData::MandiriVaBankTransfer { .. } => Err( ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( "stripe", )) .into(), ), }, PaymentMethodData::Crypto(_) => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ) .into()), PaymentMethodData::GiftCard(giftcard_data) => match giftcard_data.deref() { GiftCardData::Givex(_) | GiftCardData::PaySafeCard {} | GiftCardData::BhnCardNetwork(_) => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ) .into()), }, PaymentMethodData::CardRedirect(cardredirect_data) => match cardredirect_data { CardRedirectData::Knet {} | CardRedirectData::Benefit {} | CardRedirectData::MomoAtm {} | CardRedirectData::CardRedirect {} => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ) .into()), }, PaymentMethodData::Reward => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ) .into()), PaymentMethodData::Voucher(voucher_data) => match voucher_data { VoucherData::Boleto(_) | VoucherData::Oxxo => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ) .into()), VoucherData::Alfamart(_) | VoucherData::Efecty | VoucherData::PagoEfectivo | VoucherData::RedCompra | VoucherData::RedPagos | VoucherData::Indomaret(_) | VoucherData::SevenEleven(_) | VoucherData::Lawson(_) | VoucherData::MiniStop(_) | VoucherData::FamilyMart(_) | VoucherData::Seicomart(_) | VoucherData::PayEasy(_) => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ) .into()), }, PaymentMethodData::Upi(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Err( ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( "stripe", )) .into(), ), } } fn get_stripe_card_network(card_network: common_enums::CardNetwork) -> Option<StripeCardNetwork> { match card_network { common_enums::CardNetwork::Visa => Some(StripeCardNetwork::Visa), common_enums::CardNetwork::Mastercard => Some(StripeCardNetwork::Mastercard), common_enums::CardNetwork::CartesBancaires => Some(StripeCardNetwork::CartesBancaires), common_enums::CardNetwork::AmericanExpress | common_enums::CardNetwork::JCB | common_enums::CardNetwork::DinersClub | common_enums::CardNetwork::Discover | common_enums::CardNetwork::UnionPay | common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay | common_enums::CardNetwork::Maestro | common_enums::CardNetwork::Star | common_enums::CardNetwork::Accel | common_enums::CardNetwork::Pulse | common_enums::CardNetwork::Nyce => None, } } impl TryFrom<( &Card, Auth3ds, bool, Option<primitive_wrappers::RequestExtendedAuthorizationBool>, Option<StripeRequestOvercaptureBool>, )> for StripePaymentMethodData { type Error = ConnectorError; fn try_from( ( card, payment_method_auth_type, request_incremental_authorization, request_extended_authorization, request_overcapture, ): ( &Card, Auth3ds, bool, Option<primitive_wrappers::RequestExtendedAuthorizationBool>, Option<StripeRequestOvercaptureBool>, ), ) -> Result<Self, Self::Error> { Ok(Self::Card(StripeCardData { payment_method_data_type: StripePaymentMethodType::Card, payment_method_data_card_number: card.card_number.clone(), payment_method_data_card_exp_month: card.card_exp_month.clone(), payment_method_data_card_exp_year: card.card_exp_year.clone(), payment_method_data_card_cvc: Some(card.card_cvc.clone()), payment_method_auth_type: Some(payment_method_auth_type), payment_method_data_card_preferred_network: card .card_network .clone() .and_then(get_stripe_card_network), request_incremental_authorization: if request_incremental_authorization { Some(StripeRequestIncrementalAuthorization::IfAvailable) } else { None }, request_extended_authorization: if request_extended_authorization .map(|request_extended_authorization| request_extended_authorization.is_true()) .unwrap_or(false) { Some(StripeRequestExtendedAuthorization::IfAvailable) } else { None }, request_overcapture, })) } } impl TryFrom<(&WalletData, Option<PaymentMethodToken>)> for StripePaymentMethodData { type Error = error_stack::Report<ConnectorError>; fn try_from( (wallet_data, payment_method_token): (&WalletData, Option<PaymentMethodToken>), ) -> Result<Self, Self::Error> { match wallet_data { WalletData::ApplePay(applepay_data) => { let mut apple_pay_decrypt_data = if let Some(PaymentMethodToken::ApplePayDecrypt(decrypt_data)) = payment_method_token { let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year(); Some(Self::Wallet(StripeWallet::ApplePayPredecryptToken( Box::new(StripeApplePayPredecrypt { number: decrypt_data.clone().application_primary_account_number, exp_year: expiry_year_4_digit, exp_month: decrypt_data.application_expiration_month, eci: decrypt_data.payment_data.eci_indicator, cryptogram: decrypt_data.payment_data.online_payment_cryptogram, tokenization_method: "apple_pay".to_string(), }), ))) } else { None }; if apple_pay_decrypt_data.is_none() { apple_pay_decrypt_data = Some(Self::Wallet(StripeWallet::ApplepayToken(StripeApplePay { pk_token: applepay_data.get_applepay_decoded_payment_data()?, pk_token_instrument_name: applepay_data .payment_method .pm_type .to_owned(), pk_token_payment_network: applepay_data .payment_method .network .to_owned(), pk_token_transaction_id: Secret::new( applepay_data.transaction_identifier.to_owned(), ), }))); }; let pmd = apple_pay_decrypt_data.ok_or(ConnectorError::MissingApplePayTokenData)?; Ok(pmd) } WalletData::WeChatPayQr(_) => Ok(Self::Wallet(StripeWallet::WechatpayPayment( WechatpayPayment { client: WechatClient::Web, payment_method_data_type: StripePaymentMethodType::Wechatpay, }, ))), WalletData::AliPayRedirect(_) => { Ok(Self::Wallet(StripeWallet::AlipayPayment(AlipayPayment { payment_method_data_type: StripePaymentMethodType::Alipay, }))) } WalletData::CashappQr(_) => Ok(Self::Wallet(StripeWallet::Cashapp(CashappPayment { payment_method_data_type: StripePaymentMethodType::Cashapp, }))), WalletData::AmazonPayRedirect(_) => Ok(Self::Wallet(StripeWallet::AmazonpayPayment( AmazonpayPayment { payment_method_types: StripePaymentMethodType::AmazonPay, }, ))), WalletData::RevolutPay(_) => { Ok(Self::Wallet(StripeWallet::RevolutPay(RevolutpayPayment { payment_method_types: StripePaymentMethodType::RevolutPay, }))) } WalletData::GooglePay(gpay_data) => Ok(Self::try_from(gpay_data)?), WalletData::PaypalRedirect(_) | WalletData::MobilePayRedirect(_) => Err( ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( "stripe", )) .into(), ), WalletData::AliPayQr(_) | WalletData::Paysera(_) | WalletData::BluecodeRedirect {} | WalletData::Skrill(_) | WalletData::AmazonPay(_) | WalletData::AliPayHkRedirect(_) | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) | WalletData::GcashRedirect(_) | WalletData::ApplePayRedirect(_) | WalletData::ApplePayThirdPartySdk(_) | WalletData::DanaRedirect {} | WalletData::GooglePayRedirect(_) | WalletData::GooglePayThirdPartySdk(_) | WalletData::MbWayRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) | WalletData::SwishQr(_) | WalletData::WeChatPayRedirect(_) | WalletData::Mifinity(_) => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ) .into()), } } } impl TryFrom<&BankRedirectData> for StripePaymentMethodData { type Error = error_stack::Report<ConnectorError>; fn try_from(bank_redirect_data: &BankRedirectData) -> Result<Self, Self::Error> { let payment_method_data_type = StripePaymentMethodType::try_from(bank_redirect_data)?; match bank_redirect_data { BankRedirectData::BancontactCard { .. } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeBancontactCard(Box::new(StripeBancontactCard { payment_method_data_type, })), )), BankRedirectData::Blik { blik_code } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeBlik(Box::new(StripeBlik { payment_method_data_type, code: Secret::new(blik_code.clone().ok_or( ConnectorError::MissingRequiredField { field_name: "blik_code", }, )?), })), )), BankRedirectData::Eps { bank_name, .. } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeEps(Box::new(StripeEps { payment_method_data_type, bank_name: bank_name .map(|bank_name| StripeBankNames::try_from(&bank_name)) .transpose()?, })), )), BankRedirectData::Giropay { .. } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeGiropay(Box::new(StripeGiropay { payment_method_data_type, })), )), BankRedirectData::Ideal { bank_name, .. } => { let bank_name = bank_name .map(|bank_name| StripeBankNames::try_from(&bank_name)) .transpose()?; Ok(Self::BankRedirect(StripeBankRedirectData::StripeIdeal( Box::new(StripeIdeal { payment_method_data_type, ideal_bank_name: bank_name, }), ))) } BankRedirectData::Przelewy24 { bank_name, .. } => { let bank_name = bank_name .map(|bank_name| StripeBankNames::try_from(&bank_name)) .transpose()?; Ok(Self::BankRedirect( StripeBankRedirectData::StripePrezelewy24(Box::new(StripePrezelewy24 { payment_method_data_type, bank_name, })), )) } BankRedirectData::OnlineBankingFpx { .. } => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ) .into()), BankRedirectData::Bizum {} | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } | BankRedirectData::OnlineBankingPoland { .. } | BankRedirectData::OnlineBankingSlovakia { .. } | BankRedirectData::OnlineBankingThailand { .. } | BankRedirectData::OpenBankingUk { .. } | BankRedirectData::Sofort { .. } | BankRedirectData::Trustly { .. } | BankRedirectData::LocalBankRedirect {} => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ) .into()), } } } impl TryFrom<&GooglePayWalletData> for StripePaymentMethodData { type Error = error_stack::Report<ConnectorError>; fn try_from(gpay_data: &GooglePayWalletData) -> Result<Self, Self::Error> { Ok(Self::Wallet(StripeWallet::GooglepayToken(GooglePayToken { token: Secret::new( gpay_data .tokenization_data .get_encrypted_google_pay_token() .change_context(ConnectorError::MissingRequiredField { field_name: "gpay wallet_token", })? .as_bytes() .parse_struct::<StripeGpayToken>("StripeGpayToken") .change_context(ConnectorError::InvalidWalletToken { wallet_name: "Google Pay".to_string(), })? .id, ), payment_type: StripePaymentMethodType::Card, }))) } } impl TryFrom<(&PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntentRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(data: (&PaymentsAuthorizeRouterData, MinorUnit)) -> Result<Self, Self::Error> { let item = data.0; let mandate_metadata = item .request .mandate_id .as_ref() .and_then(|mandate_id| mandate_id.mandate_reference_id.as_ref()) .and_then(|reference_id| match reference_id { payments::MandateReferenceId::ConnectorMandateId(mandate_data) => { Some(mandate_data.get_mandate_metadata()) } _ => None, }); let (transfer_account_id, charge_type, application_fees) = if let Some(secret_value) = mandate_metadata.as_ref().and_then(|s| s.as_ref()) { let json_value = secret_value.clone().expose(); let parsed: Result<StripeSplitPaymentRequest, _> = serde_json::from_value(json_value); match parsed { Ok(data) => ( data.transfer_account_id, data.charge_type, data.application_fees, ), Err(_) => (None, None, None), } } else { (None, None, None) }; let payment_method_token = match &item.request.split_payments { Some(SplitPaymentsRequest::StripeSplitPayment(_)) => { match item.payment_method_token.clone() { Some(PaymentMethodToken::Token(secret)) => Some(secret), _ => None, } } _ => None, }; let amount = data.1; let order_id = item.connector_request_reference_id.clone(); let shipping_address = if payment_method_token.is_some() { None } else { Some(StripeShippingAddress { city: item.get_optional_shipping_city(), country: item.get_optional_shipping_country(), line1: item.get_optional_shipping_line1(), line2: item.get_optional_shipping_line2(), zip: item.get_optional_shipping_zip(), state: item.get_optional_shipping_state(), name: item.get_optional_shipping_full_name(), phone: item.get_optional_shipping_phone_number(), }) }; let billing_address = if payment_method_token.is_some() { None } else { Some(StripeBillingAddress { city: item.get_optional_billing_city(), country: item.get_optional_billing_country(), address_line1: item.get_optional_billing_line1(), address_line2: item.get_optional_billing_line2(), zip_code: item.get_optional_billing_zip(), state: item.get_optional_billing_state(), name: item.get_optional_billing_full_name(), email: item.get_optional_billing_email(), phone: item.get_optional_billing_phone_number(), }) }; let mut payment_method_options = None; let ( mut payment_data, payment_method, billing_address, payment_method_types, setup_future_usage, ) = if payment_method_token.is_some() { (None, None, StripeBillingAddress::default(), None, None) } else { match item .request .mandate_id .clone() .and_then(|mandate_ids| mandate_ids.mandate_reference_id) { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => ( None, connector_mandate_ids.get_connector_mandate_id(), StripeBillingAddress::default(), get_payment_method_type_for_saved_payment_method_payment(item)?, None, ), Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => { payment_method_options = Some(StripePaymentMethodOptions::Card { mandate_options: None, network_transaction_id: None, mit_exemption: Some(MitExemption { network_transaction_id: Secret::new(network_transaction_id), }), }); let payment_data = match item.request.payment_method_data { PaymentMethodData::CardDetailsForNetworkTransactionId( ref card_details_for_network_transaction_id, ) => StripePaymentMethodData::Card(StripeCardData { payment_method_data_type: StripePaymentMethodType::Card, payment_method_data_card_number: card_details_for_network_transaction_id.card_number.clone(), payment_method_data_card_exp_month: card_details_for_network_transaction_id .card_exp_month .clone(), payment_method_data_card_exp_year: card_details_for_network_transaction_id .card_exp_year .clone(), payment_method_data_card_cvc: None, payment_method_auth_type: None, payment_method_data_card_preferred_network: card_details_for_network_transaction_id .card_network .clone() .and_then(get_stripe_card_network), request_incremental_authorization: None, request_extended_authorization: None, request_overcapture: None, }), PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::Card(_) => Err(ConnectorError::NotSupported { message: "Network tokenization for payment method".to_string(), connector: "Stripe", })?, }; ( Some(payment_data), None, StripeBillingAddress::default(), None, None, ) } Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) | None => { let (payment_method_data, payment_method_type, billing_address) = create_stripe_payment_method( &item.request.payment_method_data, PaymentRequestDetails { auth_type : item.auth_type, payment_method_token: item.payment_method_token.clone(), is_customer_initiated_mandate_payment: Some( PaymentsAuthorizeRequestData::is_customer_initiated_mandate_payment( &item.request, ), ), billing_address: billing_address.ok_or_else(|| { ConnectorError::MissingRequiredField { field_name: "billing_address", } })?, request_incremental_authorization: item.request.request_incremental_authorization, request_extended_authorization: item.request.request_extended_authorization, request_overcapture: item.request .enable_overcapture .and_then(get_stripe_overcapture_request), })?; validate_shipping_address_against_payment_method( &shipping_address, payment_method_type.as_ref(), )?; ( Some(payment_method_data), None, billing_address, payment_method_type, item.request.setup_future_usage, ) } } }; if payment_method_token.is_none() { payment_data = match item.request.payment_method_data { PaymentMethodData::Wallet(WalletData::ApplePay(_)) => { let payment_method_token = item .payment_method_token .to_owned() .get_required_value("payment_token") .change_context(ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })?; let payment_method_token = match payment_method_token { PaymentMethodToken::Token(payment_method_token) => payment_method_token, PaymentMethodToken::ApplePayDecrypt(_) => { Err(ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })? } PaymentMethodToken::PazeDecrypt(_) => { Err(crate::unimplemented_payment_method!("Paze", "Stripe"))? } PaymentMethodToken::GooglePayDecrypt(_) => { Err(crate::unimplemented_payment_method!("Google Pay", "Stripe"))? } }; Some(StripePaymentMethodData::Wallet( StripeWallet::ApplepayPayment(ApplepayPayment { token: payment_method_token, payment_method_types: StripePaymentMethodType::Card, }), )) } _ => payment_data, } } else { payment_data = None }; let setup_mandate_details = item .request .setup_mandate_details .as_ref() .and_then(|mandate_details| { mandate_details .customer_acceptance .as_ref() .map(|customer_acceptance| { Ok::<_, error_stack::Report<ConnectorError>>( match customer_acceptance.acceptance_type { AcceptanceType::Online => { let online_mandate = customer_acceptance .online .clone() .get_required_value("online") .change_context(ConnectorError::MissingRequiredField { field_name: "online", })?; StripeMandateRequest { mandate_type: StripeMandateType::Online { ip_address: online_mandate .ip_address .get_required_value("ip_address") .change_context( ConnectorError::MissingRequiredField { field_name: "ip_address", }, )?, user_agent: online_mandate.user_agent, }, } } AcceptanceType::Offline => StripeMandateRequest { mandate_type: StripeMandateType::Offline, }, }, ) }) }) .transpose()? .or_else(|| { //stripe requires us to send mandate_data while making recurring payment through saved bank debit if payment_method.is_some() { //check if payment is done through saved payment method match &payment_method_types { //check if payment method is bank debit Some( StripePaymentMethodType::Ach | StripePaymentMethodType::Sepa | StripePaymentMethodType::Becs | StripePaymentMethodType::Bacs, ) => Some(StripeMandateRequest { mandate_type: StripeMandateType::Offline, }), _ => None, } } else { None } }); let meta_data = get_transaction_metadata(item.request.metadata.clone().map(Into::into), order_id); // We pass browser_info only when payment_data exists. // Hence, we're pass Null during recurring payments as payment_method_data[type] is not passed let browser_info = if payment_data.is_some() && payment_method_token.is_none() { item.request .browser_info .clone() .map(StripeBrowserInformation::from) } else { None }; let charges = match &item.request.split_payments { Some(SplitPaymentsRequest::StripeSplitPayment(stripe_split_payment)) => { match &stripe_split_payment.charge_type { PaymentChargeType::Stripe(charge_type) => match charge_type { StripeChargeType::Direct => Some(IntentCharges { application_fee_amount: stripe_split_payment.application_fees, destination_account_id: None, }), StripeChargeType::Destination => Some(IntentCharges { application_fee_amount: stripe_split_payment.application_fees, destination_account_id: Some( stripe_split_payment.transfer_account_id.clone(), ), }), }, } } Some(SplitPaymentsRequest::AdyenSplitPayment(_)) | Some(SplitPaymentsRequest::XenditSplitPayment(_)) | None => None, }; let charges_in = if charges.is_none() { match charge_type { Some(PaymentChargeType::Stripe(StripeChargeType::Direct)) => Some(IntentCharges { application_fee_amount: application_fees, // default to 0 if None destination_account_id: None, }), Some(PaymentChargeType::Stripe(StripeChargeType::Destination)) => { Some(IntentCharges { application_fee_amount: application_fees, destination_account_id: transfer_account_id, }) } _ => None, } } else { charges }; let pm = match (payment_method, payment_method_token.clone()) { (Some(method), _) => Some(Secret::new(method)), (None, Some(token)) => Some(token), (None, None) => None, }; Ok(Self { amount, //hopefully we don't loose some cents here currency: item.request.currency.to_string(), //we need to copy the value and not transfer ownership statement_descriptor_suffix: item.request.statement_descriptor_suffix.clone(), statement_descriptor: item.request.statement_descriptor.clone(), meta_data, return_url: item .request .router_return_url .clone() .unwrap_or_else(|| "https://juspay.in/".to_string()), confirm: true, // Stripe requires confirm to be true if return URL is present description: item.description.clone(), shipping: shipping_address, billing: billing_address, capture_method: StripeCaptureMethod::from(item.request.capture_method), payment_data, payment_method_options, payment_method: pm, customer: item.connector_customer.clone().map(Secret::new), setup_mandate_details, off_session: item.request.off_session, setup_future_usage: match ( item.request.split_payments.as_ref(), item.request.setup_future_usage, item.request.customer_acceptance.as_ref(), ) { (Some(_), Some(usage), Some(_)) => Some(usage), _ => setup_future_usage, }, payment_method_types, expand: Some(ExpandableObjects::LatestCharge), browser_info, charges: charges_in, }) } } fn get_stripe_overcapture_request( enable_overcapture: primitive_wrappers::EnableOvercaptureBool, ) -> Option<StripeRequestOvercaptureBool> { match enable_overcapture.deref() { true => Some(StripeRequestOvercaptureBool::IfAvailable), false => None, } } fn get_payment_method_type_for_saved_payment_method_payment( item: &PaymentsAuthorizeRouterData, ) -> Result<Option<StripePaymentMethodType>, error_stack::Report<ConnectorError>> { if item.payment_method == api_enums::PaymentMethod::Card { Ok(Some(StripePaymentMethodType::Card)) //stripe takes ["Card"] as default } else { let stripe_payment_method_type = match item.recurring_mandate_payment_data.clone() { Some(recurring_payment_method_data) => { match recurring_payment_method_data.payment_method_type { Some(payment_method_type) => { StripePaymentMethodType::try_from(payment_method_type) } None => Err(ConnectorError::MissingRequiredField { field_name: "payment_method_type", } .into()), } } None => Err(ConnectorError::MissingRequiredField { field_name: "recurring_mandate_payment_data", } .into()), }?; match stripe_payment_method_type { //Stripe converts Ideal, Bancontact & Sofort Bank redirect methods to Sepa direct debit and attaches to the customer for future usage StripePaymentMethodType::Ideal | StripePaymentMethodType::Bancontact | StripePaymentMethodType::Sofort => Ok(Some(StripePaymentMethodType::Sepa)), _ => Ok(Some(stripe_payment_method_type)), } } } impl From<BrowserInformation> for StripeBrowserInformation { fn from(item: BrowserInformation) -> Self { Self { ip_address: item.ip_address.map(|ip| Secret::new(ip.to_string())), user_agent: item.user_agent, } } } impl TryFrom<&SetupMandateRouterData> for SetupIntentRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> { //Only cards supported for mandates let pm_type = StripePaymentMethodType::Card; let payment_data = StripePaymentMethodData::try_from((item, item.auth_type, pm_type))?; let meta_data = Some(get_transaction_metadata( item.request.metadata.clone(), item.connector_request_reference_id.clone(), )); let browser_info = item .request .browser_info .clone() .map(StripeBrowserInformation::from); Ok(Self { confirm: true, payment_data, return_url: item.request.router_return_url.clone(), off_session: item.request.off_session, usage: item.request.setup_future_usage, payment_method_options: None, customer: item.connector_customer.to_owned().map(Secret::new), meta_data, payment_method_types: Some(pm_type), expand: Some(ExpandableObjects::LatestAttempt), browser_info, }) } } impl TryFrom<&TokenizationRouterData> for TokenRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> { let billing_address = StripeBillingAddressCardToken { name: item.get_optional_billing_full_name(), email: item.get_optional_billing_email(), phone: item.get_optional_billing_phone_number(), address_line1: item.get_optional_billing_line1(), address_line2: item.get_optional_billing_line2(), city: item.get_optional_billing_city(), state: item.get_optional_billing_state(), }; // Card flow for tokenization is handled separately because of API contact difference let request_payment_data = match &item.request.payment_method_data { PaymentMethodData::Card(card_details) => { StripePaymentMethodData::CardToken(StripeCardToken { payment_method_type: Some(StripePaymentMethodType::Card), token_card_number: card_details.card_number.clone(), token_card_exp_month: card_details.card_exp_month.clone(), token_card_exp_year: card_details.card_exp_year.clone(), token_card_cvc: card_details.card_cvc.clone(), billing: billing_address, }) } _ => { create_stripe_payment_method( &item.request.payment_method_data, PaymentRequestDetails { auth_type: item.auth_type, payment_method_token: item.payment_method_token.clone(), is_customer_initiated_mandate_payment: None, billing_address: StripeBillingAddress::default(), request_incremental_authorization: false, request_extended_authorization: None, request_overcapture: None, }, )? .0 } }; Ok(Self { token_data: request_payment_data, }) } } impl TryFrom<&ConnectorCustomerRouterData> for CustomerRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &ConnectorCustomerRouterData) -> Result<Self, Self::Error> { Ok(Self { description: item.request.description.to_owned(), email: item.request.email.to_owned(), phone: item.request.phone.to_owned(), name: item.request.name.to_owned(), source: item.request.preprocessing_id.to_owned().map(Secret::new), }) } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct StripeSplitPaymentRequest { pub charge_type: Option<PaymentChargeType>, pub application_fees: Option<MinorUnit>, pub transfer_account_id: Option<String>, } impl TryFrom<&PaymentsAuthorizeRouterData> for StripeSplitPaymentRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { //extracting mandate metadata from CIT call if CIT call was a Split Payment let from_metadata = item .request .mandate_id .as_ref() .and_then(|mandate_id| mandate_id.mandate_reference_id.as_ref()) .and_then(|reference_id| match reference_id { payments::MandateReferenceId::ConnectorMandateId(mandate_data) => { mandate_data.get_mandate_metadata() } _ => None, }) .and_then(|secret_value| { let json_value = secret_value.clone().expose(); match serde_json::from_value::<Self>(json_value.clone()) { Ok(val) => Some(val), Err(err) => { router_env::logger::info!( "STRIPE: Picking merchant_account_id and merchant_config_currency from payments request: {:?}", err ); None } } }); // If the Split Payment Request in MIT mismatches with the metadata from CIT, throw an error if from_metadata.is_some() && item.request.split_payments.is_some() { let mut mit_charge_type = None; let mut mit_application_fees = None; let mut mit_transfer_account_id = None; if let Some(SplitPaymentsRequest::StripeSplitPayment(stripe_split_payment)) = item.request.split_payments.as_ref() { mit_charge_type = Some(stripe_split_payment.charge_type.clone()); mit_application_fees = stripe_split_payment.application_fees; mit_transfer_account_id = Some(stripe_split_payment.transfer_account_id.clone()); } if mit_charge_type != from_metadata.as_ref().and_then(|m| m.charge_type.clone()) || mit_application_fees != from_metadata.as_ref().and_then(|m| m.application_fees) || mit_transfer_account_id != from_metadata .as_ref() .and_then(|m| m.transfer_account_id.clone()) { let mismatched_fields = ["transfer_account_id", "application_fees", "charge_type"]; let field_str = mismatched_fields.join(", "); return Err(error_stack::Report::from( ConnectorError::MandatePaymentDataMismatch { fields: field_str }, )); } } // If Mandate Metadata from CIT call has something, populate it let (charge_type, mut transfer_account_id, application_fees) = if let Some(ref metadata) = from_metadata { ( metadata.charge_type.clone(), metadata.transfer_account_id.clone(), metadata.application_fees, ) } else { (None, None, None) }; // If Charge Type is Destination, transfer_account_id need not be appended in headers if charge_type == Some(PaymentChargeType::Stripe(StripeChargeType::Destination)) { transfer_account_id = None; } Ok(Self { charge_type, transfer_account_id, application_fees, }) } } #[derive(Debug, Serialize)] pub struct StripeIncrementalAuthRequest { pub amount: MinorUnit, } #[derive(Clone, Default, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum StripePaymentStatus { Succeeded, Failed, #[default] Processing, #[serde(rename = "requires_action")] RequiresCustomerAction, #[serde(rename = "requires_payment_method")] RequiresPaymentMethod, RequiresConfirmation, Canceled, RequiresCapture, Chargeable, Consumed, Pending, } impl From<StripePaymentStatus> for AttemptStatus { fn from(item: StripePaymentStatus) -> Self { match item { StripePaymentStatus::Succeeded => Self::Charged, StripePaymentStatus::Failed => Self::Failure, StripePaymentStatus::Processing => Self::Authorizing, StripePaymentStatus::RequiresCustomerAction => Self::AuthenticationPending, // Make the payment attempt status as failed StripePaymentStatus::RequiresPaymentMethod => Self::Failure, StripePaymentStatus::RequiresConfirmation => Self::ConfirmationAwaited, StripePaymentStatus::Canceled => Self::Voided, StripePaymentStatus::RequiresCapture => Self::Authorized, StripePaymentStatus::Chargeable => Self::Authorizing, StripePaymentStatus::Consumed => Self::Authorizing, StripePaymentStatus::Pending => Self::Pending, } } } #[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct PaymentIntentResponse { pub id: String, pub object: String, pub amount: MinorUnit, #[serde(default, deserialize_with = "deserialize_zero_minor_amount_as_none")] // stripe gives amount_captured as 0 for payment intents instead of null pub amount_received: Option<MinorUnit>, pub amount_capturable: Option<MinorUnit>, pub currency: String, pub status: StripePaymentStatus, pub client_secret: Option<Secret<String>>, pub created: i32, pub customer: Option<Secret<String>>, pub payment_method: Option<Secret<String>>, pub description: Option<String>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, pub metadata: StripeMetadata, pub next_action: Option<StripeNextActionResponse>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub last_payment_error: Option<ErrorDetails>, pub latest_attempt: Option<LatestAttempt>, //need a merchant to test this pub latest_charge: Option<StripeChargeEnum>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeSourceResponse { pub id: String, #[serde(skip_serializing_if = "Option::is_none")] pub ach_credit_transfer: Option<AchCreditTransferResponse>, #[serde(skip_serializing_if = "Option::is_none")] pub multibanco: Option<MultibancoCreditTansferResponse>, pub receiver: AchReceiverDetails, pub status: StripePaymentStatus, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct AchCreditTransferResponse { pub account_number: Secret<String>, pub bank_name: Secret<String>, pub routing_number: Secret<String>, pub swift_code: Secret<String>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct MultibancoCreditTansferResponse { pub reference: Secret<String>, pub entity: Secret<String>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct AchReceiverDetails { pub amount_received: MinorUnit, pub amount_charged: MinorUnit, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct SepaAndBacsBankTransferInstructions { pub bacs_bank_instructions: Option<BacsFinancialDetails>, pub sepa_bank_instructions: Option<SepaFinancialDetails>, pub receiver: SepaAndBacsReceiver, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Serialize)] pub struct QrCodeNextInstructions { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct SepaAndBacsReceiver { pub amount_received: MinorUnit, pub amount_remaining: MinorUnit, } #[derive(Debug, Default, Eq, PartialEq, Deserialize)] pub struct PaymentSyncResponse { #[serde(flatten)] pub intent_fields: PaymentIntentResponse, pub last_payment_error: Option<ErrorDetails>, } impl Deref for PaymentSyncResponse { type Target = PaymentIntentResponse; fn deref(&self) -> &Self::Target { &self.intent_fields } } #[derive(Deserialize, Debug, Serialize)] pub struct PaymentIntentSyncResponse { #[serde(flatten)] payment_intent_fields: PaymentIntentResponse, pub latest_charge: Option<StripeChargeEnum>, } #[derive(Debug, Eq, PartialEq, Deserialize, Clone, Serialize)] #[serde(untagged)] pub enum StripeChargeEnum { ChargeId(String), ChargeObject(Box<StripeCharge>), } impl StripeChargeEnum { pub fn get_overcapture_status(&self) -> Option<primitive_wrappers::OvercaptureEnabledBool> { match self { Self::ChargeObject(charge_object) => charge_object .payment_method_details .as_ref() .and_then(|payment_method_details| match payment_method_details { StripePaymentMethodDetailsResponse::Card { card } => card .overcapture .as_ref() .and_then(|overcapture| match overcapture.status { Some(StripeOvercaptureStatus::Available) => { Some(primitive_wrappers::OvercaptureEnabledBool::new(true)) } Some(StripeOvercaptureStatus::Unavailable) => { Some(primitive_wrappers::OvercaptureEnabledBool::new(false)) } None => None, }), _ => None, }), _ => None, } } pub fn get_maximum_capturable_amount(&self) -> Option<MinorUnit> { match self { Self::ChargeObject(charge_object) => { if let Some(payment_method_details) = charge_object.payment_method_details.as_ref() { match payment_method_details { StripePaymentMethodDetailsResponse::Card { card } => card .overcapture .as_ref() .and_then(|overcapture| overcapture.maximum_amount_capturable), _ => None, } } else { None } } _ => None, } } } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] pub struct StripeCharge { pub id: String, pub payment_method_details: Option<StripePaymentMethodDetailsResponse>, } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] pub struct StripeBankRedirectDetails { #[serde(rename = "generated_sepa_debit")] attached_payment_method: Option<Secret<String>>, } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] pub struct StripeCashappDetails { buyer_id: Option<String>, cashtag: Option<String>, } impl Deref for PaymentIntentSyncResponse { type Target = PaymentIntentResponse; fn deref(&self) -> &Self::Target { &self.payment_intent_fields } } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] pub struct StripeAdditionalCardDetails { checks: Option<Value>, three_d_secure: Option<Value>, network_transaction_id: Option<String>, extended_authorization: Option<StripeExtendedAuthorizationResponse>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] capture_before: Option<PrimitiveDateTime>, overcapture: Option<StripeOvercaptureResponse>, } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] pub struct StripeExtendedAuthorizationResponse { status: Option<StripeExtendedAuthorizationStatus>, } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "lowercase")] pub enum StripeExtendedAuthorizationStatus { Disabled, Enabled, } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] pub struct StripeOvercaptureResponse { status: Option<StripeOvercaptureStatus>, #[serde(default, deserialize_with = "deserialize_zero_minor_amount_as_none")] // stripe gives amount_captured as 0 for payment intents instead of null maximum_amount_capturable: Option<MinorUnit>, } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum StripeOvercaptureStatus { Available, Unavailable, } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case", tag = "type")] pub enum StripePaymentMethodDetailsResponse { //only ideal and bancontact is supported by stripe for recurring payment in bank redirect Ideal { ideal: StripeBankRedirectDetails, }, Bancontact { bancontact: StripeBankRedirectDetails, }, //other payment method types supported by stripe. To avoid deserialization error. Blik, Eps, Fpx, Giropay, #[serde(rename = "p24")] Przelewy24, Card { card: StripeAdditionalCardDetails, }, Cashapp { cashapp: StripeCashappDetails, }, Klarna, Affirm, AfterpayClearpay, AmazonPay, ApplePay, #[serde(rename = "us_bank_account")] Ach, #[serde(rename = "sepa_debit")] Sepa, #[serde(rename = "au_becs_debit")] Becs, #[serde(rename = "bacs_debit")] Bacs, #[serde(rename = "wechat_pay")] Wechatpay, Alipay, CustomerBalance, RevolutPay, } pub struct AdditionalPaymentMethodDetails { pub payment_checks: Option<Value>, pub authentication_details: Option<Value>, pub extended_authorization: Option<StripeExtendedAuthorizationResponse>, pub capture_before: Option<PrimitiveDateTime>, } impl From<&AdditionalPaymentMethodDetails> for AdditionalPaymentMethodConnectorResponse { fn from(item: &AdditionalPaymentMethodDetails) -> Self { Self::Card { authentication_data: item.authentication_details.clone(), payment_checks: item.payment_checks.clone(), card_network: None, domestic_network: None, } } } impl From<&AdditionalPaymentMethodDetails> for ExtendedAuthorizationResponseData { fn from(item: &AdditionalPaymentMethodDetails) -> Self { Self { extended_authentication_applied: item.extended_authorization.as_ref().map( |extended_authorization| { primitive_wrappers::ExtendedAuthorizationAppliedBool::from(matches!( extended_authorization.status, Some(StripeExtendedAuthorizationStatus::Enabled) )) }, ), capture_before: item.capture_before, } } } impl StripePaymentMethodDetailsResponse { pub fn get_additional_payment_method_data(&self) -> Option<AdditionalPaymentMethodDetails> { match self { Self::Card { card } => Some(AdditionalPaymentMethodDetails { payment_checks: card.checks.clone(), authentication_details: card.three_d_secure.clone(), extended_authorization: card.extended_authorization.clone(), capture_before: card.capture_before, }), Self::Ideal { .. } | Self::Bancontact { .. } | Self::Blik | Self::Eps | Self::Fpx | Self::Giropay | Self::Przelewy24 | Self::Klarna | Self::Affirm | Self::AfterpayClearpay | Self::AmazonPay | Self::ApplePay | Self::Ach | Self::Sepa | Self::Becs | Self::Bacs | Self::Wechatpay | Self::Alipay | Self::CustomerBalance | Self::RevolutPay | Self::Cashapp { .. } => None, } } } #[derive(Deserialize)] pub struct SetupIntentSyncResponse { #[serde(flatten)] setup_intent_fields: SetupIntentResponse, } impl Deref for SetupIntentSyncResponse { type Target = SetupIntentResponse; fn deref(&self) -> &Self::Target { &self.setup_intent_fields } } impl From<SetupIntentSyncResponse> for PaymentIntentSyncResponse { fn from(value: SetupIntentSyncResponse) -> Self { Self { payment_intent_fields: value.setup_intent_fields.into(), latest_charge: None, } } } impl From<SetupIntentResponse> for PaymentIntentResponse { fn from(value: SetupIntentResponse) -> Self { Self { id: value.id, object: value.object, status: value.status, client_secret: Some(value.client_secret), customer: value.customer, description: None, statement_descriptor: value.statement_descriptor, statement_descriptor_suffix: value.statement_descriptor_suffix, metadata: value.metadata, next_action: value.next_action, payment_method_options: value.payment_method_options, last_payment_error: value.last_setup_error, ..Default::default() } } } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct SetupIntentResponse { pub id: String, pub object: String, pub status: StripePaymentStatus, // Change to SetupStatus pub client_secret: Secret<String>, pub customer: Option<Secret<String>>, pub payment_method: Option<String>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, pub metadata: StripeMetadata, pub next_action: Option<StripeNextActionResponse>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub latest_attempt: Option<LatestAttempt>, pub last_setup_error: Option<ErrorDetails>, } fn extract_payment_method_connector_response_from_latest_charge( stripe_charge_enum: &StripeChargeEnum, ) -> Option<ConnectorResponseData> { let is_overcapture_enabled = stripe_charge_enum.get_overcapture_status(); let additional_payment_method_details = if let StripeChargeEnum::ChargeObject(charge_object) = stripe_charge_enum { charge_object .payment_method_details .as_ref() .and_then(StripePaymentMethodDetailsResponse::get_additional_payment_method_data) } else { None }; let additional_payment_method_data = additional_payment_method_details .as_ref() .map(AdditionalPaymentMethodConnectorResponse::from); let extended_authorization_data = additional_payment_method_details .as_ref() .map(ExtendedAuthorizationResponseData::from); if additional_payment_method_data.is_some() || extended_authorization_data.is_some() || is_overcapture_enabled.is_some() { Some(ConnectorResponseData::new( additional_payment_method_data, is_overcapture_enabled, extended_authorization_data, )) } else { None } } fn extract_payment_method_connector_response_from_latest_attempt( stripe_latest_attempt: &LatestAttempt, ) -> Option<ConnectorResponseData> { if let LatestAttempt::PaymentIntentAttempt(intent_attempt) = stripe_latest_attempt { intent_attempt .payment_method_details .as_ref() .and_then(StripePaymentMethodDetailsResponse::get_additional_payment_method_data) } else { None } .as_ref() .map(AdditionalPaymentMethodConnectorResponse::from) .map(ConnectorResponseData::with_additional_payment_method_data) } impl<F, T> TryFrom<ResponseRouterData<F, PaymentIntentResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> where T: SplitPaymentData + GetRequestIncrementalAuthorization, { type Error = error_stack::Report<ConnectorError>; fn try_from( // item: ResponseRouterData<F, PaymentIntentResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirect_data = item.response.next_action.clone(); let redirection_data = redirect_data .and_then(|redirection_data| redirection_data.get_url()) .map(|redirection_url| RedirectForm::from((redirection_url, Method::Get))); let mandate_reference = item.response.payment_method.map(|payment_method_id| { // Implemented Save and re-use payment information for recurring charges // For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value let connector_mandate_id = Some(payment_method_id.clone().expose()); let payment_method_id = Some(payment_method_id.expose()); let mandate_metadata: Option<Secret<Value>> = match item.data.request.get_split_payment_data() { Some(SplitPaymentsRequest::StripeSplitPayment(stripe_split_data)) => { Some(Secret::new(serde_json::json!({ "transfer_account_id": stripe_split_data.transfer_account_id, "charge_type": stripe_split_data.charge_type, "application_fees": stripe_split_data.application_fees, }))) } _ => None, }; MandateReference { connector_mandate_id, payment_method_id, mandate_metadata, connector_mandate_request_reference_id: None, } }); //Note: we might have to call retrieve_setup_intent to get the network_transaction_id in case its not sent in PaymentIntentResponse // Or we identify the mandate txns before hand and always call SetupIntent in case of mandate payment call let network_txn_id = match item.response.latest_charge.as_ref() { Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object .payment_method_details .as_ref() .and_then(|payment_method_details| match payment_method_details { StripePaymentMethodDetailsResponse::Card { card } => { card.network_transaction_id.clone() } _ => None, }), _ => None, }; let connector_metadata = get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?; let status = AttemptStatus::from(item.response.status); let response = if is_payment_failure(status) { *get_stripe_payments_response_data( &item.response.last_payment_error, item.http_code, item.response.id.clone(), ) } else { let charges = item .response .latest_charge .as_ref() .map(|charge| match charge { StripeChargeEnum::ChargeId(charges) => charges.clone(), StripeChargeEnum::ChargeObject(charge) => charge.id.clone(), }) .and_then(|charge_id| construct_charge_response(charge_id, &item.data.request)); Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata, network_txn_id, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: item .data .request .get_request_incremental_authorization(), charges, }) }; let connector_response_data = item .response .latest_charge .as_ref() .and_then(extract_payment_method_connector_response_from_latest_charge); let minor_amount_capturable = item .response .latest_charge .as_ref() .and_then(StripeChargeEnum::get_maximum_capturable_amount); Ok(Self { status, /* Commented out fields: client_secret: Some(item.response.client_secret.clone().as_str()), description: item.response.description.map(|x| x.as_str()), statement_descriptor_suffix: item.response.statement_descriptor_suffix.map(|x| x.as_str()), three_ds_form, */ response, amount_captured: item .response .amount_received .map(|amount| amount.get_amount_as_i64()), minor_amount_captured: item.response.amount_received, connector_response: connector_response_data, minor_amount_capturable, ..item.data }) } } impl From<StripePaymentStatus> for common_enums::AuthorizationStatus { fn from(item: StripePaymentStatus) -> Self { match item { StripePaymentStatus::Succeeded | StripePaymentStatus::RequiresCapture | StripePaymentStatus::Chargeable | StripePaymentStatus::RequiresCustomerAction | StripePaymentStatus::RequiresConfirmation | StripePaymentStatus::Consumed => Self::Success, StripePaymentStatus::Processing | StripePaymentStatus::Pending => Self::Processing, StripePaymentStatus::Failed | StripePaymentStatus::Canceled | StripePaymentStatus::RequiresPaymentMethod => Self::Failure, } } } impl<F> TryFrom< ResponseRouterData< F, PaymentIntentResponse, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >, > for RouterData<F, PaymentsIncrementalAuthorizationData, PaymentsResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData< F, PaymentIntentResponse, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let status = common_enums::AuthorizationStatus::from(item.response.status); Ok(Self { response: Ok(PaymentsResponseData::IncrementalAuthorizationResponse { status, error_code: None, error_message: None, connector_authorization_id: Some(item.response.id), }), ..item.data }) } } pub fn get_connector_metadata( next_action: Option<&StripeNextActionResponse>, amount: MinorUnit, ) -> CustomResult<Option<Value>, ConnectorError> { let next_action_response = next_action .and_then(|next_action_response| match next_action_response { StripeNextActionResponse::DisplayBankTransferInstructions(response) => { match response.financial_addresses.clone() { FinancialInformation::StripeFinancialInformation(financial_addresses) => { let bank_instructions = financial_addresses.first(); let (sepa_bank_instructions, bacs_bank_instructions) = bank_instructions .map_or((None, None), |financial_address| { ( financial_address.iban.to_owned().map( |sepa_financial_details| SepaFinancialDetails { account_holder_name: sepa_financial_details .account_holder_name, bic: sepa_financial_details.bic, country: sepa_financial_details.country, iban: sepa_financial_details.iban, reference: response.reference.to_owned(), }, ), financial_address.sort_code.to_owned(), ) }); let bank_transfer_instructions = SepaAndBacsBankTransferInstructions { sepa_bank_instructions, bacs_bank_instructions, receiver: SepaAndBacsReceiver { amount_received: amount - response.amount_remaining, amount_remaining: response.amount_remaining, }, }; Some(bank_transfer_instructions.encode_to_value()) } FinancialInformation::AchFinancialInformation(financial_addresses) => { let mut ach_financial_information = HashMap::new(); for address in financial_addresses { match address.financial_details { AchFinancialDetails::Aba(aba_details) => { ach_financial_information .insert("account_number", aba_details.account_number); ach_financial_information .insert("bank_name", aba_details.bank_name); ach_financial_information .insert("routing_number", aba_details.routing_number); } AchFinancialDetails::Swift(swift_details) => { ach_financial_information .insert("swift_code", swift_details.swift_code); } } } let ach_financial_information_value = serde_json::to_value(ach_financial_information).ok()?; let ach_transfer_instruction = serde_json::from_value::<payments::AchTransfer>( ach_financial_information_value, ) .ok()?; let bank_transfer_instructions = payments::BankTransferNextStepsData { bank_transfer_instructions: payments::BankTransferInstructions::AchCreditTransfer(Box::new( ach_transfer_instruction, )), receiver: None, }; Some(bank_transfer_instructions.encode_to_value()) } } } StripeNextActionResponse::WechatPayDisplayQrCode(response) => { let wechat_pay_instructions = QrCodeNextInstructions { image_data_url: response.image_data_url.to_owned(), display_to_timestamp: None, }; Some(wechat_pay_instructions.encode_to_value()) } StripeNextActionResponse::CashappHandleRedirectOrDisplayQrCode(response) => { let cashapp_qr_instructions: QrCodeNextInstructions = QrCodeNextInstructions { image_data_url: response.qr_code.image_url_png.to_owned(), display_to_timestamp: response.qr_code.expires_at.to_owned(), }; Some(cashapp_qr_instructions.encode_to_value()) } StripeNextActionResponse::MultibancoDisplayDetails(response) => { let multibanco_bank_transfer_instructions = payments::BankTransferNextStepsData { bank_transfer_instructions: payments::BankTransferInstructions::Multibanco( Box::new(payments::MultibancoTransferInstructions { reference: response.clone().reference, entity: response.clone().entity.expose(), }), ), receiver: None, }; Some(multibanco_bank_transfer_instructions.encode_to_value()) } _ => None, }) .transpose() .change_context(ConnectorError::ResponseHandlingFailed)?; Ok(next_action_response) } pub fn get_payment_method_id( latest_charge: Option<StripeChargeEnum>, payment_method_id_from_intent_root: Secret<String>, ) -> String { match latest_charge { Some(StripeChargeEnum::ChargeObject(charge)) => match charge.payment_method_details { Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => bancontact .attached_payment_method .map(|attached_payment_method| attached_payment_method.expose()) .unwrap_or(payment_method_id_from_intent_root.expose()), Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => ideal .attached_payment_method .map(|attached_payment_method| attached_payment_method.expose()) .unwrap_or(payment_method_id_from_intent_root.expose()), Some(StripePaymentMethodDetailsResponse::Blik) | Some(StripePaymentMethodDetailsResponse::Eps) | Some(StripePaymentMethodDetailsResponse::Fpx) | Some(StripePaymentMethodDetailsResponse::Giropay) | Some(StripePaymentMethodDetailsResponse::Przelewy24) | Some(StripePaymentMethodDetailsResponse::Card { .. }) | Some(StripePaymentMethodDetailsResponse::Klarna) | Some(StripePaymentMethodDetailsResponse::Affirm) | Some(StripePaymentMethodDetailsResponse::AfterpayClearpay) | Some(StripePaymentMethodDetailsResponse::AmazonPay) | Some(StripePaymentMethodDetailsResponse::ApplePay) | Some(StripePaymentMethodDetailsResponse::Ach) | Some(StripePaymentMethodDetailsResponse::Sepa) | Some(StripePaymentMethodDetailsResponse::Becs) | Some(StripePaymentMethodDetailsResponse::Bacs) | Some(StripePaymentMethodDetailsResponse::Wechatpay) | Some(StripePaymentMethodDetailsResponse::Alipay) | Some(StripePaymentMethodDetailsResponse::CustomerBalance) | Some(StripePaymentMethodDetailsResponse::Cashapp { .. }) | Some(StripePaymentMethodDetailsResponse::RevolutPay) | None => payment_method_id_from_intent_root.expose(), }, Some(StripeChargeEnum::ChargeId(_)) | None => payment_method_id_from_intent_root.expose(), } } impl<F, T> TryFrom<ResponseRouterData<F, PaymentIntentSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> where T: SplitPaymentData, { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, PaymentIntentSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirect_data = item.response.next_action.clone(); let redirection_data = redirect_data .and_then(|redirection_data| redirection_data.get_url()) .map(|redirection_url| RedirectForm::from((redirection_url, Method::Get))); let mandate_reference = item .response .payment_method .clone() .map(|payment_method_id| { // Implemented Save and re-use payment information for recurring charges // For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value let payment_method_id = get_payment_method_id(item.response.latest_charge.clone(), payment_method_id); MandateReference { connector_mandate_id: Some(payment_method_id.clone()), payment_method_id: Some(payment_method_id), mandate_metadata: None, connector_mandate_request_reference_id: None, } }); let connector_metadata = get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?; let status = AttemptStatus::from(item.response.status.to_owned()); let connector_response_data = item .response .latest_charge .as_ref() .and_then(extract_payment_method_connector_response_from_latest_charge); let response = if is_payment_failure(status) { *get_stripe_payments_response_data( &item.response.payment_intent_fields.last_payment_error, item.http_code, item.response.id.clone(), ) } else { let network_transaction_id = match item.response.latest_charge.clone() { Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object .payment_method_details .and_then(|payment_method_details| match payment_method_details { StripePaymentMethodDetailsResponse::Card { card } => { card.network_transaction_id } _ => None, }), _ => None, }; let charges = item .response .latest_charge .as_ref() .map(|charge| match charge { StripeChargeEnum::ChargeId(charges) => charges.clone(), StripeChargeEnum::ChargeObject(charge) => charge.id.clone(), }) .and_then(|charge_id| construct_charge_response(charge_id, &item.data.request)); Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata, network_txn_id: network_transaction_id, connector_response_reference_id: Some(item.response.id.clone()), incremental_authorization_allowed: None, charges, }) }; Ok(Self { status: AttemptStatus::from(item.response.status.to_owned()), response, amount_captured: item .response .amount_received .map(|amount| amount.get_amount_as_i64()), minor_amount_captured: item.response.amount_received, connector_response: connector_response_data, ..item.data }) } } impl<F, T> TryFrom<ResponseRouterData<F, SetupIntentResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, SetupIntentResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirect_data = item.response.next_action.clone(); let redirection_data = redirect_data .and_then(|redirection_data| redirection_data.get_url()) .map(|redirection_url| RedirectForm::from((redirection_url, Method::Get))); let mandate_reference = item.response.payment_method.map(|payment_method_id| { // Implemented Save and re-use payment information for recurring charges // For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value let connector_mandate_id = Some(payment_method_id.clone()); let payment_method_id = Some(payment_method_id); MandateReference { connector_mandate_id, payment_method_id, mandate_metadata: None, connector_mandate_request_reference_id: None, } }); let status = AttemptStatus::from(item.response.status); let connector_response_data = item .response .latest_attempt .as_ref() .and_then(extract_payment_method_connector_response_from_latest_attempt); let response = if is_payment_failure(status) { *get_stripe_payments_response_data( &item.response.last_setup_error, item.http_code, item.response.id.clone(), ) } else { let network_transaction_id = match item.response.latest_attempt { Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt .payment_method_details .and_then(|payment_method_details| match payment_method_details { StripePaymentMethodDetailsResponse::Card { card } => { card.network_transaction_id } _ => None, }), _ => None, }; Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: network_transaction_id, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, charges: None, }) }; Ok(Self { status, response, connector_response: connector_response_data, ..item.data }) } } pub fn stripe_opt_latest_attempt_to_opt_string( latest_attempt: Option<LatestAttempt>, ) -> Option<String> { match latest_attempt { Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt .payment_method_options .and_then(|payment_method_options| match payment_method_options { StripePaymentMethodOptions::Card { network_transaction_id, .. } => network_transaction_id.map(|network_id| network_id.expose()), _ => None, }), _ => None, } } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "snake_case", remote = "Self")] pub enum StripeNextActionResponse { CashappHandleRedirectOrDisplayQrCode(StripeCashappQrResponse), RedirectToUrl(StripeRedirectToUrlResponse), AlipayHandleRedirect(StripeRedirectToUrlResponse), VerifyWithMicrodeposits(StripeVerifyWithMicroDepositsResponse), WechatPayDisplayQrCode(WechatPayRedirectToQr), DisplayBankTransferInstructions(StripeBankTransferDetails), MultibancoDisplayDetails(MultibancoCreditTansferResponse), NoNextActionBody, } impl StripeNextActionResponse { fn get_url(&self) -> Option<Url> { match self { Self::RedirectToUrl(redirect_to_url) | Self::AlipayHandleRedirect(redirect_to_url) => { Some(redirect_to_url.url.to_owned()) } Self::WechatPayDisplayQrCode(_) => None, Self::VerifyWithMicrodeposits(verify_with_microdeposits) => { Some(verify_with_microdeposits.hosted_verification_url.to_owned()) } Self::CashappHandleRedirectOrDisplayQrCode(_) => None, Self::DisplayBankTransferInstructions(_) => None, Self::MultibancoDisplayDetails(_) => None, Self::NoNextActionBody => None, } } } // This impl is required because Stripe's response is of the below format, which is externally // tagged, but also with an extra 'type' field specifying the enum variant name: // "next_action": { // "redirect_to_url": { "return_url": "...", "url": "..." }, // "type": "redirect_to_url" // }, // Reference: https://github.com/serde-rs/serde/issues/1343#issuecomment-409698470 impl<'de> Deserialize<'de> for StripeNextActionResponse { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] struct Wrapper { #[serde(rename = "type")] _ignore: String, #[serde(flatten, with = "StripeNextActionResponse")] inner: StripeNextActionResponse, } // There is some exception in the stripe next action, it usually sends : // "next_action": { // "redirect_to_url": { "return_url": "...", "url": "..." }, // "type": "redirect_to_url" // }, // But there is a case where it only sends the type and not other field named as it's type let stripe_next_action_response = Wrapper::deserialize(deserializer).map_or(Self::NoNextActionBody, |w| w.inner); Ok(stripe_next_action_response) } } impl Serialize for StripeNextActionResponse { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match *self { Self::CashappHandleRedirectOrDisplayQrCode(ref i) => { Serialize::serialize(i, serializer) } Self::RedirectToUrl(ref i) => Serialize::serialize(i, serializer), Self::AlipayHandleRedirect(ref i) => Serialize::serialize(i, serializer), Self::VerifyWithMicrodeposits(ref i) => Serialize::serialize(i, serializer), Self::WechatPayDisplayQrCode(ref i) => Serialize::serialize(i, serializer), Self::DisplayBankTransferInstructions(ref i) => Serialize::serialize(i, serializer), Self::MultibancoDisplayDetails(ref i) => Serialize::serialize(i, serializer), Self::NoNextActionBody => Serialize::serialize("NoNextActionBody", serializer), } } } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeRedirectToUrlResponse { return_url: String, url: Url, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct WechatPayRedirectToQr { // This data contains url, it should be converted to QR code. // Note: The url in this data is not redirection url data: Url, // This is the image source, this image_data_url can directly be used by sdk to show the QR code image_data_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeVerifyWithMicroDepositsResponse { hosted_verification_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(untagged)] pub enum FinancialInformation { AchFinancialInformation(Vec<AchFinancialInformation>), StripeFinancialInformation(Vec<StripeFinancialInformation>), } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeBankTransferDetails { pub amount_remaining: MinorUnit, pub currency: String, pub financial_addresses: FinancialInformation, pub hosted_instructions_url: Option<String>, pub reference: Option<String>, #[serde(rename = "type")] pub bank_transfer_type: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeCashappQrResponse { pub mobile_auth_url: Url, pub qr_code: QrCodeResponse, pub hosted_instructions_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct QrCodeResponse { pub expires_at: Option<i64>, pub image_url_png: Url, pub image_url_svg: Url, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct AbaDetails { pub account_number: Secret<String>, pub bank_name: Secret<String>, pub routing_number: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct SwiftDetails { pub account_number: Secret<String>, pub bank_name: Secret<String>, pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum AchFinancialDetails { Aba(AbaDetails), Swift(SwiftDetails), } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeFinancialInformation { pub iban: Option<SepaFinancialDetails>, pub sort_code: Option<BacsFinancialDetails>, pub supported_networks: Vec<String>, #[serde(rename = "type")] pub financial_info_type: String, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct AchFinancialInformation { #[serde(flatten)] pub financial_details: AchFinancialDetails, pub supported_networks: Vec<String>, #[serde(rename = "type")] pub financial_info_type: String, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct SepaFinancialDetails { pub account_holder_name: Secret<String>, pub bic: Secret<String>, pub country: Secret<String>, pub iban: Secret<String>, pub reference: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct BacsFinancialDetails { pub account_holder_name: Secret<String>, pub account_number: Secret<String>, pub sort_code: Secret<String>, } // REFUND : // Type definition for Stripe RefundRequest #[derive(Debug, Serialize)] pub struct RefundRequest { pub amount: Option<MinorUnit>, //amount in cents, hence passed as integer pub payment_intent: String, #[serde(flatten)] pub meta_data: StripeMetadata, } impl<F> TryFrom<(&RefundsRouterData<F>, MinorUnit)> for RefundRequest { type Error = error_stack::Report<ConnectorError>; fn try_from( (item, refund_amount): (&RefundsRouterData<F>, MinorUnit), ) -> Result<Self, Self::Error> { let payment_intent = item.request.connector_transaction_id.clone(); Ok(Self { amount: Some(refund_amount), payment_intent, meta_data: StripeMetadata { order_id: Some(item.request.refund_id.clone()), is_refund_id_as_reference: Some("true".to_string()), }, }) } } #[derive(Debug, Serialize)] pub struct ChargeRefundRequest { pub charge: String, pub refund_application_fee: Option<bool>, pub reverse_transfer: Option<bool>, pub amount: Option<MinorUnit>, //amount in cents, hence passed as integer #[serde(flatten)] pub meta_data: StripeMetadata, } impl<F> TryFrom<&RefundsRouterData<F>> for ChargeRefundRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> { let amount = item.request.minor_refund_amount; match item.request.split_refunds.as_ref() { None => Err(ConnectorError::MissingRequiredField { field_name: "split_refunds", } .into()), Some(split_refunds) => match split_refunds { SplitRefundsRequest::StripeSplitRefund(stripe_refund) => { let (refund_application_fee, reverse_transfer) = match &stripe_refund.options { ChargeRefundsOptions::Direct(DirectChargeRefund { revert_platform_fee, }) => (Some(*revert_platform_fee), None), ChargeRefundsOptions::Destination(DestinationChargeRefund { revert_platform_fee, revert_transfer, }) => (Some(*revert_platform_fee), Some(*revert_transfer)), }; Ok(Self { charge: stripe_refund.charge_id.clone(), refund_application_fee, reverse_transfer, amount: Some(amount), meta_data: StripeMetadata { order_id: Some(item.request.refund_id.clone()), is_refund_id_as_reference: Some("true".to_string()), }, }) } _ => Err(ConnectorError::MissingRequiredField { field_name: "stripe_split_refund", })?, }, } } } // Type definition for Stripe Refund Response #[derive(Default, Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum RefundStatus { Succeeded, Failed, #[default] Pending, RequiresAction, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Pending => Self::Pending, RefundStatus::RequiresAction => Self::ManualReview, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { pub id: String, pub object: String, pub amount: MinorUnit, pub currency: String, pub metadata: StripeMetadata, pub payment_intent: String, pub status: RefundStatus, pub failure_reason: Option<String>, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status); let response = if is_refund_failure(refund_status) { Err(hyperswitch_domain_models::router_data::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), message: item .response .failure_reason .clone() .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: item.response.failure_reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.id), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }) }; Ok(Self { response, ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status); let response = if is_refund_failure(refund_status) { Err(hyperswitch_domain_models::router_data::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), message: item .response .failure_reason .clone() .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: item.response.failure_reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.id), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }) }; Ok(Self { response, ..item.data }) } } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct ErrorDetails { pub code: Option<String>, #[serde(rename = "type")] pub error_type: Option<String>, pub message: Option<String>, pub param: Option<String>, pub decline_code: Option<String>, pub payment_intent: Option<PaymentIntentErrorResponse>, pub network_advice_code: Option<String>, pub network_decline_code: Option<String>, pub advice_code: Option<String>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct PaymentIntentErrorResponse { pub id: String, } #[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct ErrorResponse { pub error: ErrorDetails, } #[derive(Debug, Default, Eq, PartialEq, Serialize)] pub struct StripeShippingAddress { #[serde(rename = "shipping[address][city]")] pub city: Option<String>, #[serde(rename = "shipping[address][country]")] pub country: Option<api_enums::CountryAlpha2>, #[serde(rename = "shipping[address][line1]")] pub line1: Option<Secret<String>>, #[serde(rename = "shipping[address][line2]")] pub line2: Option<Secret<String>>, #[serde(rename = "shipping[address][postal_code]")] pub zip: Option<Secret<String>>, #[serde(rename = "shipping[address][state]")] pub state: Option<Secret<String>>, #[serde(rename = "shipping[name]")] pub name: Option<Secret<String>>, #[serde(rename = "shipping[phone]")] pub phone: Option<Secret<String>>, } #[derive(Debug, Clone, Default, Eq, PartialEq, Serialize)] pub struct StripeBillingAddress { #[serde(rename = "payment_method_data[billing_details][email]")] pub email: Option<Email>, #[serde(rename = "payment_method_data[billing_details][address][country]")] pub country: Option<api_enums::CountryAlpha2>, #[serde(rename = "payment_method_data[billing_details][name]")] pub name: Option<Secret<String>>, #[serde(rename = "payment_method_data[billing_details][address][city]")] pub city: Option<String>, #[serde(rename = "payment_method_data[billing_details][address][line1]")] pub address_line1: Option<Secret<String>>, #[serde(rename = "payment_method_data[billing_details][address][line2]")] pub address_line2: Option<Secret<String>>, #[serde(rename = "payment_method_data[billing_details][address][postal_code]")] pub zip_code: Option<Secret<String>>, #[serde(rename = "payment_method_data[billing_details][address][state]")] pub state: Option<Secret<String>>, #[serde(rename = "payment_method_data[billing_details][phone]")] pub phone: Option<Secret<String>>, } #[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)] pub struct StripeRedirectResponse { pub payment_intent: Option<String>, pub payment_intent_client_secret: Option<Secret<String>>, pub source_redirect_slug: Option<String>, pub redirect_status: Option<StripePaymentStatus>, pub source_type: Option<Secret<String>>, } #[derive(Debug, Serialize)] pub struct CancelRequest { cancellation_reason: Option<String>, } impl TryFrom<&PaymentsCancelRouterData> for CancelRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { Ok(Self { cancellation_reason: item.request.cancellation_reason.clone(), }) } } #[derive(Debug, Serialize)] pub struct UpdateMetadataRequest { #[serde(flatten)] pub metadata: HashMap<String, String>, } impl TryFrom<&PaymentsUpdateMetadataRouterData> for UpdateMetadataRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &PaymentsUpdateMetadataRouterData) -> Result<Self, Self::Error> { let metadata = format_metadata_for_request(item.request.metadata.clone()); Ok(Self { metadata }) } } fn format_metadata_for_request(merchant_metadata: Secret<Value>) -> HashMap<String, String> { let mut formatted_metadata = HashMap::new(); if let Value::Object(metadata_map) = merchant_metadata.expose() { for (key, value) in metadata_map { formatted_metadata.insert(format!("metadata[{key}]"), value.to_string()); } } formatted_metadata } #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] #[non_exhaustive] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum StripePaymentMethodOptions { Card { mandate_options: Option<StripeMandateOptions>, #[serde(rename = "payment_method_options[card][network_transaction_id]")] network_transaction_id: Option<Secret<String>>, #[serde(flatten)] mit_exemption: Option<MitExemption>, // To be used for MIT mandate txns }, Klarna {}, Affirm {}, AfterpayClearpay {}, AmazonPay {}, Eps {}, Giropay {}, Ideal {}, Sofort {}, #[serde(rename = "us_bank_account")] Ach {}, #[serde(rename = "sepa_debit")] Sepa {}, #[serde(rename = "au_becs_debit")] Becs {}, #[serde(rename = "bacs_debit")] Bacs {}, Bancontact {}, WechatPay {}, Alipay {}, #[serde(rename = "p24")] Przelewy24 {}, CustomerBalance {}, Multibanco {}, Blik {}, Cashapp {}, } #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] pub struct MitExemption { #[serde(rename = "payment_method_options[card][mit_exemption][network_transaction_id]")] pub network_transaction_id: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(untagged)] pub enum LatestAttempt { PaymentIntentAttempt(Box<LatestPaymentAttempt>), SetupAttempt(String), } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct LatestPaymentAttempt { pub payment_method_options: Option<StripePaymentMethodOptions>, pub payment_method_details: Option<StripePaymentMethodDetailsResponse>, } // #[derive(Deserialize, Debug, Clone, Eq, PartialEq)] // pub struct Card #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)] pub struct StripeMandateOptions { reference: Secret<String>, // Extendable, But only important field to be captured } /// Represents the capture request body for stripe connector. #[derive(Debug, Serialize, Clone, Copy)] pub struct CaptureRequest { /// If amount_to_capture is None stripe captures the amount in the payment intent. amount_to_capture: Option<MinorUnit>, } impl TryFrom<MinorUnit> for CaptureRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(capture_amount: MinorUnit) -> Result<Self, Self::Error> { Ok(Self { amount_to_capture: Some(capture_amount), }) } } impl<F, T> TryFrom<ResponseRouterData<F, StripeSourceResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, StripeSourceResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let connector_source_response = item.response.to_owned(); let connector_metadata = connector_source_response .encode_to_value() .change_context(ConnectorError::ResponseHandlingFailed)?; // We get pending as the status from stripe, but hyperswitch should give it as requires_customer_action as // customer has to make payment to the virtual account number given in the source response let status = match connector_source_response.status.clone().into() { AttemptStatus::Pending => AttemptStatus::AuthenticationPending, _ => connector_source_response.status.into(), }; Ok(Self { response: Ok(PaymentsResponseData::PreProcessingResponse { pre_processing_id: PreprocessingResponseId::PreProcessingId(item.response.id), connector_metadata: Some(connector_metadata), session_token: None, connector_response_reference_id: None, }), status, ..item.data }) } } impl TryFrom<(&PaymentsAuthorizeRouterData, MinorUnit)> for ChargesRequest { type Error = error_stack::Report<ConnectorError>; fn try_from(data: (&PaymentsAuthorizeRouterData, MinorUnit)) -> Result<Self, Self::Error> { { let value = data.0; let amount = data.1; let order_id = value.connector_request_reference_id.clone(); let meta_data = Some(get_transaction_metadata( value.request.metadata.clone().map(Into::into), order_id, )); Ok(Self { amount, currency: value.request.currency.to_string(), customer: Secret::new(value.get_connector_customer_id()?), source: Secret::new(value.get_preprocessing_id()?), meta_data, }) } } } impl<F, T> TryFrom<ResponseRouterData<F, ChargesResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, ChargesResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let connector_source_response = item.response.to_owned(); let connector_metadata = connector_source_response .source .encode_to_value() .change_context(ConnectorError::ResponseHandlingFailed)?; let status = AttemptStatus::from(item.response.status); let response = if is_payment_failure(status) { Err(hyperswitch_domain_models::router_data::ErrorResponse { code: item .response .failure_code .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: item .response .failure_message .clone() .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: item.response.failure_message, status_code: item.http_code, attempt_status: Some(status), connector_transaction_id: Some(item.response.id), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: Some(connector_metadata), network_txn_id: None, connector_response_reference_id: Some(item.response.id.clone()), incremental_authorization_allowed: None, charges: None, }) }; Ok(Self { status, response, ..item.data }) } } impl<F, T> TryFrom<ResponseRouterData<F, StripeTokenResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, StripeTokenResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let token = item.response.id.clone().expose(); Ok(Self { response: Ok(PaymentsResponseData::TokenizationResponse { token }), ..item.data }) } } impl<F, T> TryFrom<ResponseRouterData<F, StripeCustomerResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, StripeCustomerResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PaymentsResponseData::ConnectorCustomerResponse( ConnectorCustomerResponseData::new_with_customer_id(item.response.id), )), ..item.data }) } } // #[cfg(test)] // mod test_stripe_transformers { // use super::*; // #[test] // fn verify_transform_from_router_to_stripe_req() { // let router_req = PaymentsRequest { // amount: 100.0, // currency: "USD".to_string(), // ..Default::default() // }; // let stripe_req = PaymentIntentRequest::from(router_req); // //metadata is generated everytime. So use the transformed struct to copy uuid // let stripe_req_expected = PaymentIntentRequest { // amount: 10000, // currency: "USD".to_string(), // statement_descriptor_suffix: None, // metadata_order_id: "Auto generate Order ID".to_string(), // metadata_txn_id: "Fetch from Merchant Account_Auto generate Order ID_1".to_string(), // metadata_txn_uuid: stripe_req.metadata_txn_uuid.clone(), // return_url: "Fetch Url from Merchant Account".to_string(), // confirm: false, // payment_method_types: "card".to_string(), // payment_method_data_type: "card".to_string(), // payment_method_data_card_number: None, // payment_method_data_card_exp_month: None, // payment_method_data_card_exp_year: None, // payment_method_data_card_cvc: None, // description: None, // }; // assert_eq!(stripe_req_expected, stripe_req); // } // } #[derive(Debug, Deserialize)] pub struct WebhookEventDataResource { pub object: Value, } #[derive(Debug, Deserialize)] pub struct WebhookEventObjectResource { pub data: WebhookEventDataResource, } #[derive(Debug, Deserialize)] pub struct WebhookEvent { #[serde(rename = "type")] pub event_type: WebhookEventType, #[serde(rename = "data")] pub event_data: WebhookEventData, } #[derive(Debug, Deserialize)] pub struct WebhookEventTypeBody { #[serde(rename = "type")] pub event_type: WebhookEventType, #[serde(rename = "data")] pub event_data: WebhookStatusData, } #[derive(Debug, Deserialize)] pub struct WebhookEventData { #[serde(rename = "object")] pub event_object: WebhookEventObjectData, } #[derive(Debug, Deserialize)] pub struct WebhookStatusData { #[serde(rename = "object")] pub event_object: WebhookStatusObjectData, } #[derive(Debug, Deserialize)] pub struct WebhookStatusObjectData { pub status: Option<WebhookEventStatus>, pub payment_method_details: Option<WebhookPaymentMethodDetails>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case")] pub enum WebhookPaymentMethodType { AchCreditTransfer, MultibancoBankTransfers, #[serde(other)] Unknown, } #[derive(Debug, Deserialize)] pub struct WebhookPaymentMethodDetails { #[serde(rename = "type")] pub payment_method: WebhookPaymentMethodType, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct WebhookEventObjectData { pub id: String, pub object: WebhookEventObjectType, pub amount: Option<MinorUnit>, #[serde(default, deserialize_with = "convert_uppercase")] pub currency: enums::Currency, pub payment_intent: Option<String>, pub client_secret: Option<Secret<String>>, pub reason: Option<String>, #[serde(with = "common_utils::custom_serde::timestamp")] pub created: PrimitiveDateTime, pub evidence_details: Option<EvidenceDetails>, pub status: Option<WebhookEventStatus>, pub metadata: Option<StripeMetadata>, pub last_payment_error: Option<ErrorDetails>, } #[derive(Debug, Clone, Serialize, Deserialize, strum::Display)] #[serde(rename_all = "snake_case")] pub enum WebhookEventObjectType { PaymentIntent, Dispute, Charge, Source, Refund, } #[derive(Debug, Deserialize)] pub enum WebhookEventType { #[serde(rename = "payment_intent.payment_failed")] PaymentIntentFailed, #[serde(rename = "payment_intent.succeeded")] PaymentIntentSucceed, #[serde(rename = "charge.dispute.created")] DisputeCreated, #[serde(rename = "charge.dispute.closed")] DisputeClosed, #[serde(rename = "charge.dispute.updated")] DisputeUpdated, #[serde(rename = "charge.dispute.funds_reinstated")] ChargeDisputeFundsReinstated, #[serde(rename = "charge.dispute.funds_withdrawn")] ChargeDisputeFundsWithdrawn, #[serde(rename = "charge.expired")] ChargeExpired, #[serde(rename = "charge.failed")] ChargeFailed, #[serde(rename = "charge.pending")] ChargePending, #[serde(rename = "charge.captured")] ChargeCaptured, #[serde(rename = "charge.refund.updated")] ChargeRefundUpdated, #[serde(rename = "charge.succeeded")] ChargeSucceeded, #[serde(rename = "charge.updated")] ChargeUpdated, #[serde(rename = "charge.refunded")] ChargeRefunded, #[serde(rename = "payment_intent.canceled")] PaymentIntentCanceled, #[serde(rename = "payment_intent.created")] PaymentIntentCreated, #[serde(rename = "payment_intent.processing")] PaymentIntentProcessing, #[serde(rename = "payment_intent.requires_action")] PaymentIntentRequiresAction, #[serde(rename = "payment_intent.amount_capturable_updated")] PaymentIntentAmountCapturableUpdated, #[serde(rename = "source.chargeable")] SourceChargeable, #[serde(rename = "source.transaction.created")] SourceTransactionCreated, #[serde(rename = "payment_intent.partially_funded")] PaymentIntentPartiallyFunded, #[serde(other)] Unknown, } #[derive(Debug, Clone, Serialize, strum::Display, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum WebhookEventStatus { WarningNeedsResponse, WarningClosed, WarningUnderReview, Won, Lost, NeedsResponse, UnderReview, ChargeRefunded, Succeeded, RequiresPaymentMethod, RequiresConfirmation, RequiresAction, Processing, RequiresCapture, Canceled, Chargeable, Failed, #[serde(other)] Unknown, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct EvidenceDetails { #[serde(with = "common_utils::custom_serde::timestamp")] pub due_by: PrimitiveDateTime, } impl TryFrom<( &SetupMandateRouterData, enums::AuthenticationType, StripePaymentMethodType, )> for StripePaymentMethodData { type Error = error_stack::Report<ConnectorError>; fn try_from( (item, auth_type, pm_type): ( &SetupMandateRouterData, enums::AuthenticationType, StripePaymentMethodType, ), ) -> Result<Self, Self::Error> { let pm_data = &item.request.payment_method_data; match pm_data { PaymentMethodData::Card(ref ccard) => { let payment_method_auth_type = match auth_type { enums::AuthenticationType::ThreeDs => Auth3ds::Any, enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, }; Ok(Self::try_from(( ccard, payment_method_auth_type, item.request.request_incremental_authorization, None, None, ))?) } PaymentMethodData::PayLater(_) => Ok(Self::PayLater(StripePayLaterData { payment_method_data_type: pm_type, })), PaymentMethodData::BankRedirect(ref bank_redirect_data) => { Ok(Self::try_from(bank_redirect_data)?) } PaymentMethodData::Wallet(ref wallet_data) => Ok(Self::try_from((wallet_data, None))?), PaymentMethodData::BankDebit(bank_debit_data) => { let (_pm_type, bank_data) = get_bank_debit_data(bank_debit_data); Ok(Self::BankDebit(StripeBankDebitData { bank_specific_data: bank_data, })) } PaymentMethodData::BankTransfer(bank_transfer_data) => match bank_transfer_data.deref() { payment_method_data::BankTransferData::AchBankTransfer {} => { Ok(Self::BankTransfer(StripeBankTransferData::AchBankTransfer( Box::new(AchTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: StripeCreditTransferTypes::AchCreditTransfer, payment_method_type: StripePaymentMethodType::CustomerBalance, balance_funding_type: BankTransferType::BankTransfers, }), ))) } payment_method_data::BankTransferData::MultibancoBankTransfer {} => Ok( Self::BankTransfer(StripeBankTransferData::MultibancoBankTransfers(Box::new( MultibancoTransferData { payment_method_data_type: StripeCreditTransferTypes::Multibanco, payment_method_type: StripeCreditTransferTypes::Multibanco, email: item.get_billing_email()?, }, ))), ), payment_method_data::BankTransferData::SepaBankTransfer {} => { Ok(Self::BankTransfer( StripeBankTransferData::SepaBankTransfer(Box::new(SepaBankTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: BankTransferType::EuBankTransfer, balance_funding_type: BankTransferType::BankTransfers, payment_method_type: StripePaymentMethodType::CustomerBalance, country: item.get_billing_country()?, })), )) } payment_method_data::BankTransferData::BacsBankTransfer { .. } => { Ok(Self::BankTransfer( StripeBankTransferData::BacsBankTransfers(Box::new(BacsBankTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: BankTransferType::GbBankTransfer, balance_funding_type: BankTransferType::BankTransfers, payment_method_type: StripePaymentMethodType::CustomerBalance, })), )) } payment_method_data::BankTransferData::Pix { .. } | payment_method_data::BankTransferData::Pse {} | payment_method_data::BankTransferData::PermataBankTransfer { .. } | payment_method_data::BankTransferData::BcaBankTransfer { .. } | payment_method_data::BankTransferData::BniVaBankTransfer { .. } | payment_method_data::BankTransferData::BriVaBankTransfer { .. } | payment_method_data::BankTransferData::CimbVaBankTransfer { .. } | payment_method_data::BankTransferData::DanamonVaBankTransfer { .. } | payment_method_data::BankTransferData::LocalBankTransfer { .. } | payment_method_data::BankTransferData::InstantBankTransfer {} | payment_method_data::BankTransferData::InstantBankTransferFinland {} | payment_method_data::BankTransferData::InstantBankTransferPoland {} | payment_method_data::BankTransferData::IndonesianBankTransfer { .. } | payment_method_data::BankTransferData::MandiriVaBankTransfer { .. } => { Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ) .into()) } }, PaymentMethodData::MandatePayment | PaymentMethodData::Crypto(_) | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::Upi(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), ))? } } } } #[derive(Debug, Deserialize)] pub struct StripeGpayToken { pub id: String, } pub fn get_bank_transfer_request_data( req: &PaymentsAuthorizeRouterData, bank_transfer_data: &payment_method_data::BankTransferData, amount: MinorUnit, ) -> CustomResult<RequestContent, ConnectorError> { match bank_transfer_data { payment_method_data::BankTransferData::AchBankTransfer { .. } | payment_method_data::BankTransferData::MultibancoBankTransfer { .. } => { let req = ChargesRequest::try_from((req, amount))?; Ok(RequestContent::FormUrlEncoded(Box::new(req))) } _ => { let req = PaymentIntentRequest::try_from((req, amount))?; Ok(RequestContent::FormUrlEncoded(Box::new(req))) } } } #[derive(Debug, Serialize)] pub struct StripeFileRequest { pub purpose: &'static str, #[serde(skip)] pub file: Vec<u8>, #[serde(skip)] pub file_key: String, #[serde(skip)] pub file_type: String, } pub fn construct_file_upload_request( file_upload_router_data: UploadFileRouterData, ) -> CustomResult<RequestContent, ConnectorError> { let request = file_upload_router_data.request; let stripe_file_request = StripeFileRequest { purpose: "dispute_evidence", file: request.file.clone(), file_key: request.file_key.clone(), file_type: request.file_type.to_string(), }; let mut multipart = reqwest::multipart::Form::new(); multipart = multipart.text("purpose", "dispute_evidence"); let file_data = reqwest::multipart::Part::bytes(request.file) .file_name(request.file_key) .mime_str(request.file_type.as_ref()) .map_err(|_| ConnectorError::RequestEncodingFailed)?; multipart = multipart.part("file", file_data); Ok(RequestContent::FormData(( multipart, Box::new(stripe_file_request), ))) } #[derive(Debug, Deserialize, Serialize)] pub struct FileUploadResponse { #[serde(rename = "id")] pub file_id: String, } #[derive(Debug, Serialize)] pub struct Evidence { #[serde(rename = "evidence[access_activity_log]")] pub access_activity_log: Option<String>, #[serde(rename = "evidence[billing_address]")] pub billing_address: Option<Secret<String>>, #[serde(rename = "evidence[cancellation_policy]")] pub cancellation_policy: Option<String>, #[serde(rename = "evidence[cancellation_policy_disclosure]")] pub cancellation_policy_disclosure: Option<String>, #[serde(rename = "evidence[cancellation_rebuttal]")] pub cancellation_rebuttal: Option<String>, #[serde(rename = "evidence[customer_communication]")] pub customer_communication: Option<String>, #[serde(rename = "evidence[customer_email_address]")] pub customer_email_address: Option<Secret<String, pii::EmailStrategy>>, #[serde(rename = "evidence[customer_name]")] pub customer_name: Option<Secret<String>>, #[serde(rename = "evidence[customer_purchase_ip]")] pub customer_purchase_ip: Option<Secret<String, pii::IpAddress>>, #[serde(rename = "evidence[customer_signature]")] pub customer_signature: Option<Secret<String>>, #[serde(rename = "evidence[product_description]")] pub product_description: Option<String>, #[serde(rename = "evidence[receipt]")] pub receipt: Option<Secret<String>>, #[serde(rename = "evidence[refund_policy]")] pub refund_policy: Option<String>, #[serde(rename = "evidence[refund_policy_disclosure]")] pub refund_policy_disclosure: Option<String>, #[serde(rename = "evidence[refund_refusal_explanation]")] pub refund_refusal_explanation: Option<String>, #[serde(rename = "evidence[service_date]")] pub service_date: Option<String>, #[serde(rename = "evidence[service_documentation]")] pub service_documentation: Option<String>, #[serde(rename = "evidence[shipping_address]")] pub shipping_address: Option<Secret<String>>, #[serde(rename = "evidence[shipping_carrier]")] pub shipping_carrier: Option<String>, #[serde(rename = "evidence[shipping_date]")] pub shipping_date: Option<String>, #[serde(rename = "evidence[shipping_documentation]")] pub shipping_documentation: Option<Secret<String>>, #[serde(rename = "evidence[shipping_tracking_number]")] pub shipping_tracking_number: Option<Secret<String>>, #[serde(rename = "evidence[uncategorized_file]")] pub uncategorized_file: Option<String>, #[serde(rename = "evidence[uncategorized_text]")] pub uncategorized_text: Option<String>, pub submit: bool, } // Mandates for bank redirects - ideal happens through sepa direct debit in stripe fn mandatory_parameters_for_sepa_bank_debit_mandates( billing_details: &Option<StripeBillingAddress>, is_customer_initiated_mandate_payment: Option<bool>, ) -> Result<StripeBillingAddress, ConnectorError> { let billing_name = billing_details .clone() .and_then(|billing_data| billing_data.name.clone()); let billing_email = billing_details .clone() .and_then(|billing_data| billing_data.email.clone()); match is_customer_initiated_mandate_payment { Some(true) => Ok(StripeBillingAddress { name: Some(billing_name.ok_or(ConnectorError::MissingRequiredField { field_name: "billing_name", })?), email: Some(billing_email.ok_or(ConnectorError::MissingRequiredField { field_name: "billing_email", })?), ..StripeBillingAddress::default() }), Some(false) | None => Ok(StripeBillingAddress { name: billing_name, email: billing_email, ..StripeBillingAddress::default() }), } } impl TryFrom<&SubmitEvidenceRouterData> for Evidence { type Error = error_stack::Report<ConnectorError>; fn try_from(item: &SubmitEvidenceRouterData) -> Result<Self, Self::Error> { let submit_evidence_request_data = item.request.clone(); Ok(Self { access_activity_log: submit_evidence_request_data.access_activity_log, billing_address: submit_evidence_request_data .billing_address .map(Secret::new), cancellation_policy: submit_evidence_request_data.cancellation_policy_provider_file_id, cancellation_policy_disclosure: submit_evidence_request_data .cancellation_policy_disclosure, cancellation_rebuttal: submit_evidence_request_data.cancellation_rebuttal, customer_communication: submit_evidence_request_data .customer_communication_provider_file_id, customer_email_address: submit_evidence_request_data .customer_email_address .map(Secret::new), customer_name: submit_evidence_request_data.customer_name.map(Secret::new), customer_purchase_ip: submit_evidence_request_data .customer_purchase_ip .map(Secret::new), customer_signature: submit_evidence_request_data .customer_signature_provider_file_id .map(Secret::new), product_description: submit_evidence_request_data.product_description, receipt: submit_evidence_request_data .receipt_provider_file_id .map(Secret::new), refund_policy: submit_evidence_request_data.refund_policy_provider_file_id, refund_policy_disclosure: submit_evidence_request_data.refund_policy_disclosure, refund_refusal_explanation: submit_evidence_request_data.refund_refusal_explanation, service_date: submit_evidence_request_data.service_date, service_documentation: submit_evidence_request_data .service_documentation_provider_file_id, shipping_address: submit_evidence_request_data .shipping_address .map(Secret::new), shipping_carrier: submit_evidence_request_data.shipping_carrier, shipping_date: submit_evidence_request_data.shipping_date, shipping_documentation: submit_evidence_request_data .shipping_documentation_provider_file_id .map(Secret::new), shipping_tracking_number: submit_evidence_request_data .shipping_tracking_number .map(Secret::new), uncategorized_file: submit_evidence_request_data.uncategorized_file_provider_file_id, uncategorized_text: submit_evidence_request_data.uncategorized_text, submit: true, }) } } #[derive(Debug, Deserialize, Serialize)] pub struct DisputeObj { #[serde(rename = "id")] pub dispute_id: String, pub status: String, } fn get_transaction_metadata( merchant_metadata: Option<Secret<Value>>, order_id: String, ) -> HashMap<String, String> { let mut meta_data = HashMap::from([("metadata[order_id]".to_string(), order_id)]); let mut request_hash_map = HashMap::new(); if let Some(metadata) = merchant_metadata { let hashmap: HashMap<String, Value> = serde_json::from_str(&metadata.peek().to_string()).unwrap_or(HashMap::new()); for (key, value) in hashmap { request_hash_map.insert(format!("metadata[{key}]"), value.to_string()); } meta_data.extend(request_hash_map) }; meta_data } fn get_stripe_payments_response_data( response: &Option<ErrorDetails>, http_code: u16, response_id: String, ) -> Box<Result<PaymentsResponseData, hyperswitch_domain_models::router_data::ErrorResponse>> { let (code, error_message) = match response { Some(error_details) => ( error_details .code .to_owned() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), error_details .message .to_owned() .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), ), None => ( consts::NO_ERROR_CODE.to_string(), consts::NO_ERROR_MESSAGE.to_string(), ), }; Box::new(Err(hyperswitch_domain_models::router_data::ErrorResponse { code, message: error_message.clone(), reason: response.clone().and_then(|res| { res.decline_code .clone() .map(|decline_code| { format!("message - {error_message}, decline_code - {decline_code}") }) .or(Some(error_message.clone())) }), status_code: http_code, attempt_status: None, connector_transaction_id: Some(response_id), network_advice_code: response .as_ref() .and_then(|res| res.network_advice_code.clone()), network_decline_code: response .as_ref() .and_then(|res| res.network_decline_code.clone()), network_error_message: response .as_ref() .and_then(|res| res.decline_code.clone().or(res.advice_code.clone())), connector_metadata: None, })) } pub(super) fn transform_headers_for_connect_platform( charge_type: PaymentChargeType, transfer_account_id: String, header: &mut Vec<(String, Maskable<String>)>, ) { if let PaymentChargeType::Stripe(StripeChargeType::Direct) = charge_type { let mut customer_account_header = vec![( STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), transfer_account_id.into_masked(), )]; header.append(&mut customer_account_header); } } pub fn construct_charge_response<T>( charge_id: String, request: &T, ) -> Option<common_types::payments::ConnectorChargeResponseData> where T: SplitPaymentData, { let charge_request = request.get_split_payment_data(); if let Some(SplitPaymentsRequest::StripeSplitPayment(stripe_split_payment)) = charge_request { let stripe_charge_response = common_types::payments::StripeChargeResponseData { charge_id: Some(charge_id), charge_type: stripe_split_payment.charge_type, application_fees: stripe_split_payment.application_fees, transfer_account_id: stripe_split_payment.transfer_account_id, }; Some( common_types::payments::ConnectorChargeResponseData::StripeSplitPayment( stripe_charge_response, ), ) } else { None } } #[cfg(test)] mod test_validate_shipping_address_against_payment_method { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use crate::connectors::stripe::transformers::{ validate_shipping_address_against_payment_method, StripePaymentMethodType, StripeShippingAddress, }; #[test] fn should_return_ok() { // Arrange let stripe_shipping_address = create_stripe_shipping_address( "name".to_string(), Some("line1".to_string()), Some(CountryAlpha2::AD), Some("zip".to_string()), ); let payment_method = &StripePaymentMethodType::AfterpayClearpay; //Act let result = validate_shipping_address_against_payment_method( &Some(stripe_shipping_address), Some(payment_method), ); // Assert assert!(result.is_ok()); } #[test] fn should_return_err_for_empty_line1() { // Arrange let stripe_shipping_address = create_stripe_shipping_address( "name".to_string(), None, Some(CountryAlpha2::AD), Some("zip".to_string()), ); let payment_method = &StripePaymentMethodType::AfterpayClearpay; //Act let result = validate_shipping_address_against_payment_method( &Some(stripe_shipping_address), Some(payment_method), ); // Assert assert!(result.is_err()); let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); assert_eq!(missing_fields.len(), 1); assert_eq!(*missing_fields.first().unwrap(), "shipping.address.line1"); } #[test] fn should_return_err_for_empty_country() { // Arrange let stripe_shipping_address = create_stripe_shipping_address( "name".to_string(), Some("line1".to_string()), None, Some("zip".to_string()), ); let payment_method = &StripePaymentMethodType::AfterpayClearpay; //Act let result = validate_shipping_address_against_payment_method( &Some(stripe_shipping_address), Some(payment_method), ); // Assert assert!(result.is_err()); let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); assert_eq!(missing_fields.len(), 1); assert_eq!(*missing_fields.first().unwrap(), "shipping.address.country"); } #[test] fn should_return_err_for_empty_zip() { // Arrange let stripe_shipping_address = create_stripe_shipping_address( "name".to_string(), Some("line1".to_string()), Some(CountryAlpha2::AD), None, ); let payment_method = &StripePaymentMethodType::AfterpayClearpay; //Act let result = validate_shipping_address_against_payment_method( &Some(stripe_shipping_address), Some(payment_method), ); // Assert assert!(result.is_err()); let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); assert_eq!(missing_fields.len(), 1); assert_eq!(*missing_fields.first().unwrap(), "shipping.address.zip"); } #[test] fn should_return_error_when_missing_multiple_fields() { // Arrange let expected_missing_field_names: Vec<&'static str> = vec!["shipping.address.zip", "shipping.address.country"]; let stripe_shipping_address = create_stripe_shipping_address( "name".to_string(), Some("line1".to_string()), None, None, ); let payment_method = &StripePaymentMethodType::AfterpayClearpay; //Act let result = validate_shipping_address_against_payment_method( &Some(stripe_shipping_address), Some(payment_method), ); // Assert assert!(result.is_err()); let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); for field in missing_fields { assert!(expected_missing_field_names.contains(&field)); } } fn get_missing_fields(connector_error: &ConnectorError) -> Vec<&'static str> { if let ConnectorError::MissingRequiredFields { field_names } = connector_error { return field_names.to_vec(); } vec![] } fn create_stripe_shipping_address( name: String, line1: Option<String>, country: Option<CountryAlpha2>, zip: Option<String>, ) -> StripeShippingAddress { StripeShippingAddress { name: Some(Secret::new(name)), line1: line1.map(Secret::new), country, zip: zip.map(Secret::new), city: Some(String::from("city")), line2: Some(Secret::new(String::from("line2"))), state: Some(Secret::new(String::from("state"))), phone: Some(Secret::new(String::from("pbone number"))), } } }
crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs
hyperswitch_connectors::src::connectors::stripe::transformers
40,412
true
// File: crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs // Module: hyperswitch_connectors::src::connectors::stripe::transformers::connect use api_models; use common_enums::{enums, Currency}; use common_utils::{ext_traits::OptionExt as _, pii::Email}; use error_stack::ResultExt; use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData}; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use super::ErrorDetails; use crate::{ types::{PayoutIndividualDetailsExt as _, PayoutsResponseRouterData}, utils::{CustomerDetails as _, PayoutsData as _, RouterData}, }; type Error = error_stack::Report<errors::ConnectorError>; #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum StripeConnectPayoutStatus { Canceled, Failed, InTransit, Paid, Pending, } #[derive(Debug, Deserialize, Serialize)] pub struct StripeConnectErrorResponse { pub error: ErrorDetails, } // Payouts #[derive(Clone, Debug, Serialize)] pub struct StripeConnectPayoutCreateRequest { amount: i64, currency: Currency, destination: String, transfer_group: String, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StripeConnectPayoutCreateResponse { id: String, description: Option<String>, source_transaction: Option<String>, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct TransferReversals { object: String, has_more: bool, total_count: i32, url: String, } #[derive(Clone, Debug, Serialize)] pub struct StripeConnectPayoutFulfillRequest { amount: i64, currency: Currency, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StripeConnectPayoutFulfillResponse { id: String, currency: String, description: Option<String>, failure_balance_transaction: Option<String>, failure_code: Option<String>, failure_message: Option<String>, original_payout: Option<String>, reversed_by: Option<String>, statement_descriptor: Option<String>, status: StripeConnectPayoutStatus, } #[derive(Clone, Debug, Serialize)] pub struct StripeConnectReversalRequest { amount: i64, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StripeConnectReversalResponse { id: String, source_refund: Option<String>, } #[derive(Clone, Debug, Serialize)] pub struct StripeConnectRecipientCreateRequest { #[serde(rename = "type")] account_type: String, country: Option<enums::CountryAlpha2>, email: Option<Email>, #[serde(rename = "capabilities[card_payments][requested]")] capabilities_card_payments: Option<bool>, #[serde(rename = "capabilities[transfers][requested]")] capabilities_transfers: Option<bool>, #[serde(rename = "tos_acceptance[date]")] tos_acceptance_date: Option<i64>, #[serde(rename = "tos_acceptance[ip]")] tos_acceptance_ip: Option<Secret<String>>, business_type: String, #[serde(rename = "business_profile[mcc]")] business_profile_mcc: Option<i32>, #[serde(rename = "business_profile[url]")] business_profile_url: Option<String>, #[serde(rename = "business_profile[name]")] business_profile_name: Option<Secret<String>>, #[serde(rename = "company[name]")] company_name: Option<Secret<String>>, #[serde(rename = "company[address][line1]")] company_address_line1: Option<Secret<String>>, #[serde(rename = "company[address][line2]")] company_address_line2: Option<Secret<String>>, #[serde(rename = "company[address][postal_code]")] company_address_postal_code: Option<Secret<String>>, #[serde(rename = "company[address][city]")] company_address_city: Option<Secret<String>>, #[serde(rename = "company[address][state]")] company_address_state: Option<Secret<String>>, #[serde(rename = "company[phone]")] company_phone: Option<Secret<String>>, #[serde(rename = "company[tax_id]")] company_tax_id: Option<Secret<String>>, #[serde(rename = "company[owners_provided]")] company_owners_provided: Option<bool>, #[serde(rename = "individual[first_name]")] individual_first_name: Option<Secret<String>>, #[serde(rename = "individual[last_name]")] individual_last_name: Option<Secret<String>>, #[serde(rename = "individual[dob][day]")] individual_dob_day: Option<Secret<String>>, #[serde(rename = "individual[dob][month]")] individual_dob_month: Option<Secret<String>>, #[serde(rename = "individual[dob][year]")] individual_dob_year: Option<Secret<String>>, #[serde(rename = "individual[address][line1]")] individual_address_line1: Option<Secret<String>>, #[serde(rename = "individual[address][line2]")] individual_address_line2: Option<Secret<String>>, #[serde(rename = "individual[address][postal_code]")] individual_address_postal_code: Option<Secret<String>>, #[serde(rename = "individual[address][city]")] individual_address_city: Option<String>, #[serde(rename = "individual[address][state]")] individual_address_state: Option<Secret<String>>, #[serde(rename = "individual[email]")] individual_email: Option<Email>, #[serde(rename = "individual[phone]")] individual_phone: Option<Secret<String>>, #[serde(rename = "individual[id_number]")] individual_id_number: Option<Secret<String>>, #[serde(rename = "individual[ssn_last_4]")] individual_ssn_last_4: Option<Secret<String>>, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct StripeConnectRecipientCreateResponse { id: String, } #[derive(Clone, Debug, Serialize)] #[serde(untagged)] pub enum StripeConnectRecipientAccountCreateRequest { Bank(RecipientBankAccountRequest), Card(RecipientCardAccountRequest), Token(RecipientTokenRequest), } #[derive(Clone, Debug, Serialize)] pub struct RecipientTokenRequest { external_account: String, } #[derive(Clone, Debug, Serialize)] pub struct RecipientCardAccountRequest { #[serde(rename = "external_account[object]")] external_account_object: String, #[serde(rename = "external_account[number]")] external_account_number: Secret<String>, #[serde(rename = "external_account[exp_month]")] external_account_exp_month: Secret<String>, #[serde(rename = "external_account[exp_year]")] external_account_exp_year: Secret<String>, } #[derive(Clone, Debug, Serialize)] pub struct RecipientBankAccountRequest { #[serde(rename = "external_account[object]")] external_account_object: String, #[serde(rename = "external_account[country]")] external_account_country: enums::CountryAlpha2, #[serde(rename = "external_account[currency]")] external_account_currency: Currency, #[serde(rename = "external_account[account_holder_name]")] external_account_account_holder_name: Secret<String>, #[serde(rename = "external_account[account_number]")] external_account_account_number: Secret<String>, #[serde(rename = "external_account[account_holder_type]")] external_account_account_holder_type: String, #[serde(rename = "external_account[routing_number]")] external_account_routing_number: Secret<String>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StripeConnectRecipientAccountCreateResponse { id: String, } // Payouts create/transfer request transform impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectPayoutCreateRequest { type Error = Error; fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let connector_customer_id = item.get_connector_customer_id()?; Ok(Self { amount: request.amount, currency: request.destination_currency, destination: connector_customer_id, transfer_group: item.connector_request_reference_id.clone(), }) } } // Payouts create response transform impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( item: PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>, ) -> Result<Self, Self::Error> { let response: StripeConnectPayoutCreateResponse = item.response; Ok(Self { response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::RequiresFulfillment), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } // Payouts fulfill request transform impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectPayoutFulfillRequest { type Error = Error; fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); Ok(Self { amount: request.amount, currency: request.destination_currency, }) } } // Payouts fulfill response transform impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( item: PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>, ) -> Result<Self, Self::Error> { let response: StripeConnectPayoutFulfillResponse = item.response; Ok(Self { response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::from(response.status)), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } // Payouts reversal request transform impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectReversalRequest { type Error = Error; fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { Ok(Self { amount: item.request.amount, }) } } // Payouts reversal response transform impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectReversalResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( item: PayoutsResponseRouterData<F, StripeConnectReversalResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::Cancelled), connector_payout_id: item.data.request.connector_payout_id.clone(), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } // Recipient creation request transform impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectRecipientCreateRequest { type Error = Error; fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let customer_details = request.get_customer_details()?; let customer_email = customer_details.get_customer_email()?; let address = item.get_billing_address()?.clone(); let payout_vendor_details = request.get_vendor_details()?; let (vendor_details, individual_details) = ( payout_vendor_details.vendor_details, payout_vendor_details.individual_details, ); Ok(Self { account_type: vendor_details.account_type, country: address.country, email: Some(customer_email.clone()), capabilities_card_payments: vendor_details.capabilities_card_payments, capabilities_transfers: vendor_details.capabilities_transfers, tos_acceptance_date: individual_details.tos_acceptance_date, tos_acceptance_ip: individual_details.tos_acceptance_ip, business_type: vendor_details.business_type, business_profile_mcc: vendor_details.business_profile_mcc, business_profile_url: vendor_details.business_profile_url, business_profile_name: vendor_details.business_profile_name.clone(), company_name: vendor_details.business_profile_name, company_address_line1: vendor_details.company_address_line1, company_address_line2: vendor_details.company_address_line2, company_address_postal_code: vendor_details.company_address_postal_code, company_address_city: vendor_details.company_address_city, company_address_state: vendor_details.company_address_state, company_phone: vendor_details.company_phone, company_tax_id: vendor_details.company_tax_id, company_owners_provided: vendor_details.company_owners_provided, individual_first_name: address.first_name, individual_last_name: address.last_name, individual_dob_day: individual_details.individual_dob_day, individual_dob_month: individual_details.individual_dob_month, individual_dob_year: individual_details.individual_dob_year, individual_address_line1: address.line1, individual_address_line2: address.line2, individual_address_postal_code: address.zip, individual_address_city: address.city, individual_address_state: address.state, individual_email: Some(customer_email), individual_phone: customer_details.phone, individual_id_number: individual_details.individual_id_number, individual_ssn_last_4: individual_details.individual_ssn_last_4, }) } } // Recipient creation response transform impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( item: PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>, ) -> Result<Self, Self::Error> { let response: StripeConnectRecipientCreateResponse = item.response; Ok(Self { response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::RequiresVendorAccountCreation), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: true, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } // Recipient account's creation request impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectRecipientAccountCreateRequest { type Error = Error; fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let payout_method_data = item.get_payout_method_data()?; let customer_details = request.get_customer_details()?; let customer_name = customer_details.get_customer_name()?; let payout_vendor_details = request.get_vendor_details()?; match payout_method_data { api_models::payouts::PayoutMethodData::Card(_) => { Ok(Self::Token(RecipientTokenRequest { external_account: "tok_visa_debit".to_string(), })) } api_models::payouts::PayoutMethodData::Bank(bank) => match bank { api_models::payouts::Bank::Ach(bank_details) => { Ok(Self::Bank(RecipientBankAccountRequest { external_account_object: "bank_account".to_string(), external_account_country: bank_details .bank_country_code .get_required_value("bank_country_code") .change_context(errors::ConnectorError::MissingRequiredField { field_name: "bank_country_code", })?, external_account_currency: request.destination_currency.to_owned(), external_account_account_holder_name: customer_name, external_account_account_holder_type: payout_vendor_details .individual_details .get_external_account_account_holder_type()?, external_account_account_number: bank_details.bank_account_number, external_account_routing_number: bank_details.bank_routing_number, })) } api_models::payouts::Bank::Bacs(_) => Err(errors::ConnectorError::NotSupported { message: "BACS payouts are not supported".to_string(), connector: "stripe", } .into()), api_models::payouts::Bank::Sepa(_) => Err(errors::ConnectorError::NotSupported { message: "SEPA payouts are not supported".to_string(), connector: "stripe", } .into()), api_models::payouts::Bank::Pix(_) => Err(errors::ConnectorError::NotSupported { message: "PIX payouts are not supported".to_string(), connector: "stripe", } .into()), }, api_models::payouts::PayoutMethodData::Wallet(_) => { Err(errors::ConnectorError::NotSupported { message: "Payouts via wallets are not supported".to_string(), connector: "stripe", } .into()) } api_models::payouts::PayoutMethodData::BankRedirect(_) => { Err(errors::ConnectorError::NotSupported { message: "Payouts via BankRedirect are not supported".to_string(), connector: "stripe", } .into()) } } } } // Recipient account's creation response impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( item: PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::RequiresCreation), connector_payout_id: item.data.request.connector_payout_id.clone(), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, payout_connector_metadata: None, }), ..item.data }) } } impl From<StripeConnectPayoutStatus> for enums::PayoutStatus { fn from(stripe_connect_status: StripeConnectPayoutStatus) -> Self { match stripe_connect_status { StripeConnectPayoutStatus::Paid => Self::Success, StripeConnectPayoutStatus::Failed => Self::Failed, StripeConnectPayoutStatus::Canceled => Self::Cancelled, StripeConnectPayoutStatus::Pending | StripeConnectPayoutStatus::InTransit => { Self::Pending } } } }
crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs
hyperswitch_connectors::src::connectors::stripe::transformers::connect
4,054
true
// File: crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs // Module: hyperswitch_connectors::src::connectors::bamboraapac::transformers use common_enums::enums; use common_utils::types::MinorUnit; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_request_types::{ PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData, }, router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData}, types, }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors, }; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::ResponseRouterData, utils::{self, CardData as _, PaymentsAuthorizeRequestData, RouterData as _}, }; type Error = error_stack::Report<errors::ConnectorError>; pub struct BamboraapacRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> TryFrom<(MinorUnit, T)> for BamboraapacRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BamboraapacMeta { pub authorize_id: String, } // request body in soap format pub fn get_payment_body( req: &BamboraapacRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Vec<u8>, Error> { let transaction_data = get_transaction_body(req)?; let body = format!( r#" <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dts="http://www.ippayments.com.au/interface/api/dts"> <soapenv:Body> <dts:SubmitSinglePayment> <dts:trnXML> <![CDATA[ {transaction_data} ]]> </dts:trnXML> </dts:SubmitSinglePayment> </soapenv:Body> </soapenv:Envelope> "#, ); Ok(body.as_bytes().to_vec()) } fn get_transaction_body( req: &BamboraapacRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<String, Error> { let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?; let transaction_type = get_transaction_type(req.router_data.request.capture_method)?; let card_info = get_card_data(req.router_data)?; let transaction_data = format!( r#" <Transaction> <CustRef>{}</CustRef> <Amount>{}</Amount> <TrnType>{}</TrnType> <AccountNumber>{}</AccountNumber> {} <Security> <UserName>{}</UserName> <Password>{}</Password> </Security> </Transaction> "#, req.router_data.connector_request_reference_id.to_owned(), req.amount, transaction_type, auth_details.account_number.peek(), card_info, auth_details.username.peek(), auth_details.password.peek(), ); Ok(transaction_data) } fn get_card_data(req: &types::PaymentsAuthorizeRouterData) -> Result<String, Error> { let card_data = match &req.request.payment_method_data { PaymentMethodData::Card(card) => { let card_holder_name = req.get_billing_full_name()?; if req.request.setup_future_usage == Some(enums::FutureUsage::OffSession) { format!( r#" <CreditCard Registered="False"> <TokeniseAlgorithmID>2</TokeniseAlgorithmID> <CardNumber>{}</CardNumber> <ExpM>{}</ExpM> <ExpY>{}</ExpY> <CVN>{}</CVN> <CardHolderName>{}</CardHolderName> </CreditCard> "#, card.card_number.get_card_no(), card.card_exp_month.peek(), card.get_expiry_year_4_digit().peek(), card.card_cvc.peek(), card_holder_name.peek(), ) } else { format!( r#" <CreditCard Registered="False"> <CardNumber>{}</CardNumber> <ExpM>{}</ExpM> <ExpY>{}</ExpY> <CVN>{}</CVN> <CardHolderName>{}</CardHolderName> </CreditCard> "#, card.card_number.get_card_no(), card.card_exp_month.peek(), card.get_expiry_year_4_digit().peek(), card.card_cvc.peek(), card_holder_name.peek(), ) } } PaymentMethodData::MandatePayment => { format!( r#" <CreditCard> <TokeniseAlgorithmID>2</TokeniseAlgorithmID> <CardNumber>{}</CardNumber> </CreditCard> "#, req.request.get_connector_mandate_id()? ) } _ => { return Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Bambora APAC"), ))? } }; Ok(card_data) } fn get_transaction_type(capture_method: Option<enums::CaptureMethod>) -> Result<u8, Error> { match capture_method { Some(enums::CaptureMethod::Automatic) | None => Ok(1), Some(enums::CaptureMethod::Manual) => Ok(2), _ => Err(errors::ConnectorError::CaptureMethodNotSupported)?, } } pub struct BamboraapacAuthType { username: Secret<String>, password: Secret<String>, account_number: Secret<String>, } impl TryFrom<&ConnectorAuthType> for BamboraapacAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { username: api_key.to_owned(), password: api_secret.to_owned(), account_number: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename = "Envelope")] #[serde(rename_all = "PascalCase")] pub struct BamboraapacPaymentsResponse { body: BodyResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct BodyResponse { submit_single_payment_response: SubmitSinglePaymentResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct SubmitSinglePaymentResponse { submit_single_payment_result: SubmitSinglePaymentResult, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct SubmitSinglePaymentResult { response: PaymentResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct PaymentResponse { response_code: u8, receipt: String, credit_card_token: Option<String>, declined_code: Option<String>, declined_message: Option<String>, } fn get_attempt_status( response_code: u8, capture_method: Option<enums::CaptureMethod>, ) -> enums::AttemptStatus { match response_code { 0 => match capture_method { Some(enums::CaptureMethod::Automatic) | None => enums::AttemptStatus::Charged, Some(enums::CaptureMethod::Manual) => enums::AttemptStatus::Authorized, _ => enums::AttemptStatus::Pending, }, 1 => enums::AttemptStatus::Failure, _ => enums::AttemptStatus::Pending, } } impl<F> TryFrom< ResponseRouterData< F, BamboraapacPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BamboraapacPaymentsResponse, PaymentsAuthorizeData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_code = item .response .body .submit_single_payment_response .submit_single_payment_result .response .response_code; let connector_transaction_id = item .response .body .submit_single_payment_response .submit_single_payment_result .response .receipt; let mandate_reference = if item.data.request.setup_future_usage == Some(enums::FutureUsage::OffSession) { let connector_mandate_id = item .response .body .submit_single_payment_response .submit_single_payment_result .response .credit_card_token; Some(MandateReference { connector_mandate_id, payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, }) } else { None }; // transaction approved if response_code == 0 { Ok(Self { status: get_attempt_status(response_code, item.data.request.capture_method), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( connector_transaction_id.to_owned(), ), redirection_data: Box::new(None), mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(connector_transaction_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } // transaction failed else { let code = item .response .body .submit_single_payment_response .submit_single_payment_result .response .declined_code .unwrap_or(NO_ERROR_CODE.to_string()); let declined_message = item .response .body .submit_single_payment_response .submit_single_payment_result .response .declined_message .unwrap_or(NO_ERROR_MESSAGE.to_string()); Ok(Self { status: get_attempt_status(response_code, item.data.request.capture_method), response: Err(ErrorResponse { status_code: item.http_code, code, message: declined_message.to_owned(), reason: Some(declined_message), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } pub fn get_setup_mandate_body(req: &types::SetupMandateRouterData) -> Result<Vec<u8>, Error> { let card_holder_name = req.get_billing_full_name()?; let auth_details = BamboraapacAuthType::try_from(&req.connector_auth_type)?; let body = match &req.request.payment_method_data { PaymentMethodData::Card(card) => { format!( r#" <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sipp="http://www.ippayments.com.au/interface/api/sipp"> <soapenv:Header/> <soapenv:Body> <sipp:TokeniseCreditCard> <sipp:tokeniseCreditCardXML> <![CDATA[ <TokeniseCreditCard> <CardNumber>{}</CardNumber> <ExpM>{}</ExpM> <ExpY>{}</ExpY> <CardHolderName>{}</CardHolderName> <TokeniseAlgorithmID>2</TokeniseAlgorithmID> <UserName>{}</UserName> <Password>{}</Password> </TokeniseCreditCard> ]]> </sipp:tokeniseCreditCardXML> </sipp:TokeniseCreditCard> </soapenv:Body> </soapenv:Envelope> "#, card.card_number.get_card_no(), card.card_exp_month.peek(), card.get_expiry_year_4_digit().peek(), card_holder_name.peek(), auth_details.username.peek(), auth_details.password.peek(), ) } _ => { return Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Bambora APAC"), ))?; } }; Ok(body.as_bytes().to_vec()) } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename = "Envelope")] #[serde(rename_all = "PascalCase")] pub struct BamboraapacMandateResponse { body: MandateBodyResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct MandateBodyResponse { tokenise_credit_card_response: TokeniseCreditCardResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct TokeniseCreditCardResponse { tokenise_credit_card_result: TokeniseCreditCardResult, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct TokeniseCreditCardResult { tokenise_credit_card_response: MandateResponseBody, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct MandateResponseBody { return_value: u8, token: Option<String>, } impl<F> TryFrom< ResponseRouterData< F, BamboraapacMandateResponse, SetupMandateRequestData, PaymentsResponseData, >, > for RouterData<F, SetupMandateRequestData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BamboraapacMandateResponse, SetupMandateRequestData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_code = item .response .body .tokenise_credit_card_response .tokenise_credit_card_result .tokenise_credit_card_response .return_value; let connector_mandate_id = item .response .body .tokenise_credit_card_response .tokenise_credit_card_result .tokenise_credit_card_response .token .ok_or(errors::ConnectorError::MissingConnectorMandateID)?; // transaction approved if response_code == 0 { Ok(Self { status: enums::AttemptStatus::Charged, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(Some(MandateReference { connector_mandate_id: Some(connector_mandate_id), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None, })), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } // transaction failed else { Ok(Self { status: enums::AttemptStatus::Failure, response: Err(ErrorResponse { status_code: item.http_code, code: NO_ERROR_CODE.to_string(), message: NO_ERROR_MESSAGE.to_string(), reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } // capture body in soap format pub fn get_capture_body( req: &BamboraapacRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Vec<u8>, Error> { let receipt = req.router_data.request.connector_transaction_id.to_owned(); let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?; let body = format!( r#" <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dts="http://www.ippayments.com.au/interface/api/dts"> <soapenv:Body> <dts:SubmitSingleCapture> <dts:trnXML> <![CDATA[ <Capture> <Receipt>{}</Receipt> <Amount>{}</Amount> <Security> <UserName>{}</UserName> <Password>{}</Password> </Security> </Capture> ]]> </dts:trnXML> </dts:SubmitSingleCapture> </soapenv:Body> </soapenv:Envelope> "#, receipt, req.amount, auth_details.username.peek(), auth_details.password.peek(), ); Ok(body.as_bytes().to_vec()) } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename = "Envelope")] #[serde(rename_all = "PascalCase")] pub struct BamboraapacCaptureResponse { body: CaptureBodyResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct CaptureBodyResponse { submit_single_capture_response: SubmitSingleCaptureResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct SubmitSingleCaptureResponse { submit_single_capture_result: SubmitSingleCaptureResult, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct SubmitSingleCaptureResult { response: CaptureResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct CaptureResponse { response_code: u8, receipt: String, declined_code: Option<String>, declined_message: Option<String>, } impl<F> TryFrom< ResponseRouterData< F, BamboraapacCaptureResponse, PaymentsCaptureData, PaymentsResponseData, >, > for RouterData<F, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BamboraapacCaptureResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_code = item .response .body .submit_single_capture_response .submit_single_capture_result .response .response_code; let connector_transaction_id = item .response .body .submit_single_capture_response .submit_single_capture_result .response .receipt; // storing receipt_id of authorize to metadata for future usage let connector_metadata = Some(serde_json::json!(BamboraapacMeta { authorize_id: item.data.request.connector_transaction_id.to_owned() })); // transaction approved if response_code == 0 { Ok(Self { status: enums::AttemptStatus::Charged, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( connector_transaction_id.to_owned(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some(connector_transaction_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } // transaction failed else { let code = item .response .body .submit_single_capture_response .submit_single_capture_result .response .declined_code .unwrap_or(NO_ERROR_CODE.to_string()); let declined_message = item .response .body .submit_single_capture_response .submit_single_capture_result .response .declined_message .unwrap_or(NO_ERROR_MESSAGE.to_string()); Ok(Self { status: enums::AttemptStatus::Failure, response: Err(ErrorResponse { status_code: item.http_code, code, message: declined_message.to_owned(), reason: Some(declined_message), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } // refund body in soap format pub fn get_refund_body( req: &BamboraapacRouterData<&types::RefundExecuteRouterData>, ) -> Result<Vec<u8>, Error> { let receipt = req.router_data.request.connector_transaction_id.to_owned(); let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?; let body = format!( r#" <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dts="http://www.ippayments.com.au/interface/api/dts"> <soapenv:Header/> <soapenv:Body> <dts:SubmitSingleRefund> <dts:trnXML> <![CDATA[ <Refund> <CustRef>{}</CustRef> <Receipt>{}</Receipt> <Amount>{}</Amount> <Security> <UserName>{}</UserName> <Password>{}</Password> </Security> </Refund> ]]> </dts:trnXML> </dts:SubmitSingleRefund> </soapenv:Body> </soapenv:Envelope> "#, req.router_data.request.refund_id.to_owned(), receipt, req.amount, auth_details.username.peek(), auth_details.password.peek(), ); Ok(body.as_bytes().to_vec()) } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename = "Envelope")] #[serde(rename_all = "PascalCase")] pub struct BamboraapacRefundsResponse { body: RefundBodyResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct RefundBodyResponse { submit_single_refund_response: SubmitSingleRefundResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct SubmitSingleRefundResponse { submit_single_refund_result: SubmitSingleRefundResult, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct SubmitSingleRefundResult { response: RefundResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct RefundResponse { response_code: u8, receipt: String, declined_code: Option<String>, declined_message: Option<String>, } fn get_status(item: u8) -> enums::RefundStatus { match item { 0 => enums::RefundStatus::Success, 1 => enums::RefundStatus::Failure, _ => enums::RefundStatus::Pending, } } impl<F> TryFrom<ResponseRouterData<F, BamboraapacRefundsResponse, RefundsData, RefundsResponseData>> for RouterData<F, RefundsData, RefundsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, BamboraapacRefundsResponse, RefundsData, RefundsResponseData>, ) -> Result<Self, Self::Error> { let response_code = item .response .body .submit_single_refund_response .submit_single_refund_result .response .response_code; let connector_refund_id = item .response .body .submit_single_refund_response .submit_single_refund_result .response .receipt; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: connector_refund_id.to_owned(), refund_status: get_status(response_code), }), ..item.data }) } } pub fn get_payment_sync_body(req: &types::PaymentsSyncRouterData) -> Result<Vec<u8>, Error> { let auth_details = BamboraapacAuthType::try_from(&req.connector_auth_type)?; let connector_transaction_id = req .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; let body = format!( r#" <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dts="http://www.ippayments.com.au/interface/api/dts"> <soapenv:Header/> <soapenv:Body> <dts:QueryTransaction> <dts:queryXML> <![CDATA[ <QueryTransaction> <Criteria> <AccountNumber>{}</AccountNumber> <TrnStartTimestamp>2024-06-23 00:00:00</TrnStartTimestamp> <TrnEndTimestamp>2099-12-31 23:59:59</TrnEndTimestamp> <Receipt>{}</Receipt> </Criteria> <Security> <UserName>{}</UserName> <Password>{}</Password> </Security> </QueryTransaction> ]]> </dts:queryXML> </dts:QueryTransaction> </soapenv:Body> </soapenv:Envelope> "#, auth_details.account_number.peek(), connector_transaction_id, auth_details.username.peek(), auth_details.password.peek(), ); Ok(body.as_bytes().to_vec()) } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename = "Envelope")] #[serde(rename_all = "PascalCase")] pub struct BamboraapacSyncResponse { body: SyncBodyResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct SyncBodyResponse { query_transaction_response: QueryTransactionResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct QueryTransactionResponse { query_transaction_result: QueryTransactionResult, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct QueryTransactionResult { query_response: QueryResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct QueryResponse { response: SyncResponse, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct SyncResponse { response_code: u8, receipt: String, declined_code: Option<String>, declined_message: Option<String>, } impl<F> TryFrom<ResponseRouterData<F, BamboraapacSyncResponse, PaymentsSyncData, PaymentsResponseData>> for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, BamboraapacSyncResponse, PaymentsSyncData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let response_code = item .response .body .query_transaction_response .query_transaction_result .query_response .response .response_code; let connector_transaction_id = item .response .body .query_transaction_response .query_transaction_result .query_response .response .receipt; // transaction approved if response_code == 0 { Ok(Self { status: get_attempt_status(response_code, item.data.request.capture_method), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( connector_transaction_id.to_owned(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(connector_transaction_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } // transaction failed else { let code = item .response .body .query_transaction_response .query_transaction_result .query_response .response .declined_code .unwrap_or(NO_ERROR_CODE.to_string()); let declined_message = item .response .body .query_transaction_response .query_transaction_result .query_response .response .declined_message .unwrap_or(NO_ERROR_MESSAGE.to_string()); Ok(Self { status: get_attempt_status(response_code, item.data.request.capture_method), response: Err(ErrorResponse { status_code: item.http_code, code, message: declined_message.to_owned(), reason: Some(declined_message), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } } } pub fn get_refund_sync_body(req: &types::RefundSyncRouterData) -> Result<Vec<u8>, Error> { let auth_details = BamboraapacAuthType::try_from(&req.connector_auth_type)?; let body = format!( r#" <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dts="http://www.ippayments.com.au/interface/api/dts"> <soapenv:Header/> <soapenv:Body> <dts:QueryTransaction> <dts:queryXML> <![CDATA[ <QueryTransaction> <Criteria> <AccountNumber>{}</AccountNumber> <TrnStartTimestamp>2024-06-23 00:00:00</TrnStartTimestamp> <TrnEndTimestamp>2099-12-31 23:59:59</TrnEndTimestamp> <CustRef>{}</CustRef> </Criteria> <Security> <UserName>{}</UserName> <Password>{}</Password> </Security> </QueryTransaction> ]]> </dts:queryXML> </dts:QueryTransaction> </soapenv:Body> </soapenv:Envelope> "#, auth_details.account_number.peek(), req.request.refund_id, auth_details.username.peek(), auth_details.password.peek(), ); Ok(body.as_bytes().to_vec()) } impl<F> TryFrom<ResponseRouterData<F, BamboraapacSyncResponse, RefundsData, RefundsResponseData>> for RouterData<F, RefundsData, RefundsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, BamboraapacSyncResponse, RefundsData, RefundsResponseData>, ) -> Result<Self, Self::Error> { let response_code = item .response .body .query_transaction_response .query_transaction_result .query_response .response .response_code; let connector_refund_id = item .response .body .query_transaction_response .query_transaction_result .query_response .response .receipt; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: connector_refund_id.to_owned(), refund_status: get_status(response_code), }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct BamboraapacErrorResponse { pub declined_code: Option<String>, pub declined_message: Option<String>, }
crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
hyperswitch_connectors::src::connectors::bamboraapac::transformers
7,141
true
// File: crates/hyperswitch_connectors/src/connectors/checkbook/transformers.rs // Module: hyperswitch_connectors::src::connectors::checkbook::transformers use api_models::webhooks::IncomingWebhookEvent; use common_utils::{pii, types::FloatMajorUnit}; use hyperswitch_domain_models::{ payment_method_data::{BankTransferData, PaymentMethodData}, router_data::{ConnectorAuthType, RouterData}, router_request_types::ResponseId, router_response_types::PaymentsResponseData, types::PaymentsAuthorizeRouterData, }; use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::ResponseRouterData, utils::{get_unimplemented_payment_method_error_message, RouterData as _}, }; #[derive(Debug, Serialize)] pub struct CheckbookPaymentsRequest { name: Secret<String>, recipient: pii::Email, amount: FloatMajorUnit, description: String, } impl TryFrom<(FloatMajorUnit, &PaymentsAuthorizeRouterData)> for CheckbookPaymentsRequest { type Error = error_stack::Report<ConnectorError>; fn try_from( (amount, item): (FloatMajorUnit, &PaymentsAuthorizeRouterData), ) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data { BankTransferData::AchBankTransfer {} => Ok(Self { name: item.get_billing_full_name()?, recipient: item.get_billing_email()?, amount, description: item.get_description()?, }), _ => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Checkbook"), ) .into()), }, _ => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Checkbook"), ) .into()), } } } pub struct CheckbookAuthType { pub(super) publishable_key: Secret<String>, pub(super) secret_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for CheckbookAuthType { type Error = error_stack::Report<ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { key1, api_key } => Ok(Self { publishable_key: key1.to_owned(), secret_key: api_key.to_owned(), }), _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CheckbookPaymentStatus { Unpaid, InProcess, Paid, Mailed, Printed, Failed, Expired, Void, #[default] Processing, } impl From<CheckbookPaymentStatus> for common_enums::AttemptStatus { fn from(item: CheckbookPaymentStatus) -> Self { match item { CheckbookPaymentStatus::Paid | CheckbookPaymentStatus::Mailed | CheckbookPaymentStatus::Printed => Self::Charged, CheckbookPaymentStatus::Failed | CheckbookPaymentStatus::Expired => Self::Failure, CheckbookPaymentStatus::Unpaid => Self::AuthenticationPending, CheckbookPaymentStatus::InProcess | CheckbookPaymentStatus::Processing => Self::Pending, CheckbookPaymentStatus::Void => Self::Voided, } } } impl From<CheckbookPaymentStatus> for IncomingWebhookEvent { fn from(status: CheckbookPaymentStatus) -> Self { match status { CheckbookPaymentStatus::Mailed | CheckbookPaymentStatus::Printed | CheckbookPaymentStatus::Paid => Self::PaymentIntentSuccess, CheckbookPaymentStatus::Failed | CheckbookPaymentStatus::Expired => { Self::PaymentIntentFailure } CheckbookPaymentStatus::Unpaid | CheckbookPaymentStatus::InProcess | CheckbookPaymentStatus::Processing => Self::PaymentIntentProcessing, CheckbookPaymentStatus::Void => Self::PaymentIntentCancelled, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CheckbookPaymentsResponse { pub status: CheckbookPaymentStatus, pub id: String, pub amount: Option<FloatMajorUnit>, pub description: Option<String>, pub name: Option<String>, pub recipient: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, CheckbookPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, CheckbookPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct CheckbookErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, }
crates/hyperswitch_connectors/src/connectors/checkbook/transformers.rs
hyperswitch_connectors::src::connectors::checkbook::transformers
1,215
true
// File: crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs // Module: hyperswitch_connectors::src::connectors::amazonpay::transformers use std::collections::HashMap; use common_enums::{enums, CaptureMethod}; use common_utils::{errors::CustomResult, pii, types::StringMajorUnit}; use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::{consts, errors}; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{is_refund_failure, RouterData as _}, }; pub struct AmazonpayRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, } impl<T> From<(StringMajorUnit, T)> for AmazonpayRouterData<T> { fn from((amount, item): (StringMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AmazonpayFinalizeRequest { charge_amount: ChargeAmount, shipping_address: AddressDetails, payment_intent: PaymentIntent, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct ChargeAmount { amount: StringMajorUnit, currency_code: common_enums::Currency, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AddressDetails { name: Secret<String>, address_line_1: Secret<String>, address_line_2: Option<Secret<String>>, address_line_3: Option<Secret<String>>, city: String, state_or_region: Secret<String>, postal_code: Secret<String>, country_code: Option<common_enums::CountryAlpha2>, phone_number: Secret<String>, } #[derive(Debug, Serialize, PartialEq)] pub enum PaymentIntent { AuthorizeWithCapture, } fn get_amazonpay_capture_type( item: Option<CaptureMethod>, ) -> CustomResult<PaymentIntent, errors::ConnectorError> { match item { Some(CaptureMethod::Automatic) | None => Ok(PaymentIntent::AuthorizeWithCapture), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } impl TryFrom<&AmazonpayRouterData<&PaymentsAuthorizeRouterData>> for AmazonpayFinalizeRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &AmazonpayRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let charge_amount = ChargeAmount { amount: item.amount.clone(), currency_code: item.router_data.request.currency, }; let shipping_address = AddressDetails { name: item.router_data.get_required_shipping_full_name()?, address_line_1: item.router_data.get_required_shipping_line1()?, address_line_2: item.router_data.get_optional_shipping_line2(), address_line_3: item.router_data.get_optional_shipping_line3(), city: item.router_data.get_required_shipping_city()?, state_or_region: item.router_data.get_required_shipping_state()?, postal_code: item.router_data.get_required_shipping_zip()?, country_code: item.router_data.get_optional_shipping_country(), phone_number: item.router_data.get_required_shipping_phone_number()?, }; let payment_intent = get_amazonpay_capture_type(item.router_data.request.capture_method)?; Ok(Self { charge_amount, shipping_address, payment_intent, }) } } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AmazonpayFinalizeResponse { checkout_session_id: String, web_checkout_details: WebCheckoutDetails, product_type: Option<String>, payment_details: Option<PaymentDetails>, cart_details: CartDetails, charge_permission_type: String, order_type: Option<String>, recurring_metadata: Option<RecurringMetadata>, payment_method_on_file_metadata: Option<String>, processor_specifications: Option<String>, merchant_details: Option<String>, merchant_metadata: Option<MerchantMetadata>, supplementary_data: Option<String>, buyer: Option<BuyerDetails>, billing_address: Option<AddressDetails>, payment_preferences: Option<String>, status_details: FinalizeStatusDetails, shipping_address: Option<AddressDetails>, platform_id: Option<String>, charge_permission_id: String, charge_id: String, constraints: Option<String>, creation_timestamp: String, expiration_timestamp: Option<String>, store_id: Option<String>, provider_metadata: Option<ProviderMetadata>, release_environment: Option<ReleaseEnvironment>, checkout_button_text: Option<String>, delivery_specifications: Option<DeliverySpecifications>, tokens: Option<String>, disbursement_details: Option<String>, channel_type: Option<String>, payment_processing_meta_data: PaymentProcessingMetaData, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct WebCheckoutDetails { checkout_review_return_url: Option<String>, checkout_result_return_url: Option<String>, amazon_pay_redirect_url: Option<String>, authorize_result_return_url: Option<String>, sign_in_return_url: Option<String>, sign_in_cancel_url: Option<String>, checkout_error_url: Option<String>, sign_in_error_url: Option<String>, amazon_pay_decline_url: Option<String>, checkout_cancel_url: Option<String>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentDetails { payment_intent: String, can_handle_pending_authorization: bool, charge_amount: ChargeAmount, total_order_amount: ChargeAmount, presentment_currency: String, soft_descriptor: String, allow_overcharge: bool, extend_expiration: bool, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct CartDetails { line_items: Vec<String>, delivery_options: Vec<DeliveryOptions>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DeliveryOptions { id: String, price: ChargeAmount, shipping_method: ShippingMethod, is_default: bool, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct ShippingMethod { shipping_method_name: String, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct RecurringMetadata { frequency: Frequency, amount: ChargeAmount, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Frequency { unit: String, value: String, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct BuyerDetails { buyer_id: Secret<String>, name: Secret<String>, email: pii::Email, phone_number: Secret<String>, prime_membership_types: Vec<String>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct FinalizeStatusDetails { state: FinalizeState, reason_code: Option<String>, reason_description: Option<String>, last_updated_timestamp: String, } #[derive(Debug, Deserialize, Serialize, PartialEq)] pub enum FinalizeState { Open, Completed, Canceled, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DeliverySpecifications { special_restrictions: Vec<String>, address_restrictions: AddressRestrictions, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AddressRestrictions { r#type: String, restrictions: HashMap<String, Restriction>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Restriction { pub states_or_regions: Vec<Secret<String>>, pub zip_codes: Vec<Secret<String>>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentProcessingMetaData { payment_processing_model: String, } impl From<FinalizeState> for common_enums::AttemptStatus { fn from(item: FinalizeState) -> Self { match item { FinalizeState::Open => Self::Pending, FinalizeState::Completed => Self::Charged, FinalizeState::Canceled => Self::Failure, } } } impl<F, T> TryFrom<ResponseRouterData<F, AmazonpayFinalizeResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AmazonpayFinalizeResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response.status_details.state { FinalizeState::Canceled => { Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: consts::NO_ERROR_CODE.to_owned(), message: "Checkout was not successfully completed".to_owned(), reason: Some("Checkout was not successfully completed due to buyer abandoment, payment decline, or because checkout wasn't confirmed with Finalize Checkout Session.".to_owned()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.checkout_session_id), network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } FinalizeState::Open | FinalizeState::Completed => { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status_details.state), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.charge_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.checkout_session_id), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } } } pub struct AmazonpayAuthType { pub(super) public_key: Secret<String>, pub(super) private_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for AmazonpayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { public_key: api_key.to_owned(), private_key: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "PascalCase")] pub enum AmazonpayPaymentStatus { AuthorizationInitiated, Authorized, Canceled, Captured, CaptureInitiated, Declined, } impl From<AmazonpayPaymentStatus> for common_enums::AttemptStatus { fn from(item: AmazonpayPaymentStatus) -> Self { match item { AmazonpayPaymentStatus::AuthorizationInitiated => Self::Pending, AmazonpayPaymentStatus::Authorized => Self::Authorized, AmazonpayPaymentStatus::Canceled => Self::Voided, AmazonpayPaymentStatus::Captured => Self::Charged, AmazonpayPaymentStatus::CaptureInitiated => Self::CaptureInitiated, AmazonpayPaymentStatus::Declined => Self::CaptureFailed, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AmazonpayPaymentsResponse { charge_id: String, charge_amount: ChargeAmount, charge_permission_id: String, capture_amount: Option<ChargeAmount>, refunded_amount: Option<ChargeAmount>, soft_descriptor: Option<String>, provider_metadata: Option<ProviderMetadata>, converted_amount: Option<ChargeAmount>, conversion_rate: Option<f64>, channel: Option<String>, charge_initiator: Option<String>, status_details: PaymentsStatusDetails, creation_timestamp: String, expiration_timestamp: String, release_environment: Option<ReleaseEnvironment>, merchant_metadata: Option<MerchantMetadata>, platform_id: Option<String>, web_checkout_details: Option<WebCheckoutDetails>, disbursement_details: Option<String>, payment_method: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct ProviderMetadata { provider_reference_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PaymentsStatusDetails { state: AmazonpayPaymentStatus, reason_code: Option<String>, reason_description: Option<String>, last_updated_timestamp: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum ReleaseEnvironment { Sandbox, Live, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MerchantMetadata { merchant_reference_id: Option<String>, merchant_store_name: Option<String>, note_to_buyer: Option<String>, custom_information: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, AmazonpayPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, AmazonpayPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response.status_details.state { AmazonpayPaymentStatus::Canceled => { Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: consts::NO_ERROR_CODE.to_owned(), message: "Charge was canceled by Amazon or by the merchant".to_owned(), reason: Some("Charge was canceled due to expiration, Amazon, buyer, merchant action, or charge permission cancellation.".to_owned()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.charge_id), network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } AmazonpayPaymentStatus::Declined => { Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: consts::NO_ERROR_CODE.to_owned(), message: "The authorization or capture was declined".to_owned(), reason: Some("Charge was declined due to soft/hard decline, Amazon rejection, or internal processing failure.".to_owned()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.charge_id), network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } _ => { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status_details.state), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.charge_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } } } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AmazonpayRefundRequest { pub refund_amount: ChargeAmount, pub charge_id: String, } impl<F> TryFrom<&AmazonpayRouterData<&RefundsRouterData<F>>> for AmazonpayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &AmazonpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let refund_amount = ChargeAmount { amount: item.amount.clone(), currency_code: item.router_data.request.currency, }; let charge_id = item.router_data.request.connector_transaction_id.clone(); Ok(Self { refund_amount, charge_id, }) } } #[derive(Debug, Serialize, Deserialize, Clone)] pub enum RefundStatus { RefundInitiated, Refunded, Declined, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::RefundInitiated => Self::Pending, RefundStatus::Refunded => Self::Success, RefundStatus::Declined => Self::Failure, } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RefundResponse { refund_id: String, charge_id: String, creation_timestamp: String, refund_amount: ChargeAmount, status_details: RefundStatusDetails, soft_descriptor: String, release_environment: ReleaseEnvironment, disbursement_details: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RefundStatusDetails { state: RefundStatus, reason_code: Option<String>, reason_description: Option<String>, last_updated_timestamp: String, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { match item.response.status_details.state { RefundStatus::Declined => { Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(ErrorResponse { code: consts::NO_ERROR_CODE.to_owned(), message: "Amazon has declined the refund.".to_owned(), reason: Some("Amazon has declined the refund because maximum amount has been refunded or there was some other issue.".to_owned()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.charge_id), network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }) } _ => { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.refund_id, refund_status: enums::RefundStatus::from(item.response.status_details.state), }), ..item.data }) } } } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status_details.state); let response = if is_refund_failure(refund_status) { Err(ErrorResponse { code: consts::NO_ERROR_CODE.to_owned(), message: "Amazon has declined the refund.".to_owned(), reason: Some("Amazon has declined the refund because maximum amount has been refunded or there was some other issue.".to_owned()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.refund_id.clone()), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { Ok(RefundsResponseData { connector_refund_id: item.response.refund_id.to_string(), refund_status, }) }; Ok(Self { response, ..item.data }) } } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AmazonpayErrorResponse { pub reason_code: String, pub message: String, }
crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs
hyperswitch_connectors::src::connectors::amazonpay::transformers
4,465
true
// File: crates/smithy/src/lib.rs // Module: smithy::src::lib // crates/smithy/lib.rs - Fixed with proper optional type handling in flattening use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::quote; use smithy_core::{SmithyConstraint, SmithyEnumVariant, SmithyField}; use syn::{parse_macro_input, Attribute, DeriveInput, Fields, Lit, Meta, Variant}; /// Derive macro for generating Smithy models from Rust structs and enums #[proc_macro_derive(SmithyModel, attributes(smithy))] pub fn derive_smithy_model(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); match generate_smithy_impl(&input) { Ok(tokens) => tokens.into(), Err(err) => err.to_compile_error().into(), } } fn generate_smithy_impl(input: &DeriveInput) -> syn::Result<TokenStream2> { let name = &input.ident; let (namespace, is_mixin) = extract_namespace_and_mixin(&input.attrs)?; match &input.data { syn::Data::Struct(data_struct) => { generate_struct_impl(name, &namespace, data_struct, &input.attrs, is_mixin) } syn::Data::Enum(data_enum) => generate_enum_impl(name, &namespace, data_enum, &input.attrs), _ => Err(syn::Error::new_spanned( input, "SmithyModel can only be derived for structs and enums", )), } } fn generate_struct_impl( name: &syn::Ident, namespace: &str, data_struct: &syn::DataStruct, attrs: &[Attribute], is_mixin: bool, ) -> syn::Result<TokenStream2> { let fields = extract_fields(&data_struct.fields)?; let struct_doc = extract_documentation(attrs); let struct_doc_expr = struct_doc .as_ref() .map(|doc| quote! { Some(#doc.to_string()) }) .unwrap_or(quote! { None }); let field_implementations = fields.iter().map(|field| { let field_name = &field.name; let value_type = &field.value_type; let documentation = &field.documentation; let constraints = &field.constraints; let optional = field.optional; let flatten = field.flatten; if flatten { // Extract the inner type from Option<T> if it's an optional type let inner_type = if value_type.starts_with("Option<") && value_type.ends_with('>') { let start_idx = "Option<".len(); let end_idx = value_type.len() - 1; &value_type[start_idx..end_idx] } else { value_type }; let inner_type_ident = syn::parse_str::<syn::Type>(inner_type).unwrap(); // For flattened fields, we merge the fields from the inner type // but we don't add the field itself to the structure quote! { { let flattened_model = <#inner_type_ident as smithy_core::SmithyModelGenerator>::generate_smithy_model(); let flattened_struct_name = stringify!(#inner_type_ident).to_string(); for (shape_name, shape) in flattened_model.shapes { if shape_name == flattened_struct_name { match shape { smithy_core::SmithyShape::Structure { members: flattened_members, .. } | smithy_core::SmithyShape::Union { members: flattened_members, .. } => { members.extend(flattened_members); } _ => { // Potentially handle other shapes or log a warning } } } else { shapes.insert(shape_name, shape); } } } } } else { let field_doc = documentation .as_ref() .map(|doc| quote! { Some(#doc.to_string()) }) .unwrap_or(quote! { None }); let mut all_constraints = constraints.clone(); if !optional && !all_constraints.iter().any(|c| matches!(c, SmithyConstraint::Required)) { all_constraints.push(SmithyConstraint::Required); } let traits = if all_constraints.is_empty() { quote! { vec![] } } else { let trait_tokens = all_constraints .iter() .map(|constraint| match constraint { SmithyConstraint::Pattern(pattern) => quote! { smithy_core::SmithyTrait::Pattern { pattern: #pattern.to_string() } }, SmithyConstraint::Range(min, max) => { let min_expr = min.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None }); let max_expr = max.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None }); quote! { smithy_core::SmithyTrait::Range { min: #min_expr, max: #max_expr } } }, SmithyConstraint::Length(min, max) => { let min_expr = min.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None }); let max_expr = max.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None }); quote! { smithy_core::SmithyTrait::Length { min: #min_expr, max: #max_expr } } }, SmithyConstraint::Required => quote! { smithy_core::SmithyTrait::Required }, SmithyConstraint::HttpLabel => quote! { smithy_core::SmithyTrait::HttpLabel }, SmithyConstraint::HttpQuery(name) => quote! { smithy_core::SmithyTrait::HttpQuery { name: #name.to_string() } }, }) .collect::<Vec<_>>(); quote! { vec![#(#trait_tokens),*] } }; quote! { { let (target_type, new_shapes) = smithy_core::types::resolve_type_and_generate_shapes(#value_type, &mut shapes).unwrap(); shapes.extend(new_shapes); members.insert(#field_name.to_string(), smithy_core::SmithyMember { target: target_type, documentation: #field_doc, traits: #traits, }); } } } }); let traits_expr = if is_mixin { quote! { vec![smithy_core::SmithyTrait::Mixin] } } else { quote! { vec![] } }; let expanded = quote! { impl smithy_core::SmithyModelGenerator for #name { fn generate_smithy_model() -> smithy_core::SmithyModel { let mut shapes = std::collections::HashMap::new(); let mut members = std::collections::HashMap::new(); #(#field_implementations;)* let shape = smithy_core::SmithyShape::Structure { members, documentation: #struct_doc_expr, traits: #traits_expr }; shapes.insert(stringify!(#name).to_string(), shape); smithy_core::SmithyModel { namespace: #namespace.to_string(), shapes } } } }; Ok(expanded) } fn generate_enum_impl( name: &syn::Ident, namespace: &str, data_enum: &syn::DataEnum, attrs: &[Attribute], ) -> syn::Result<TokenStream2> { let variants = extract_enum_variants(&data_enum.variants)?; let serde_enum_attrs = parse_serde_enum_attributes(attrs)?; let enum_doc = extract_documentation(attrs); let enum_doc_expr = enum_doc .as_ref() .map(|doc| quote! { Some(#doc.to_string()) }) .unwrap_or(quote! { None }); // Check if this is a string enum (all variants are unit variants) or a union let is_string_enum = variants.iter().all(|v| v.fields.is_empty()); if is_string_enum { // Generate as Smithy enum let variant_implementations = variants .iter() .map(|variant| { let variant_name = &variant.name; let variant_doc = variant .documentation .as_ref() .map(|doc| quote! { Some(#doc.to_string()) }) .unwrap_or(quote! { None }); // Apply serde rename transformation if specified let rename_all = serde_enum_attrs.rename_all.as_deref(); let transformed_name = if let Some(rename_pattern) = rename_all { // Generate the transformation at compile time let transformed = transform_variant_name(variant_name, Some(rename_pattern)); quote! { #transformed.to_string() } } else { quote! { #variant_name.to_string() } }; quote! { enum_values.insert(#transformed_name, smithy_core::SmithyEnumValue { name: #transformed_name, documentation: #variant_doc, is_default: false, }); } }) .collect::<Vec<_>>(); let expanded = quote! { impl smithy_core::SmithyModelGenerator for #name { fn generate_smithy_model() -> smithy_core::SmithyModel { let mut shapes = std::collections::HashMap::new(); let mut enum_values = std::collections::HashMap::new(); #(#variant_implementations)* let shape = smithy_core::SmithyShape::Enum { values: enum_values, documentation: #enum_doc_expr, traits: vec![] }; shapes.insert(stringify!(#name).to_string(), shape); smithy_core::SmithyModel { namespace: #namespace.to_string(), shapes } } } }; Ok(expanded) } else { // Generate as Smithy union let variant_implementations = variants .iter() .filter_map(|variant| { let variant_name = &variant.name; let variant_doc = variant .documentation .as_ref() .map(|doc| quote! { Some(#doc.to_string()) }) .unwrap_or(quote! { None }); let target_type_expr = if variant.fields.is_empty() { // If there are no fields with `value_type`, this variant should be skipped. return None; } else if variant.fields.len() == 1 { // Single field - reference the type directly instead of creating a wrapper let field = &variant.fields[0]; let field_value_type = &field.value_type; if field_value_type.is_empty() { return None; } quote! { { let (target_type, new_shapes) = smithy_core::types::resolve_type_and_generate_shapes(#field_value_type, &mut shapes).unwrap(); shapes.extend(new_shapes); target_type } } } else { // Multiple fields - create an inline structure let inline_struct_members = variant.fields.iter().map(|field| { let field_name = &field.name; let field_value_type = &field.value_type; let field_doc = field .documentation .as_ref() .map(|doc| quote! { Some(#doc.to_string()) }) .unwrap_or(quote! { None }); let mut field_constraints = field.constraints.clone(); if !field.optional && !field_constraints.iter().any(|c| matches!(c, SmithyConstraint::Required)) { field_constraints.push(SmithyConstraint::Required); } let field_traits = if field_constraints.is_empty() { quote! { vec![] } } else { let trait_tokens = field_constraints .iter() .map(|constraint| match constraint { SmithyConstraint::Pattern(pattern) => quote! { smithy_core::SmithyTrait::Pattern { pattern: #pattern.to_string() } }, SmithyConstraint::Range(min, max) => { let min_expr = min.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None }); let max_expr = max.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None }); quote! { smithy_core::SmithyTrait::Range { min: #min_expr, max: #max_expr } } }, SmithyConstraint::Length(min, max) => { let min_expr = min.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None }); let max_expr = max.map(|v| quote! { Some(#v) }).unwrap_or(quote! { None }); quote! { smithy_core::SmithyTrait::Length { min: #min_expr, max: #max_expr } } }, SmithyConstraint::Required => quote! { smithy_core::SmithyTrait::Required }, SmithyConstraint::HttpLabel => quote! { smithy_core::SmithyTrait::HttpLabel }, SmithyConstraint::HttpQuery(name) => quote! { smithy_core::SmithyTrait::HttpQuery { name: #name.to_string() } }, }) .collect::<Vec<_>>(); quote! { vec![#(#trait_tokens),*] } }; quote! { { let (field_target, field_shapes) = smithy_core::types::resolve_type_and_generate_shapes(#field_value_type, &mut shapes).unwrap(); shapes.extend(field_shapes); inline_members.insert(#field_name.to_string(), smithy_core::SmithyMember { target: field_target, documentation: #field_doc, traits: #field_traits, }); } } }); quote! { { let inline_struct_name = format!("{}{}Data", stringify!(#name), #variant_name); let mut inline_members = std::collections::HashMap::new(); #(#inline_struct_members)* let inline_shape = smithy_core::SmithyShape::Structure { members: inline_members, documentation: None, traits: vec![], }; shapes.insert(inline_struct_name.clone(), inline_shape); inline_struct_name } } }; // Apply serde rename transformation if specified let rename_all = serde_enum_attrs.rename_all.as_deref(); let transformed_name = if let Some(rename_pattern) = rename_all { // Generate the transformation at compile time let transformed = transform_variant_name(variant_name, Some(rename_pattern)); quote! { #transformed.to_string() } } else { quote! { #variant_name.to_string() } }; Some(quote! { let target_type = #target_type_expr; members.insert(#transformed_name, smithy_core::SmithyMember { target: target_type, documentation: #variant_doc, traits: vec![] }); }) }) .collect::<Vec<_>>(); let expanded = quote! { impl smithy_core::SmithyModelGenerator for #name { fn generate_smithy_model() -> smithy_core::SmithyModel { let mut shapes = std::collections::HashMap::new(); let mut members = std::collections::HashMap::new(); #(#variant_implementations;)* let shape = smithy_core::SmithyShape::Union { members, documentation: #enum_doc_expr, traits: vec![] }; shapes.insert(stringify!(#name).to_string(), shape); smithy_core::SmithyModel { namespace: #namespace.to_string(), shapes } } } }; Ok(expanded) } } fn extract_namespace_and_mixin(attrs: &[Attribute]) -> syn::Result<(String, bool)> { for attr in attrs { if attr.path().is_ident("smithy") { let mut namespace = None; let mut mixin = false; attr.parse_nested_meta(|meta| { if meta.path.is_ident("namespace") { if let Ok(value) = meta.value() { if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() { namespace = Some(lit_str.value()); } } } else if meta.path.is_ident("mixin") { if let Ok(value) = meta.value() { if let Ok(Lit::Bool(lit_bool)) = value.parse::<Lit>() { mixin = lit_bool.value; } } } Ok(()) })?; // Propagate parsing errors return Ok(( namespace.unwrap_or_else(|| "com.hyperswitch.default".to_string()), mixin, )); } } Ok(("com.hyperswitch.default".to_string(), false)) } fn extract_fields(fields: &Fields) -> syn::Result<Vec<SmithyField>> { let mut smithy_fields = Vec::new(); match fields { Fields::Named(fields_named) => { for field in &fields_named.named { let field_name = field.ident.as_ref().unwrap().to_string(); let field_attrs = parse_smithy_field_attributes(&field.attrs)?; let serde_attrs = parse_serde_attributes(&field.attrs)?; if let Some(value_type) = field_attrs.value_type { let documentation = extract_documentation(&field.attrs); let optional = value_type.trim().starts_with("Option<"); smithy_fields.push(SmithyField { name: field_name, value_type, constraints: field_attrs.constraints, documentation, optional, flatten: serde_attrs.flatten, }); } } } _ => { return Err(syn::Error::new_spanned( fields, "Only named fields are supported", )) } } Ok(smithy_fields) } fn extract_enum_variants( variants: &syn::punctuated::Punctuated<Variant, syn::token::Comma>, ) -> syn::Result<Vec<SmithyEnumVariant>> { let mut smithy_variants = Vec::new(); for variant in variants { let variant_name = variant.ident.to_string(); let documentation = extract_documentation(&variant.attrs); let variant_attrs = parse_smithy_field_attributes(&variant.attrs)?; // Extract fields from the variant let fields = match &variant.fields { Fields::Unit => Vec::new(), Fields::Named(fields_named) => { let mut variant_fields = Vec::new(); for field in &fields_named.named { let field_name = field.ident.as_ref().unwrap().to_string(); let field_attrs = parse_smithy_field_attributes(&field.attrs)?; if let Some(value_type) = field_attrs.value_type { let field_documentation = extract_documentation(&field.attrs); let optional = value_type.trim().starts_with("Option<"); variant_fields.push(SmithyField { name: field_name, value_type, constraints: field_attrs.constraints, documentation: field_documentation, optional, flatten: false, }); } } variant_fields } Fields::Unnamed(fields_unnamed) => { let mut variant_fields = Vec::new(); for (index, field) in fields_unnamed.unnamed.iter().enumerate() { let field_name = format!("field_{}", index); let field_attrs = parse_smithy_field_attributes(&field.attrs)?; // For single unnamed fields, use the variant attribute if field doesn't have one let value_type = field_attrs .value_type .or_else(|| variant_attrs.value_type.clone()); if let Some(value_type) = value_type { let field_documentation = extract_documentation(&field.attrs); let optional = value_type.trim().starts_with("Option<"); variant_fields.push(SmithyField { name: field_name, value_type, constraints: field_attrs.constraints, documentation: field_documentation, optional, flatten: false, }); } } variant_fields } }; smithy_variants.push(SmithyEnumVariant { name: variant_name, fields, constraints: variant_attrs.constraints, documentation, }); } Ok(smithy_variants) } #[derive(Default)] struct SmithyFieldAttributes { value_type: Option<String>, constraints: Vec<SmithyConstraint>, } #[derive(Default)] struct SerdeAttributes { flatten: bool, } #[derive(Default)] struct SerdeEnumAttributes { rename_all: Option<String>, } fn parse_serde_attributes(attrs: &[Attribute]) -> syn::Result<SerdeAttributes> { let mut serde_attributes = SerdeAttributes::default(); for attr in attrs { if attr.path().is_ident("serde") { if let Ok(list) = attr.meta.require_list() { if list.path.is_ident("serde") { for item in list.tokens.clone() { if let Some(ident) = item.to_string().split_whitespace().next() { if ident == "flatten" { serde_attributes.flatten = true; } } } } } } } Ok(serde_attributes) } fn parse_serde_enum_attributes(attrs: &[Attribute]) -> syn::Result<SerdeEnumAttributes> { let mut serde_enum_attributes = SerdeEnumAttributes::default(); for attr in attrs { if attr.path().is_ident("serde") { // Use more robust parsing that handles all serde attributes let parse_result = attr.parse_nested_meta(|meta| { if meta.path.is_ident("rename_all") { if let Ok(value) = meta.value() { if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() { serde_enum_attributes.rename_all = Some(lit_str.value()); } } } else if meta.path.is_ident("tag") { // Parse and ignore the tag attribute if let Ok(value) = meta.value() { let _ = value.parse::<Lit>(); } } else if meta.path.is_ident("content") { // Parse and ignore the content attribute if let Ok(value) = meta.value() { let _ = value.parse::<Lit>(); } } else if meta.path.is_ident("rename") { // Parse and ignore the rename attribute (used for enum renaming) if let Ok(value) = meta.value() { let _ = value.parse::<Lit>(); } } else if meta.path.is_ident("deny_unknown_fields") { // Handle deny_unknown_fields (no value needed) // This is a flag attribute with no value } else if meta.path.is_ident("skip_serializing") { // Handle skip_serializing } else if meta.path.is_ident("skip_deserializing") { // Handle skip_deserializing } else if meta.path.is_ident("skip_serializing_if") { // Handle skip_serializing_if if let Ok(value) = meta.value() { let _ = value.parse::<syn::Expr>(); } } else if meta.path.is_ident("default") { // Handle default attribute // Could have a value or be a flag if meta.value().is_ok() { let _ = meta.value().and_then(|v| v.parse::<syn::Expr>()); } } else if meta.path.is_ident("flatten") { // Handle flatten (flag attribute) } else if meta.path.is_ident("untagged") { // Handle untagged (flag attribute) } else if meta.path.is_ident("bound") { // Handle bound attribute if let Ok(value) = meta.value() { let _ = value.parse::<Lit>(); } } // Silently ignore any other serde attributes to prevent parsing errors Ok(()) }); // If parsing failed, provide a more helpful error message if let Err(e) = parse_result { return Err(syn::Error::new_spanned( attr, format!("Failed to parse serde attribute: {}. This may be due to multiple serde attributes on separate lines. Consider consolidating them into a single #[serde(...)] attribute.", e) )); } } } Ok(serde_enum_attributes) } fn transform_variant_name(name: &str, rename_all: Option<&str>) -> String { match rename_all { Some("snake_case") => to_snake_case(name), Some("camelCase") => to_camel_case(name), Some("kebab-case") => to_kebab_case(name), Some("PascalCase") => name.to_string(), // No change for PascalCase Some("SCREAMING_SNAKE_CASE") => to_screaming_snake_case(name), Some("lowercase") => name.to_lowercase(), Some("UPPERCASE") => name.to_uppercase(), _ => name.to_string(), // No transformation if no rename_all or unknown pattern } } fn to_snake_case(input: &str) -> String { let mut result = String::new(); let chars = input.chars(); for ch in chars { if ch.is_uppercase() && !result.is_empty() { // Add underscore before uppercase letters (except the first character) result.push('_'); } result.push(ch.to_lowercase().next().unwrap()); } result } fn to_camel_case(input: &str) -> String { let mut result = String::new(); let mut chars = input.chars(); // First character should be lowercase if let Some(ch) = chars.next() { result.push(ch.to_lowercase().next().unwrap()); } // Rest of the characters remain the same for ch in chars { result.push(ch); } result } fn to_kebab_case(input: &str) -> String { let mut result = String::new(); for ch in input.chars() { if ch.is_uppercase() && !result.is_empty() { // Add hyphen before uppercase letters (except the first character) result.push('-'); } result.push(ch.to_lowercase().next().unwrap()); } result } fn to_screaming_snake_case(input: &str) -> String { let mut result = String::new(); for ch in input.chars() { if ch.is_uppercase() && !result.is_empty() { // Add underscore before uppercase letters (except the first character) result.push('_'); } result.push(ch.to_uppercase().next().unwrap()); } result } fn parse_smithy_field_attributes(attrs: &[Attribute]) -> syn::Result<SmithyFieldAttributes> { let mut field_attributes = SmithyFieldAttributes::default(); for attr in attrs { if attr.path().is_ident("smithy") { attr.parse_nested_meta(|meta| { if meta.path.is_ident("value_type") { if let Ok(value) = meta.value() { if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() { field_attributes.value_type = Some(lit_str.value()); } } } else if meta.path.is_ident("pattern") { if let Ok(value) = meta.value() { if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() { field_attributes .constraints .push(SmithyConstraint::Pattern(lit_str.value())); } } } else if meta.path.is_ident("range") { if let Ok(value) = meta.value() { if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() { let range_str = lit_str.value(); match parse_range(&range_str) { Ok((min, max)) => { field_attributes .constraints .push(SmithyConstraint::Range(min, max)); } Err(e) => { return Err(syn::Error::new_spanned( &meta.path, format!("Invalid range: {}", e), )); } } } } } else if meta.path.is_ident("length") { if let Ok(value) = meta.value() { if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() { let length_str = lit_str.value(); match parse_length(&length_str) { Ok((min, max)) => { field_attributes .constraints .push(SmithyConstraint::Length(min, max)); } Err(e) => { return Err(syn::Error::new_spanned( &meta.path, format!("Invalid length: {}", e), )); } } } } } else if meta.path.is_ident("required") { field_attributes .constraints .push(SmithyConstraint::Required); } else if meta.path.is_ident("http_label") { field_attributes .constraints .push(SmithyConstraint::HttpLabel); } else if meta.path.is_ident("http_query") { if let Ok(value) = meta.value() { if let Ok(Lit::Str(lit_str)) = value.parse::<Lit>() { field_attributes .constraints .push(SmithyConstraint::HttpQuery(lit_str.value())); } } } Ok(()) })?; } } // Automatically add Required for http_label fields if field_attributes .constraints .iter() .any(|c| matches!(c, SmithyConstraint::HttpLabel)) && !field_attributes .constraints .iter() .any(|c| matches!(c, SmithyConstraint::Required)) { field_attributes .constraints .push(SmithyConstraint::Required); } Ok(field_attributes) } fn extract_documentation(attrs: &[Attribute]) -> Option<String> { let mut docs = Vec::new(); for attr in attrs { if attr.path().is_ident("doc") { if let Meta::NameValue(meta_name_value) = &attr.meta { if let syn::Expr::Lit(expr_lit) = &meta_name_value.value { if let Lit::Str(lit_str) = &expr_lit.lit { docs.push(lit_str.value().trim().to_string()); } } } } } if docs.is_empty() { None } else { Some(docs.join(" ")) } } fn parse_range(range_str: &str) -> Result<(Option<i64>, Option<i64>), String> { if range_str.contains("..=") { let parts: Vec<&str> = range_str.split("..=").collect(); if parts.len() != 2 { return Err( "Invalid range format: must be 'min..=max', '..=max', or 'min..='".to_string(), ); } let min = if parts[0].is_empty() { None } else { Some( parts[0] .parse() .map_err(|_| format!("Invalid range min: '{}'", parts[0]))?, ) }; let max = if parts[1].is_empty() { None } else { Some( parts[1] .parse() .map_err(|_| format!("Invalid range max: '{}'", parts[1]))?, ) }; Ok((min, max)) } else if range_str.contains("..") { let parts: Vec<&str> = range_str.split("..").collect(); if parts.len() != 2 { return Err( "Invalid range format: must be 'min..max', '..max', or 'min..'".to_string(), ); } let min = if parts[0].is_empty() { None } else { Some( parts[0] .parse() .map_err(|_| format!("Invalid range min: '{}'", parts[0]))?, ) }; let max = if parts[1].is_empty() { None } else { Some( parts[1] .parse::<i64>() .map_err(|_| format!("Invalid range max: '{}'", parts[1]))? - 1, ) }; Ok((min, max)) } else { Err("Invalid range format: must contain '..' or '..='".to_string()) } } fn parse_length(length_str: &str) -> Result<(Option<u64>, Option<u64>), String> { if length_str.contains("..=") { let parts: Vec<&str> = length_str.split("..=").collect(); if parts.len() != 2 { return Err( "Invalid length format: must be 'min..=max', '..=max', or 'min..='".to_string(), ); } let min = if parts[0].is_empty() { None } else { Some( parts[0] .parse() .map_err(|_| format!("Invalid length min: '{}'", parts[0]))?, ) }; let max = if parts[1].is_empty() { None } else { Some( parts[1] .parse() .map_err(|_| format!("Invalid length max: '{}'", parts[1]))?, ) }; Ok((min, max)) } else if length_str.contains("..") { let parts: Vec<&str> = length_str.split("..").collect(); if parts.len() != 2 { return Err( "Invalid length format: must be 'min..max', '..max', or 'min..'".to_string(), ); } let min = if parts[0].is_empty() { None } else { Some( parts[0] .parse() .map_err(|_| format!("Invalid length min: '{}'", parts[0]))?, ) }; let max = if parts[1].is_empty() { None } else { Some( parts[1] .parse::<u64>() .map_err(|_| format!("Invalid length max: '{}'", parts[1]))? - 1, ) }; Ok((min, max)) } else { Err("Invalid length format: must contain '..' or '..='".to_string()) } }
crates/smithy/src/lib.rs
smithy::src::lib
7,386
true
// File: crates/common_enums/src/connector_enums.rs // Module: common_enums::src::connector_enums use std::collections::HashSet; use utoipa::ToSchema; pub use super::enums::{PaymentMethod, PayoutType}; pub use crate::PaymentMethodType; #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] /// RoutableConnectors are the subset of Connectors that are eligible for payments routing pub enum RoutableConnectors { Authipay, Adyenplatform, #[cfg(feature = "dummy_connector")] #[serde(rename = "stripe_billing_test")] #[strum(serialize = "stripe_billing_test")] DummyBillingConnector, #[cfg(feature = "dummy_connector")] #[serde(rename = "phonypay")] #[strum(serialize = "phonypay")] DummyConnector1, #[cfg(feature = "dummy_connector")] #[serde(rename = "fauxpay")] #[strum(serialize = "fauxpay")] DummyConnector2, #[cfg(feature = "dummy_connector")] #[serde(rename = "pretendpay")] #[strum(serialize = "pretendpay")] DummyConnector3, #[cfg(feature = "dummy_connector")] #[serde(rename = "stripe_test")] #[strum(serialize = "stripe_test")] DummyConnector4, #[cfg(feature = "dummy_connector")] #[serde(rename = "adyen_test")] #[strum(serialize = "adyen_test")] DummyConnector5, #[cfg(feature = "dummy_connector")] #[serde(rename = "checkout_test")] #[strum(serialize = "checkout_test")] DummyConnector6, #[cfg(feature = "dummy_connector")] #[serde(rename = "paypal_test")] #[strum(serialize = "paypal_test")] DummyConnector7, Aci, Adyen, Affirm, Airwallex, Amazonpay, Archipel, Authorizedotnet, Bankofamerica, Barclaycard, Billwerk, Bitpay, Bambora, Blackhawknetwork, Bamboraapac, Bluesnap, #[serde(alias = "bluecode")] Calida, Boku, Braintree, Breadpay, Cashtocode, Celero, Chargebee, Custombilling, Checkbook, Checkout, Coinbase, Coingate, Cryptopay, Cybersource, Datatrans, Deutschebank, Digitalvirgo, Dlocal, Dwolla, Ebanx, Elavon, Facilitapay, Finix, Fiserv, Fiservemea, Fiuu, Flexiti, Forte, Getnet, Gigadat, Globalpay, Globepay, Gocardless, Hipay, Helcim, Iatapay, Inespay, Itaubank, Jpmorgan, Klarna, Loonio, Mifinity, Mollie, Moneris, Multisafepay, Nexinets, Nexixpay, Nmi, Nomupay, Noon, Nordea, Novalnet, Nuvei, // Opayo, added as template code for future usage Opennode, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage Paybox, Payme, Payload, Payone, Paypal, Paysafe, Paystack, Paytm, Payu, Peachpayments, Phonepe, Placetopay, Powertranz, Prophetpay, Rapyd, Razorpay, Recurly, Redsys, Riskified, Santander, Shift4, Signifyd, Silverflow, Square, Stax, Stripe, Stripebilling, Tesouro, // Taxjar, Trustpay, Trustpayments, // Thunes Tokenio, // Tsys, Tsys, // UnifiedAuthenticationService, // Vgs Volt, Wellsfargo, // Wellsfargopayout, Wise, Worldline, Worldpay, Worldpayvantiv, Worldpayxml, Xendit, Zen, Plaid, Zsl, } // A connector is an integration to fulfill payments #[derive( Clone, Copy, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::VariantNames, strum::EnumIter, strum::Display, strum::EnumString, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum Connector { Authipay, Adyenplatform, #[cfg(feature = "dummy_connector")] #[serde(rename = "stripe_billing_test")] #[strum(serialize = "stripe_billing_test")] DummyBillingConnector, #[cfg(feature = "dummy_connector")] #[serde(rename = "phonypay")] #[strum(serialize = "phonypay")] DummyConnector1, #[cfg(feature = "dummy_connector")] #[serde(rename = "fauxpay")] #[strum(serialize = "fauxpay")] DummyConnector2, #[cfg(feature = "dummy_connector")] #[serde(rename = "pretendpay")] #[strum(serialize = "pretendpay")] DummyConnector3, #[cfg(feature = "dummy_connector")] #[serde(rename = "stripe_test")] #[strum(serialize = "stripe_test")] DummyConnector4, #[cfg(feature = "dummy_connector")] #[serde(rename = "adyen_test")] #[strum(serialize = "adyen_test")] DummyConnector5, #[cfg(feature = "dummy_connector")] #[serde(rename = "checkout_test")] #[strum(serialize = "checkout_test")] DummyConnector6, #[cfg(feature = "dummy_connector")] #[serde(rename = "paypal_test")] #[strum(serialize = "paypal_test")] DummyConnector7, Aci, Adyen, Affirm, Airwallex, Amazonpay, Archipel, Authorizedotnet, Bambora, Bamboraapac, Bankofamerica, Barclaycard, Billwerk, Bitpay, Bluesnap, Blackhawknetwork, #[serde(alias = "bluecode")] Calida, Boku, Braintree, Breadpay, Cardinal, Cashtocode, Celero, Chargebee, Checkbook, Checkout, Coinbase, Coingate, Custombilling, Cryptopay, CtpMastercard, CtpVisa, Cybersource, Datatrans, Deutschebank, Digitalvirgo, Dlocal, Dwolla, Ebanx, Elavon, Facilitapay, Finix, Fiserv, Fiservemea, Fiuu, Flexiti, Forte, Getnet, Gigadat, Globalpay, Globepay, Gocardless, Gpayments, Hipay, Helcim, HyperswitchVault, // Hyperwallet, added as template code for future usage Inespay, Iatapay, Itaubank, Jpmorgan, Juspaythreedsserver, Klarna, Loonio, Mifinity, Mollie, Moneris, Multisafepay, Netcetera, Nexinets, Nexixpay, Nmi, Nomupay, Noon, Nordea, Novalnet, Nuvei, // Opayo, added as template code for future usage Opennode, Paybox, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage Payload, Payme, Payone, Paypal, Paysafe, Paystack, Paytm, Payu, Peachpayments, Phonepe, Placetopay, Powertranz, Prophetpay, Rapyd, Razorpay, Recurly, Redsys, Santander, Shift4, Silverflow, Square, Stax, Stripe, Stripebilling, Taxjar, Threedsecureio, // Tokenio, //Thunes, Tesouro, Tokenex, Tokenio, Trustpay, Trustpayments, Tsys, // UnifiedAuthenticationService, Vgs, Volt, Wellsfargo, // Wellsfargopayout, Wise, Worldline, Worldpay, Worldpayvantiv, Worldpayxml, Signifyd, Plaid, Riskified, Xendit, Zen, Zsl, } impl Connector { #[cfg(feature = "payouts")] pub fn supports_instant_payout(self, payout_method: Option<PayoutType>) -> bool { matches!( (self, payout_method), (Self::Paypal, Some(PayoutType::Wallet)) | (_, Some(PayoutType::Card)) | (Self::Adyenplatform, _) | (Self::Nomupay, _) | (Self::Loonio, _) | (Self::Worldpay, Some(PayoutType::Wallet)) ) } #[cfg(feature = "payouts")] pub fn supports_create_recipient(self, payout_method: Option<PayoutType>) -> bool { matches!((self, payout_method), (_, Some(PayoutType::Bank))) } #[cfg(feature = "payouts")] pub fn supports_payout_eligibility(self, payout_method: Option<PayoutType>) -> bool { matches!((self, payout_method), (_, Some(PayoutType::Card))) } #[cfg(feature = "payouts")] pub fn is_payout_quote_call_required(self) -> bool { matches!(self, Self::Wise | Self::Gigadat) } #[cfg(feature = "payouts")] pub fn supports_access_token_for_payout(self, payout_method: Option<PayoutType>) -> bool { matches!((self, payout_method), (Self::Paypal, _)) } #[cfg(feature = "payouts")] pub fn supports_vendor_disburse_account_create_for_payout(self) -> bool { matches!(self, Self::Stripe | Self::Nomupay) } pub fn supports_access_token(self, payment_method: PaymentMethod) -> bool { matches!( (self, payment_method), (Self::Airwallex, _) | (Self::Deutschebank, _) | (Self::Globalpay, _) | (Self::Jpmorgan, _) | (Self::Moneris, _) | (Self::Nordea, _) | (Self::Paypal, _) | (Self::Payu, _) | ( Self::Trustpay, PaymentMethod::BankRedirect | PaymentMethod::BankTransfer ) | (Self::Tesouro, _) | (Self::Iatapay, _) | (Self::Volt, _) | (Self::Itaubank, _) | (Self::Facilitapay, _) | (Self::Dwolla, _) ) } pub fn requires_order_creation_before_payment(self, payment_method: PaymentMethod) -> bool { matches!((self, payment_method), (Self::Razorpay, PaymentMethod::Upi)) } pub fn supports_file_storage_module(self) -> bool { matches!(self, Self::Stripe | Self::Checkout | Self::Worldpayvantiv) } pub fn requires_defend_dispute(self) -> bool { matches!(self, Self::Checkout) } pub fn is_separate_authentication_supported(self) -> bool { match self { #[cfg(feature = "dummy_connector")] Self::DummyBillingConnector => false, #[cfg(feature = "dummy_connector")] Self::DummyConnector1 | Self::DummyConnector2 | Self::DummyConnector3 | Self::DummyConnector4 | Self::DummyConnector5 | Self::DummyConnector6 | Self::DummyConnector7 => false, Self::Aci // Add Separate authentication support for connectors | Self::Authipay | Self::Adyen | Self::Affirm | Self::Adyenplatform | Self::Airwallex | Self::Amazonpay | Self::Authorizedotnet | Self::Bambora | Self::Bamboraapac | Self::Bankofamerica | Self::Barclaycard | Self::Billwerk | Self::Bitpay | Self::Bluesnap | Self::Blackhawknetwork | Self::Calida | Self::Boku | Self::Braintree | Self::Breadpay | Self::Cashtocode | Self::Celero | Self::Chargebee | Self::Checkbook | Self::Coinbase | Self::Coingate | Self::Cryptopay | Self::Custombilling | Self::Deutschebank | Self::Digitalvirgo | Self::Dlocal | Self::Dwolla | Self::Ebanx | Self::Elavon | Self::Facilitapay | Self::Finix | Self::Fiserv | Self::Fiservemea | Self::Fiuu | Self::Flexiti | Self::Forte | Self::Getnet | Self::Gigadat | Self::Globalpay | Self::Globepay | Self::Gocardless | Self::Gpayments | Self::Hipay | Self::Helcim | Self::HyperswitchVault | Self::Iatapay | Self::Inespay | Self::Itaubank | Self::Jpmorgan | Self::Juspaythreedsserver | Self::Klarna | Self::Loonio | Self::Mifinity | Self::Mollie | Self::Moneris | Self::Multisafepay | Self::Nexinets | Self::Nexixpay | Self::Nomupay | Self::Nordea | Self::Novalnet | Self::Opennode | Self::Paybox | Self::Payload | Self::Payme | Self::Payone | Self::Paypal | Self::Paysafe | Self::Paystack | Self::Payu | Self::Peachpayments | Self::Placetopay | Self::Powertranz | Self::Prophetpay | Self::Rapyd | Self::Recurly | Self::Redsys | Self::Santander | Self::Shift4 | Self::Silverflow | Self::Square | Self::Stax | Self::Stripebilling | Self::Taxjar | Self::Tesouro // | Self::Thunes | Self::Trustpay | Self::Trustpayments // | Self::Tokenio | Self::Tsys // | Self::UnifiedAuthenticationService | Self::Vgs | Self::Volt | Self::Wellsfargo // | Self::Wellsfargopayout | Self::Wise | Self::Worldline | Self::Worldpay | Self::Worldpayvantiv | Self::Worldpayxml | Self::Xendit | Self::Zen | Self::Zsl | Self::Signifyd | Self::Plaid | Self::Razorpay | Self::Riskified | Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::Cardinal | Self::CtpVisa | Self::Noon | Self::Tokenex | Self::Tokenio | Self::Stripe | Self::Datatrans | Self::Paytm | Self::Phonepe => false, Self::Checkout | Self::Nmi |Self::Cybersource | Self::Archipel | Self::Nuvei => true, } } pub fn is_pre_processing_required_before_authorize(self) -> bool { matches!(self, Self::Airwallex) } pub fn get_payment_methods_supporting_extended_authorization(self) -> HashSet<PaymentMethod> { HashSet::from([PaymentMethod::Card]) } pub fn get_payment_method_types_supporting_extended_authorization( self, ) -> HashSet<PaymentMethodType> { HashSet::from([PaymentMethodType::Credit, PaymentMethodType::Debit]) } pub fn is_overcapture_supported_by_connector(self) -> bool { matches!(self, Self::Stripe | Self::Adyen) } pub fn should_acknowledge_webhook_for_resource_not_found_errors(self) -> bool { matches!(self, Self::Adyenplatform | Self::Adyen) } /// Validates if dummy connector can be created /// Dummy connectors can be created only if dummy_connector feature is enabled in the configs #[cfg(feature = "dummy_connector")] pub fn validate_dummy_connector_create(self, is_dummy_connector_enabled: bool) -> bool { matches!( self, Self::DummyConnector1 | Self::DummyConnector2 | Self::DummyConnector3 | Self::DummyConnector4 | Self::DummyConnector5 | Self::DummyConnector6 | Self::DummyConnector7 ) && !is_dummy_connector_enabled } } /// Convert the RoutableConnectors to Connector impl From<RoutableConnectors> for Connector { fn from(routable_connector: RoutableConnectors) -> Self { match routable_connector { RoutableConnectors::Authipay => Self::Authipay, RoutableConnectors::Adyenplatform => Self::Adyenplatform, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyBillingConnector => Self::DummyBillingConnector, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector1 => Self::DummyConnector1, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector2 => Self::DummyConnector2, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector3 => Self::DummyConnector3, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector4 => Self::DummyConnector4, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector5 => Self::DummyConnector5, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector6 => Self::DummyConnector6, #[cfg(feature = "dummy_connector")] RoutableConnectors::DummyConnector7 => Self::DummyConnector7, RoutableConnectors::Aci => Self::Aci, RoutableConnectors::Adyen => Self::Adyen, RoutableConnectors::Affirm => Self::Affirm, RoutableConnectors::Airwallex => Self::Airwallex, RoutableConnectors::Amazonpay => Self::Amazonpay, RoutableConnectors::Archipel => Self::Archipel, RoutableConnectors::Authorizedotnet => Self::Authorizedotnet, RoutableConnectors::Bankofamerica => Self::Bankofamerica, RoutableConnectors::Barclaycard => Self::Barclaycard, RoutableConnectors::Billwerk => Self::Billwerk, RoutableConnectors::Bitpay => Self::Bitpay, RoutableConnectors::Bambora => Self::Bambora, RoutableConnectors::Bamboraapac => Self::Bamboraapac, RoutableConnectors::Bluesnap => Self::Bluesnap, RoutableConnectors::Blackhawknetwork => Self::Blackhawknetwork, RoutableConnectors::Calida => Self::Calida, RoutableConnectors::Boku => Self::Boku, RoutableConnectors::Braintree => Self::Braintree, RoutableConnectors::Breadpay => Self::Breadpay, RoutableConnectors::Cashtocode => Self::Cashtocode, RoutableConnectors::Celero => Self::Celero, RoutableConnectors::Chargebee => Self::Chargebee, RoutableConnectors::Custombilling => Self::Custombilling, RoutableConnectors::Checkbook => Self::Checkbook, RoutableConnectors::Checkout => Self::Checkout, RoutableConnectors::Coinbase => Self::Coinbase, RoutableConnectors::Cryptopay => Self::Cryptopay, RoutableConnectors::Cybersource => Self::Cybersource, RoutableConnectors::Datatrans => Self::Datatrans, RoutableConnectors::Deutschebank => Self::Deutschebank, RoutableConnectors::Digitalvirgo => Self::Digitalvirgo, RoutableConnectors::Dlocal => Self::Dlocal, RoutableConnectors::Dwolla => Self::Dwolla, RoutableConnectors::Ebanx => Self::Ebanx, RoutableConnectors::Elavon => Self::Elavon, RoutableConnectors::Facilitapay => Self::Facilitapay, RoutableConnectors::Finix => Self::Finix, RoutableConnectors::Fiserv => Self::Fiserv, RoutableConnectors::Fiservemea => Self::Fiservemea, RoutableConnectors::Fiuu => Self::Fiuu, RoutableConnectors::Flexiti => Self::Flexiti, RoutableConnectors::Forte => Self::Forte, RoutableConnectors::Getnet => Self::Getnet, RoutableConnectors::Gigadat => Self::Gigadat, RoutableConnectors::Globalpay => Self::Globalpay, RoutableConnectors::Globepay => Self::Globepay, RoutableConnectors::Gocardless => Self::Gocardless, RoutableConnectors::Helcim => Self::Helcim, RoutableConnectors::Iatapay => Self::Iatapay, RoutableConnectors::Itaubank => Self::Itaubank, RoutableConnectors::Jpmorgan => Self::Jpmorgan, RoutableConnectors::Klarna => Self::Klarna, RoutableConnectors::Loonio => Self::Loonio, RoutableConnectors::Mifinity => Self::Mifinity, RoutableConnectors::Mollie => Self::Mollie, RoutableConnectors::Moneris => Self::Moneris, RoutableConnectors::Multisafepay => Self::Multisafepay, RoutableConnectors::Nexinets => Self::Nexinets, RoutableConnectors::Nexixpay => Self::Nexixpay, RoutableConnectors::Nmi => Self::Nmi, RoutableConnectors::Nomupay => Self::Nomupay, RoutableConnectors::Noon => Self::Noon, RoutableConnectors::Nordea => Self::Nordea, RoutableConnectors::Novalnet => Self::Novalnet, RoutableConnectors::Nuvei => Self::Nuvei, RoutableConnectors::Opennode => Self::Opennode, RoutableConnectors::Paybox => Self::Paybox, RoutableConnectors::Payload => Self::Payload, RoutableConnectors::Payme => Self::Payme, RoutableConnectors::Payone => Self::Payone, RoutableConnectors::Paypal => Self::Paypal, RoutableConnectors::Paysafe => Self::Paysafe, RoutableConnectors::Paystack => Self::Paystack, RoutableConnectors::Payu => Self::Payu, RoutableConnectors::Peachpayments => Self::Peachpayments, RoutableConnectors::Placetopay => Self::Placetopay, RoutableConnectors::Powertranz => Self::Powertranz, RoutableConnectors::Prophetpay => Self::Prophetpay, RoutableConnectors::Rapyd => Self::Rapyd, RoutableConnectors::Razorpay => Self::Razorpay, RoutableConnectors::Recurly => Self::Recurly, RoutableConnectors::Redsys => Self::Redsys, RoutableConnectors::Riskified => Self::Riskified, RoutableConnectors::Santander => Self::Santander, RoutableConnectors::Shift4 => Self::Shift4, RoutableConnectors::Signifyd => Self::Signifyd, RoutableConnectors::Silverflow => Self::Silverflow, RoutableConnectors::Square => Self::Square, RoutableConnectors::Stax => Self::Stax, RoutableConnectors::Stripe => Self::Stripe, RoutableConnectors::Stripebilling => Self::Stripebilling, RoutableConnectors::Tesouro => Self::Tesouro, RoutableConnectors::Tokenio => Self::Tokenio, RoutableConnectors::Trustpay => Self::Trustpay, RoutableConnectors::Trustpayments => Self::Trustpayments, // RoutableConnectors::Tokenio => Self::Tokenio, RoutableConnectors::Tsys => Self::Tsys, RoutableConnectors::Volt => Self::Volt, RoutableConnectors::Wellsfargo => Self::Wellsfargo, RoutableConnectors::Wise => Self::Wise, RoutableConnectors::Worldline => Self::Worldline, RoutableConnectors::Worldpay => Self::Worldpay, RoutableConnectors::Worldpayvantiv => Self::Worldpayvantiv, RoutableConnectors::Worldpayxml => Self::Worldpayxml, RoutableConnectors::Zen => Self::Zen, RoutableConnectors::Plaid => Self::Plaid, RoutableConnectors::Zsl => Self::Zsl, RoutableConnectors::Xendit => Self::Xendit, RoutableConnectors::Inespay => Self::Inespay, RoutableConnectors::Coingate => Self::Coingate, RoutableConnectors::Hipay => Self::Hipay, RoutableConnectors::Paytm => Self::Paytm, RoutableConnectors::Phonepe => Self::Phonepe, } } } impl TryFrom<Connector> for RoutableConnectors { type Error = &'static str; fn try_from(connector: Connector) -> Result<Self, Self::Error> { match connector { Connector::Authipay => Ok(Self::Authipay), Connector::Adyenplatform => Ok(Self::Adyenplatform), #[cfg(feature = "dummy_connector")] Connector::DummyBillingConnector => Ok(Self::DummyBillingConnector), #[cfg(feature = "dummy_connector")] Connector::DummyConnector1 => Ok(Self::DummyConnector1), #[cfg(feature = "dummy_connector")] Connector::DummyConnector2 => Ok(Self::DummyConnector2), #[cfg(feature = "dummy_connector")] Connector::DummyConnector3 => Ok(Self::DummyConnector3), #[cfg(feature = "dummy_connector")] Connector::DummyConnector4 => Ok(Self::DummyConnector4), #[cfg(feature = "dummy_connector")] Connector::DummyConnector5 => Ok(Self::DummyConnector5), #[cfg(feature = "dummy_connector")] Connector::DummyConnector6 => Ok(Self::DummyConnector6), #[cfg(feature = "dummy_connector")] Connector::DummyConnector7 => Ok(Self::DummyConnector7), Connector::Aci => Ok(Self::Aci), Connector::Adyen => Ok(Self::Adyen), Connector::Affirm => Ok(Self::Affirm), Connector::Airwallex => Ok(Self::Airwallex), Connector::Amazonpay => Ok(Self::Amazonpay), Connector::Archipel => Ok(Self::Archipel), Connector::Authorizedotnet => Ok(Self::Authorizedotnet), Connector::Bankofamerica => Ok(Self::Bankofamerica), Connector::Barclaycard => Ok(Self::Barclaycard), Connector::Billwerk => Ok(Self::Billwerk), Connector::Bitpay => Ok(Self::Bitpay), Connector::Bambora => Ok(Self::Bambora), Connector::Bamboraapac => Ok(Self::Bamboraapac), Connector::Bluesnap => Ok(Self::Bluesnap), Connector::Blackhawknetwork => Ok(Self::Blackhawknetwork), Connector::Calida => Ok(Self::Calida), Connector::Boku => Ok(Self::Boku), Connector::Braintree => Ok(Self::Braintree), Connector::Breadpay => Ok(Self::Breadpay), Connector::Cashtocode => Ok(Self::Cashtocode), Connector::Celero => Ok(Self::Celero), Connector::Chargebee => Ok(Self::Chargebee), Connector::Checkbook => Ok(Self::Checkbook), Connector::Checkout => Ok(Self::Checkout), Connector::Coinbase => Ok(Self::Coinbase), Connector::Coingate => Ok(Self::Coingate), Connector::Cryptopay => Ok(Self::Cryptopay), Connector::Custombilling => Ok(Self::Custombilling), Connector::Cybersource => Ok(Self::Cybersource), Connector::Datatrans => Ok(Self::Datatrans), Connector::Deutschebank => Ok(Self::Deutschebank), Connector::Digitalvirgo => Ok(Self::Digitalvirgo), Connector::Dlocal => Ok(Self::Dlocal), Connector::Dwolla => Ok(Self::Dwolla), Connector::Ebanx => Ok(Self::Ebanx), Connector::Elavon => Ok(Self::Elavon), Connector::Facilitapay => Ok(Self::Facilitapay), Connector::Finix => Ok(Self::Finix), Connector::Fiserv => Ok(Self::Fiserv), Connector::Fiservemea => Ok(Self::Fiservemea), Connector::Fiuu => Ok(Self::Fiuu), Connector::Flexiti => Ok(Self::Flexiti), Connector::Forte => Ok(Self::Forte), Connector::Globalpay => Ok(Self::Globalpay), Connector::Globepay => Ok(Self::Globepay), Connector::Gocardless => Ok(Self::Gocardless), Connector::Helcim => Ok(Self::Helcim), Connector::Iatapay => Ok(Self::Iatapay), Connector::Itaubank => Ok(Self::Itaubank), Connector::Jpmorgan => Ok(Self::Jpmorgan), Connector::Klarna => Ok(Self::Klarna), Connector::Loonio => Ok(Self::Loonio), Connector::Mifinity => Ok(Self::Mifinity), Connector::Mollie => Ok(Self::Mollie), Connector::Moneris => Ok(Self::Moneris), Connector::Multisafepay => Ok(Self::Multisafepay), Connector::Nexinets => Ok(Self::Nexinets), Connector::Nexixpay => Ok(Self::Nexixpay), Connector::Nmi => Ok(Self::Nmi), Connector::Nomupay => Ok(Self::Nomupay), Connector::Noon => Ok(Self::Noon), Connector::Nordea => Ok(Self::Nordea), Connector::Novalnet => Ok(Self::Novalnet), Connector::Nuvei => Ok(Self::Nuvei), Connector::Opennode => Ok(Self::Opennode), Connector::Paybox => Ok(Self::Paybox), Connector::Payload => Ok(Self::Payload), Connector::Payme => Ok(Self::Payme), Connector::Payone => Ok(Self::Payone), Connector::Paypal => Ok(Self::Paypal), Connector::Paysafe => Ok(Self::Paysafe), Connector::Paystack => Ok(Self::Paystack), Connector::Payu => Ok(Self::Payu), Connector::Peachpayments => Ok(Self::Peachpayments), Connector::Placetopay => Ok(Self::Placetopay), Connector::Powertranz => Ok(Self::Powertranz), Connector::Prophetpay => Ok(Self::Prophetpay), Connector::Rapyd => Ok(Self::Rapyd), Connector::Razorpay => Ok(Self::Razorpay), Connector::Riskified => Ok(Self::Riskified), Connector::Santander => Ok(Self::Santander), Connector::Shift4 => Ok(Self::Shift4), Connector::Signifyd => Ok(Self::Signifyd), Connector::Silverflow => Ok(Self::Silverflow), Connector::Square => Ok(Self::Square), Connector::Stax => Ok(Self::Stax), Connector::Stripe => Ok(Self::Stripe), Connector::Stripebilling => Ok(Self::Stripebilling), Connector::Tokenio => Ok(Self::Tokenio), Connector::Tesouro => Ok(Self::Tesouro), Connector::Trustpay => Ok(Self::Trustpay), Connector::Trustpayments => Ok(Self::Trustpayments), Connector::Tsys => Ok(Self::Tsys), Connector::Volt => Ok(Self::Volt), Connector::Wellsfargo => Ok(Self::Wellsfargo), Connector::Wise => Ok(Self::Wise), Connector::Worldline => Ok(Self::Worldline), Connector::Worldpay => Ok(Self::Worldpay), Connector::Worldpayvantiv => Ok(Self::Worldpayvantiv), Connector::Worldpayxml => Ok(Self::Worldpayxml), Connector::Xendit => Ok(Self::Xendit), Connector::Zen => Ok(Self::Zen), Connector::Plaid => Ok(Self::Plaid), Connector::Zsl => Ok(Self::Zsl), Connector::Recurly => Ok(Self::Recurly), Connector::Getnet => Ok(Self::Getnet), Connector::Gigadat => Ok(Self::Gigadat), Connector::Hipay => Ok(Self::Hipay), Connector::Inespay => Ok(Self::Inespay), Connector::Redsys => Ok(Self::Redsys), Connector::Paytm => Ok(Self::Paytm), Connector::Phonepe => Ok(Self::Phonepe), Connector::CtpMastercard | Connector::Gpayments | Connector::HyperswitchVault | Connector::Juspaythreedsserver | Connector::Netcetera | Connector::Taxjar | Connector::Threedsecureio | Connector::Vgs | Connector::CtpVisa | Connector::Cardinal | Connector::Tokenex => Err("Invalid conversion. Not a routable connector"), } } } // Enum representing different status an invoice can have. #[derive( Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum InvoiceStatus { InvoiceCreated, PaymentPending, PaymentPendingTimeout, PaymentSucceeded, PaymentFailed, PaymentCanceled, InvoicePaid, ManualReview, Voided, }
crates/common_enums/src/connector_enums.rs
common_enums::src::connector_enums
8,140
true
// File: crates/common_enums/src/transformers.rs // Module: common_enums::src::transformers use std::fmt::{Display, Formatter}; use serde::{Deserialize, Serialize}; #[cfg(feature = "payouts")] use crate::enums::PayoutStatus; use crate::enums::{ AttemptStatus, Country, CountryAlpha2, CountryAlpha3, DisputeStatus, EventType, IntentStatus, MandateStatus, PaymentMethod, PaymentMethodType, RefundStatus, }; impl Display for NumericCountryCodeParseError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "Invalid Country Code") } } impl CountryAlpha2 { pub const fn from_alpha2_to_alpha3(code: Self) -> CountryAlpha3 { match code { Self::AF => CountryAlpha3::AFG, Self::AX => CountryAlpha3::ALA, Self::AL => CountryAlpha3::ALB, Self::DZ => CountryAlpha3::DZA, Self::AS => CountryAlpha3::ASM, Self::AD => CountryAlpha3::AND, Self::AO => CountryAlpha3::AGO, Self::AI => CountryAlpha3::AIA, Self::AQ => CountryAlpha3::ATA, Self::AG => CountryAlpha3::ATG, Self::AR => CountryAlpha3::ARG, Self::AM => CountryAlpha3::ARM, Self::AW => CountryAlpha3::ABW, Self::AU => CountryAlpha3::AUS, Self::AT => CountryAlpha3::AUT, Self::AZ => CountryAlpha3::AZE, Self::BS => CountryAlpha3::BHS, Self::BH => CountryAlpha3::BHR, Self::BD => CountryAlpha3::BGD, Self::BB => CountryAlpha3::BRB, Self::BY => CountryAlpha3::BLR, Self::BE => CountryAlpha3::BEL, Self::BZ => CountryAlpha3::BLZ, Self::BJ => CountryAlpha3::BEN, Self::BM => CountryAlpha3::BMU, Self::BT => CountryAlpha3::BTN, Self::BO => CountryAlpha3::BOL, Self::BQ => CountryAlpha3::BES, Self::BA => CountryAlpha3::BIH, Self::BW => CountryAlpha3::BWA, Self::BV => CountryAlpha3::BVT, Self::BR => CountryAlpha3::BRA, Self::IO => CountryAlpha3::IOT, Self::BN => CountryAlpha3::BRN, Self::BG => CountryAlpha3::BGR, Self::BF => CountryAlpha3::BFA, Self::BI => CountryAlpha3::BDI, Self::CV => CountryAlpha3::CPV, Self::KH => CountryAlpha3::KHM, Self::CM => CountryAlpha3::CMR, Self::CA => CountryAlpha3::CAN, Self::KY => CountryAlpha3::CYM, Self::CF => CountryAlpha3::CAF, Self::TD => CountryAlpha3::TCD, Self::CL => CountryAlpha3::CHL, Self::CN => CountryAlpha3::CHN, Self::CX => CountryAlpha3::CXR, Self::CC => CountryAlpha3::CCK, Self::CO => CountryAlpha3::COL, Self::KM => CountryAlpha3::COM, Self::CG => CountryAlpha3::COG, Self::CD => CountryAlpha3::COD, Self::CK => CountryAlpha3::COK, Self::CR => CountryAlpha3::CRI, Self::CI => CountryAlpha3::CIV, Self::HR => CountryAlpha3::HRV, Self::CU => CountryAlpha3::CUB, Self::CW => CountryAlpha3::CUW, Self::CY => CountryAlpha3::CYP, Self::CZ => CountryAlpha3::CZE, Self::DK => CountryAlpha3::DNK, Self::DJ => CountryAlpha3::DJI, Self::DM => CountryAlpha3::DMA, Self::DO => CountryAlpha3::DOM, Self::EC => CountryAlpha3::ECU, Self::EG => CountryAlpha3::EGY, Self::SV => CountryAlpha3::SLV, Self::GQ => CountryAlpha3::GNQ, Self::ER => CountryAlpha3::ERI, Self::EE => CountryAlpha3::EST, Self::ET => CountryAlpha3::ETH, Self::FK => CountryAlpha3::FLK, Self::FO => CountryAlpha3::FRO, Self::FJ => CountryAlpha3::FJI, Self::FI => CountryAlpha3::FIN, Self::FR => CountryAlpha3::FRA, Self::GF => CountryAlpha3::GUF, Self::PF => CountryAlpha3::PYF, Self::TF => CountryAlpha3::ATF, Self::GA => CountryAlpha3::GAB, Self::GM => CountryAlpha3::GMB, Self::GE => CountryAlpha3::GEO, Self::DE => CountryAlpha3::DEU, Self::GH => CountryAlpha3::GHA, Self::GI => CountryAlpha3::GIB, Self::GR => CountryAlpha3::GRC, Self::GL => CountryAlpha3::GRL, Self::GD => CountryAlpha3::GRD, Self::GP => CountryAlpha3::GLP, Self::GU => CountryAlpha3::GUM, Self::GT => CountryAlpha3::GTM, Self::GG => CountryAlpha3::GGY, Self::GN => CountryAlpha3::GIN, Self::GW => CountryAlpha3::GNB, Self::GY => CountryAlpha3::GUY, Self::HT => CountryAlpha3::HTI, Self::HM => CountryAlpha3::HMD, Self::VA => CountryAlpha3::VAT, Self::HN => CountryAlpha3::HND, Self::HK => CountryAlpha3::HKG, Self::HU => CountryAlpha3::HUN, Self::IS => CountryAlpha3::ISL, Self::IN => CountryAlpha3::IND, Self::ID => CountryAlpha3::IDN, Self::IR => CountryAlpha3::IRN, Self::IQ => CountryAlpha3::IRQ, Self::IE => CountryAlpha3::IRL, Self::IM => CountryAlpha3::IMN, Self::IL => CountryAlpha3::ISR, Self::IT => CountryAlpha3::ITA, Self::JM => CountryAlpha3::JAM, Self::JP => CountryAlpha3::JPN, Self::JE => CountryAlpha3::JEY, Self::JO => CountryAlpha3::JOR, Self::KZ => CountryAlpha3::KAZ, Self::KE => CountryAlpha3::KEN, Self::KI => CountryAlpha3::KIR, Self::KP => CountryAlpha3::PRK, Self::KR => CountryAlpha3::KOR, Self::KW => CountryAlpha3::KWT, Self::KG => CountryAlpha3::KGZ, Self::LA => CountryAlpha3::LAO, Self::LV => CountryAlpha3::LVA, Self::LB => CountryAlpha3::LBN, Self::LS => CountryAlpha3::LSO, Self::LR => CountryAlpha3::LBR, Self::LY => CountryAlpha3::LBY, Self::LI => CountryAlpha3::LIE, Self::LT => CountryAlpha3::LTU, Self::LU => CountryAlpha3::LUX, Self::MO => CountryAlpha3::MAC, Self::MK => CountryAlpha3::MKD, Self::MG => CountryAlpha3::MDG, Self::MW => CountryAlpha3::MWI, Self::MY => CountryAlpha3::MYS, Self::MV => CountryAlpha3::MDV, Self::ML => CountryAlpha3::MLI, Self::MT => CountryAlpha3::MLT, Self::MH => CountryAlpha3::MHL, Self::MQ => CountryAlpha3::MTQ, Self::MR => CountryAlpha3::MRT, Self::MU => CountryAlpha3::MUS, Self::YT => CountryAlpha3::MYT, Self::MX => CountryAlpha3::MEX, Self::FM => CountryAlpha3::FSM, Self::MD => CountryAlpha3::MDA, Self::MC => CountryAlpha3::MCO, Self::MN => CountryAlpha3::MNG, Self::ME => CountryAlpha3::MNE, Self::MS => CountryAlpha3::MSR, Self::MA => CountryAlpha3::MAR, Self::MZ => CountryAlpha3::MOZ, Self::MM => CountryAlpha3::MMR, Self::NA => CountryAlpha3::NAM, Self::NR => CountryAlpha3::NRU, Self::NP => CountryAlpha3::NPL, Self::NL => CountryAlpha3::NLD, Self::NC => CountryAlpha3::NCL, Self::NZ => CountryAlpha3::NZL, Self::NI => CountryAlpha3::NIC, Self::NE => CountryAlpha3::NER, Self::NG => CountryAlpha3::NGA, Self::NU => CountryAlpha3::NIU, Self::NF => CountryAlpha3::NFK, Self::MP => CountryAlpha3::MNP, Self::NO => CountryAlpha3::NOR, Self::OM => CountryAlpha3::OMN, Self::PK => CountryAlpha3::PAK, Self::PW => CountryAlpha3::PLW, Self::PS => CountryAlpha3::PSE, Self::PA => CountryAlpha3::PAN, Self::PG => CountryAlpha3::PNG, Self::PY => CountryAlpha3::PRY, Self::PE => CountryAlpha3::PER, Self::PH => CountryAlpha3::PHL, Self::PN => CountryAlpha3::PCN, Self::PL => CountryAlpha3::POL, Self::PT => CountryAlpha3::PRT, Self::PR => CountryAlpha3::PRI, Self::QA => CountryAlpha3::QAT, Self::RE => CountryAlpha3::REU, Self::RO => CountryAlpha3::ROU, Self::RU => CountryAlpha3::RUS, Self::RW => CountryAlpha3::RWA, Self::BL => CountryAlpha3::BLM, Self::SH => CountryAlpha3::SHN, Self::KN => CountryAlpha3::KNA, Self::LC => CountryAlpha3::LCA, Self::MF => CountryAlpha3::MAF, Self::PM => CountryAlpha3::SPM, Self::VC => CountryAlpha3::VCT, Self::WS => CountryAlpha3::WSM, Self::SM => CountryAlpha3::SMR, Self::ST => CountryAlpha3::STP, Self::SA => CountryAlpha3::SAU, Self::SN => CountryAlpha3::SEN, Self::RS => CountryAlpha3::SRB, Self::SC => CountryAlpha3::SYC, Self::SL => CountryAlpha3::SLE, Self::SG => CountryAlpha3::SGP, Self::SX => CountryAlpha3::SXM, Self::SK => CountryAlpha3::SVK, Self::SI => CountryAlpha3::SVN, Self::SB => CountryAlpha3::SLB, Self::SO => CountryAlpha3::SOM, Self::ZA => CountryAlpha3::ZAF, Self::GS => CountryAlpha3::SGS, Self::SS => CountryAlpha3::SSD, Self::ES => CountryAlpha3::ESP, Self::LK => CountryAlpha3::LKA, Self::SD => CountryAlpha3::SDN, Self::SR => CountryAlpha3::SUR, Self::SJ => CountryAlpha3::SJM, Self::SZ => CountryAlpha3::SWZ, Self::SE => CountryAlpha3::SWE, Self::CH => CountryAlpha3::CHE, Self::SY => CountryAlpha3::SYR, Self::TW => CountryAlpha3::TWN, Self::TJ => CountryAlpha3::TJK, Self::TZ => CountryAlpha3::TZA, Self::TH => CountryAlpha3::THA, Self::TL => CountryAlpha3::TLS, Self::TG => CountryAlpha3::TGO, Self::TK => CountryAlpha3::TKL, Self::TO => CountryAlpha3::TON, Self::TT => CountryAlpha3::TTO, Self::TN => CountryAlpha3::TUN, Self::TR => CountryAlpha3::TUR, Self::TM => CountryAlpha3::TKM, Self::TC => CountryAlpha3::TCA, Self::TV => CountryAlpha3::TUV, Self::UG => CountryAlpha3::UGA, Self::UA => CountryAlpha3::UKR, Self::AE => CountryAlpha3::ARE, Self::GB => CountryAlpha3::GBR, Self::US => CountryAlpha3::USA, Self::UM => CountryAlpha3::UMI, Self::UY => CountryAlpha3::URY, Self::UZ => CountryAlpha3::UZB, Self::VU => CountryAlpha3::VUT, Self::VE => CountryAlpha3::VEN, Self::VN => CountryAlpha3::VNM, Self::VG => CountryAlpha3::VGB, Self::VI => CountryAlpha3::VIR, Self::WF => CountryAlpha3::WLF, Self::EH => CountryAlpha3::ESH, Self::YE => CountryAlpha3::YEM, Self::ZM => CountryAlpha3::ZMB, Self::ZW => CountryAlpha3::ZWE, } } } impl Country { pub const fn from_alpha2(code: CountryAlpha2) -> Self { match code { CountryAlpha2::AF => Self::Afghanistan, CountryAlpha2::AX => Self::AlandIslands, CountryAlpha2::AL => Self::Albania, CountryAlpha2::DZ => Self::Algeria, CountryAlpha2::AS => Self::AmericanSamoa, CountryAlpha2::AD => Self::Andorra, CountryAlpha2::AO => Self::Angola, CountryAlpha2::AI => Self::Anguilla, CountryAlpha2::AQ => Self::Antarctica, CountryAlpha2::AG => Self::AntiguaAndBarbuda, CountryAlpha2::AR => Self::Argentina, CountryAlpha2::AM => Self::Armenia, CountryAlpha2::AW => Self::Aruba, CountryAlpha2::AU => Self::Australia, CountryAlpha2::AT => Self::Austria, CountryAlpha2::AZ => Self::Azerbaijan, CountryAlpha2::BS => Self::Bahamas, CountryAlpha2::BH => Self::Bahrain, CountryAlpha2::BD => Self::Bangladesh, CountryAlpha2::BB => Self::Barbados, CountryAlpha2::BY => Self::Belarus, CountryAlpha2::BE => Self::Belgium, CountryAlpha2::BZ => Self::Belize, CountryAlpha2::BJ => Self::Benin, CountryAlpha2::BM => Self::Bermuda, CountryAlpha2::BT => Self::Bhutan, CountryAlpha2::BO => Self::BoliviaPlurinationalState, CountryAlpha2::BQ => Self::BonaireSintEustatiusAndSaba, CountryAlpha2::BA => Self::BosniaAndHerzegovina, CountryAlpha2::BW => Self::Botswana, CountryAlpha2::BV => Self::BouvetIsland, CountryAlpha2::BR => Self::Brazil, CountryAlpha2::IO => Self::BritishIndianOceanTerritory, CountryAlpha2::BN => Self::BruneiDarussalam, CountryAlpha2::BG => Self::Bulgaria, CountryAlpha2::BF => Self::BurkinaFaso, CountryAlpha2::BI => Self::Burundi, CountryAlpha2::CV => Self::CaboVerde, CountryAlpha2::KH => Self::Cambodia, CountryAlpha2::CM => Self::Cameroon, CountryAlpha2::CA => Self::Canada, CountryAlpha2::KY => Self::CaymanIslands, CountryAlpha2::CF => Self::CentralAfricanRepublic, CountryAlpha2::TD => Self::Chad, CountryAlpha2::CL => Self::Chile, CountryAlpha2::CN => Self::China, CountryAlpha2::CX => Self::ChristmasIsland, CountryAlpha2::CC => Self::CocosKeelingIslands, CountryAlpha2::CO => Self::Colombia, CountryAlpha2::KM => Self::Comoros, CountryAlpha2::CG => Self::Congo, CountryAlpha2::CD => Self::CongoDemocraticRepublic, CountryAlpha2::CK => Self::CookIslands, CountryAlpha2::CR => Self::CostaRica, CountryAlpha2::CI => Self::CotedIvoire, CountryAlpha2::HR => Self::Croatia, CountryAlpha2::CU => Self::Cuba, CountryAlpha2::CW => Self::Curacao, CountryAlpha2::CY => Self::Cyprus, CountryAlpha2::CZ => Self::Czechia, CountryAlpha2::DK => Self::Denmark, CountryAlpha2::DJ => Self::Djibouti, CountryAlpha2::DM => Self::Dominica, CountryAlpha2::DO => Self::DominicanRepublic, CountryAlpha2::EC => Self::Ecuador, CountryAlpha2::EG => Self::Egypt, CountryAlpha2::SV => Self::ElSalvador, CountryAlpha2::GQ => Self::EquatorialGuinea, CountryAlpha2::ER => Self::Eritrea, CountryAlpha2::EE => Self::Estonia, CountryAlpha2::ET => Self::Ethiopia, CountryAlpha2::FK => Self::FalklandIslandsMalvinas, CountryAlpha2::FO => Self::FaroeIslands, CountryAlpha2::FJ => Self::Fiji, CountryAlpha2::FI => Self::Finland, CountryAlpha2::FR => Self::France, CountryAlpha2::GF => Self::FrenchGuiana, CountryAlpha2::PF => Self::FrenchPolynesia, CountryAlpha2::TF => Self::FrenchSouthernTerritories, CountryAlpha2::GA => Self::Gabon, CountryAlpha2::GM => Self::Gambia, CountryAlpha2::GE => Self::Georgia, CountryAlpha2::DE => Self::Germany, CountryAlpha2::GH => Self::Ghana, CountryAlpha2::GI => Self::Gibraltar, CountryAlpha2::GR => Self::Greece, CountryAlpha2::GL => Self::Greenland, CountryAlpha2::GD => Self::Grenada, CountryAlpha2::GP => Self::Guadeloupe, CountryAlpha2::GU => Self::Guam, CountryAlpha2::GT => Self::Guatemala, CountryAlpha2::GG => Self::Guernsey, CountryAlpha2::GN => Self::Guinea, CountryAlpha2::GW => Self::GuineaBissau, CountryAlpha2::GY => Self::Guyana, CountryAlpha2::HT => Self::Haiti, CountryAlpha2::HM => Self::HeardIslandAndMcDonaldIslands, CountryAlpha2::VA => Self::HolySee, CountryAlpha2::HN => Self::Honduras, CountryAlpha2::HK => Self::HongKong, CountryAlpha2::HU => Self::Hungary, CountryAlpha2::IS => Self::Iceland, CountryAlpha2::IN => Self::India, CountryAlpha2::ID => Self::Indonesia, CountryAlpha2::IR => Self::IranIslamicRepublic, CountryAlpha2::IQ => Self::Iraq, CountryAlpha2::IE => Self::Ireland, CountryAlpha2::IM => Self::IsleOfMan, CountryAlpha2::IL => Self::Israel, CountryAlpha2::IT => Self::Italy, CountryAlpha2::JM => Self::Jamaica, CountryAlpha2::JP => Self::Japan, CountryAlpha2::JE => Self::Jersey, CountryAlpha2::JO => Self::Jordan, CountryAlpha2::KZ => Self::Kazakhstan, CountryAlpha2::KE => Self::Kenya, CountryAlpha2::KI => Self::Kiribati, CountryAlpha2::KP => Self::KoreaDemocraticPeoplesRepublic, CountryAlpha2::KR => Self::KoreaRepublic, CountryAlpha2::KW => Self::Kuwait, CountryAlpha2::KG => Self::Kyrgyzstan, CountryAlpha2::LA => Self::LaoPeoplesDemocraticRepublic, CountryAlpha2::LV => Self::Latvia, CountryAlpha2::LB => Self::Lebanon, CountryAlpha2::LS => Self::Lesotho, CountryAlpha2::LR => Self::Liberia, CountryAlpha2::LY => Self::Libya, CountryAlpha2::LI => Self::Liechtenstein, CountryAlpha2::LT => Self::Lithuania, CountryAlpha2::LU => Self::Luxembourg, CountryAlpha2::MO => Self::Macao, CountryAlpha2::MK => Self::MacedoniaTheFormerYugoslavRepublic, CountryAlpha2::MG => Self::Madagascar, CountryAlpha2::MW => Self::Malawi, CountryAlpha2::MY => Self::Malaysia, CountryAlpha2::MV => Self::Maldives, CountryAlpha2::ML => Self::Mali, CountryAlpha2::MT => Self::Malta, CountryAlpha2::MH => Self::MarshallIslands, CountryAlpha2::MQ => Self::Martinique, CountryAlpha2::MR => Self::Mauritania, CountryAlpha2::MU => Self::Mauritius, CountryAlpha2::YT => Self::Mayotte, CountryAlpha2::MX => Self::Mexico, CountryAlpha2::FM => Self::MicronesiaFederatedStates, CountryAlpha2::MD => Self::MoldovaRepublic, CountryAlpha2::MC => Self::Monaco, CountryAlpha2::MN => Self::Mongolia, CountryAlpha2::ME => Self::Montenegro, CountryAlpha2::MS => Self::Montserrat, CountryAlpha2::MA => Self::Morocco, CountryAlpha2::MZ => Self::Mozambique, CountryAlpha2::MM => Self::Myanmar, CountryAlpha2::NA => Self::Namibia, CountryAlpha2::NR => Self::Nauru, CountryAlpha2::NP => Self::Nepal, CountryAlpha2::NL => Self::Netherlands, CountryAlpha2::NC => Self::NewCaledonia, CountryAlpha2::NZ => Self::NewZealand, CountryAlpha2::NI => Self::Nicaragua, CountryAlpha2::NE => Self::Niger, CountryAlpha2::NG => Self::Nigeria, CountryAlpha2::NU => Self::Niue, CountryAlpha2::NF => Self::NorfolkIsland, CountryAlpha2::MP => Self::NorthernMarianaIslands, CountryAlpha2::NO => Self::Norway, CountryAlpha2::OM => Self::Oman, CountryAlpha2::PK => Self::Pakistan, CountryAlpha2::PW => Self::Palau, CountryAlpha2::PS => Self::PalestineState, CountryAlpha2::PA => Self::Panama, CountryAlpha2::PG => Self::PapuaNewGuinea, CountryAlpha2::PY => Self::Paraguay, CountryAlpha2::PE => Self::Peru, CountryAlpha2::PH => Self::Philippines, CountryAlpha2::PN => Self::Pitcairn, CountryAlpha2::PL => Self::Poland, CountryAlpha2::PT => Self::Portugal, CountryAlpha2::PR => Self::PuertoRico, CountryAlpha2::QA => Self::Qatar, CountryAlpha2::RE => Self::Reunion, CountryAlpha2::RO => Self::Romania, CountryAlpha2::RU => Self::RussianFederation, CountryAlpha2::RW => Self::Rwanda, CountryAlpha2::BL => Self::SaintBarthelemy, CountryAlpha2::SH => Self::SaintHelenaAscensionAndTristandaCunha, CountryAlpha2::KN => Self::SaintKittsAndNevis, CountryAlpha2::LC => Self::SaintLucia, CountryAlpha2::MF => Self::SaintMartinFrenchpart, CountryAlpha2::PM => Self::SaintPierreAndMiquelon, CountryAlpha2::VC => Self::SaintVincentAndTheGrenadines, CountryAlpha2::WS => Self::Samoa, CountryAlpha2::SM => Self::SanMarino, CountryAlpha2::ST => Self::SaoTomeAndPrincipe, CountryAlpha2::SA => Self::SaudiArabia, CountryAlpha2::SN => Self::Senegal, CountryAlpha2::RS => Self::Serbia, CountryAlpha2::SC => Self::Seychelles, CountryAlpha2::SL => Self::SierraLeone, CountryAlpha2::SG => Self::Singapore, CountryAlpha2::SX => Self::SintMaartenDutchpart, CountryAlpha2::SK => Self::Slovakia, CountryAlpha2::SI => Self::Slovenia, CountryAlpha2::SB => Self::SolomonIslands, CountryAlpha2::SO => Self::Somalia, CountryAlpha2::ZA => Self::SouthAfrica, CountryAlpha2::GS => Self::SouthGeorgiaAndTheSouthSandwichIslands, CountryAlpha2::SS => Self::SouthSudan, CountryAlpha2::ES => Self::Spain, CountryAlpha2::LK => Self::SriLanka, CountryAlpha2::SD => Self::Sudan, CountryAlpha2::SR => Self::Suriname, CountryAlpha2::SJ => Self::SvalbardAndJanMayen, CountryAlpha2::SZ => Self::Swaziland, CountryAlpha2::SE => Self::Sweden, CountryAlpha2::CH => Self::Switzerland, CountryAlpha2::SY => Self::SyrianArabRepublic, CountryAlpha2::TW => Self::TaiwanProvinceOfChina, CountryAlpha2::TJ => Self::Tajikistan, CountryAlpha2::TZ => Self::TanzaniaUnitedRepublic, CountryAlpha2::TH => Self::Thailand, CountryAlpha2::TL => Self::TimorLeste, CountryAlpha2::TG => Self::Togo, CountryAlpha2::TK => Self::Tokelau, CountryAlpha2::TO => Self::Tonga, CountryAlpha2::TT => Self::TrinidadAndTobago, CountryAlpha2::TN => Self::Tunisia, CountryAlpha2::TR => Self::Turkey, CountryAlpha2::TM => Self::Turkmenistan, CountryAlpha2::TC => Self::TurksAndCaicosIslands, CountryAlpha2::TV => Self::Tuvalu, CountryAlpha2::UG => Self::Uganda, CountryAlpha2::UA => Self::Ukraine, CountryAlpha2::AE => Self::UnitedArabEmirates, CountryAlpha2::GB => Self::UnitedKingdomOfGreatBritainAndNorthernIreland, CountryAlpha2::US => Self::UnitedStatesOfAmerica, CountryAlpha2::UM => Self::UnitedStatesMinorOutlyingIslands, CountryAlpha2::UY => Self::Uruguay, CountryAlpha2::UZ => Self::Uzbekistan, CountryAlpha2::VU => Self::Vanuatu, CountryAlpha2::VE => Self::VenezuelaBolivarianRepublic, CountryAlpha2::VN => Self::Vietnam, CountryAlpha2::VG => Self::VirginIslandsBritish, CountryAlpha2::VI => Self::VirginIslandsUS, CountryAlpha2::WF => Self::WallisAndFutuna, CountryAlpha2::EH => Self::WesternSahara, CountryAlpha2::YE => Self::Yemen, CountryAlpha2::ZM => Self::Zambia, CountryAlpha2::ZW => Self::Zimbabwe, } } pub const fn to_alpha2(self) -> CountryAlpha2 { match self { Self::Afghanistan => CountryAlpha2::AF, Self::AlandIslands => CountryAlpha2::AX, Self::Albania => CountryAlpha2::AL, Self::Algeria => CountryAlpha2::DZ, Self::AmericanSamoa => CountryAlpha2::AS, Self::Andorra => CountryAlpha2::AD, Self::Angola => CountryAlpha2::AO, Self::Anguilla => CountryAlpha2::AI, Self::Antarctica => CountryAlpha2::AQ, Self::AntiguaAndBarbuda => CountryAlpha2::AG, Self::Argentina => CountryAlpha2::AR, Self::Armenia => CountryAlpha2::AM, Self::Aruba => CountryAlpha2::AW, Self::Australia => CountryAlpha2::AU, Self::Austria => CountryAlpha2::AT, Self::Azerbaijan => CountryAlpha2::AZ, Self::Bahamas => CountryAlpha2::BS, Self::Bahrain => CountryAlpha2::BH, Self::Bangladesh => CountryAlpha2::BD, Self::Barbados => CountryAlpha2::BB, Self::Belarus => CountryAlpha2::BY, Self::Belgium => CountryAlpha2::BE, Self::Belize => CountryAlpha2::BZ, Self::Benin => CountryAlpha2::BJ, Self::Bermuda => CountryAlpha2::BM, Self::Bhutan => CountryAlpha2::BT, Self::BoliviaPlurinationalState => CountryAlpha2::BO, Self::BonaireSintEustatiusAndSaba => CountryAlpha2::BQ, Self::BosniaAndHerzegovina => CountryAlpha2::BA, Self::Botswana => CountryAlpha2::BW, Self::BouvetIsland => CountryAlpha2::BV, Self::Brazil => CountryAlpha2::BR, Self::BritishIndianOceanTerritory => CountryAlpha2::IO, Self::BruneiDarussalam => CountryAlpha2::BN, Self::Bulgaria => CountryAlpha2::BG, Self::BurkinaFaso => CountryAlpha2::BF, Self::Burundi => CountryAlpha2::BI, Self::CaboVerde => CountryAlpha2::CV, Self::Cambodia => CountryAlpha2::KH, Self::Cameroon => CountryAlpha2::CM, Self::Canada => CountryAlpha2::CA, Self::CaymanIslands => CountryAlpha2::KY, Self::CentralAfricanRepublic => CountryAlpha2::CF, Self::Chad => CountryAlpha2::TD, Self::Chile => CountryAlpha2::CL, Self::China => CountryAlpha2::CN, Self::ChristmasIsland => CountryAlpha2::CX, Self::CocosKeelingIslands => CountryAlpha2::CC, Self::Colombia => CountryAlpha2::CO, Self::Comoros => CountryAlpha2::KM, Self::Congo => CountryAlpha2::CG, Self::CongoDemocraticRepublic => CountryAlpha2::CD, Self::CookIslands => CountryAlpha2::CK, Self::CostaRica => CountryAlpha2::CR, Self::CotedIvoire => CountryAlpha2::CI, Self::Croatia => CountryAlpha2::HR, Self::Cuba => CountryAlpha2::CU, Self::Curacao => CountryAlpha2::CW, Self::Cyprus => CountryAlpha2::CY, Self::Czechia => CountryAlpha2::CZ, Self::Denmark => CountryAlpha2::DK, Self::Djibouti => CountryAlpha2::DJ, Self::Dominica => CountryAlpha2::DM, Self::DominicanRepublic => CountryAlpha2::DO, Self::Ecuador => CountryAlpha2::EC, Self::Egypt => CountryAlpha2::EG, Self::ElSalvador => CountryAlpha2::SV, Self::EquatorialGuinea => CountryAlpha2::GQ, Self::Eritrea => CountryAlpha2::ER, Self::Estonia => CountryAlpha2::EE, Self::Ethiopia => CountryAlpha2::ET, Self::FalklandIslandsMalvinas => CountryAlpha2::FK, Self::FaroeIslands => CountryAlpha2::FO, Self::Fiji => CountryAlpha2::FJ, Self::Finland => CountryAlpha2::FI, Self::France => CountryAlpha2::FR, Self::FrenchGuiana => CountryAlpha2::GF, Self::FrenchPolynesia => CountryAlpha2::PF, Self::FrenchSouthernTerritories => CountryAlpha2::TF, Self::Gabon => CountryAlpha2::GA, Self::Gambia => CountryAlpha2::GM, Self::Georgia => CountryAlpha2::GE, Self::Germany => CountryAlpha2::DE, Self::Ghana => CountryAlpha2::GH, Self::Gibraltar => CountryAlpha2::GI, Self::Greece => CountryAlpha2::GR, Self::Greenland => CountryAlpha2::GL, Self::Grenada => CountryAlpha2::GD, Self::Guadeloupe => CountryAlpha2::GP, Self::Guam => CountryAlpha2::GU, Self::Guatemala => CountryAlpha2::GT, Self::Guernsey => CountryAlpha2::GG, Self::Guinea => CountryAlpha2::GN, Self::GuineaBissau => CountryAlpha2::GW, Self::Guyana => CountryAlpha2::GY, Self::Haiti => CountryAlpha2::HT, Self::HeardIslandAndMcDonaldIslands => CountryAlpha2::HM, Self::HolySee => CountryAlpha2::VA, Self::Honduras => CountryAlpha2::HN, Self::HongKong => CountryAlpha2::HK, Self::Hungary => CountryAlpha2::HU, Self::Iceland => CountryAlpha2::IS, Self::India => CountryAlpha2::IN, Self::Indonesia => CountryAlpha2::ID, Self::IranIslamicRepublic => CountryAlpha2::IR, Self::Iraq => CountryAlpha2::IQ, Self::Ireland => CountryAlpha2::IE, Self::IsleOfMan => CountryAlpha2::IM, Self::Israel => CountryAlpha2::IL, Self::Italy => CountryAlpha2::IT, Self::Jamaica => CountryAlpha2::JM, Self::Japan => CountryAlpha2::JP, Self::Jersey => CountryAlpha2::JE, Self::Jordan => CountryAlpha2::JO, Self::Kazakhstan => CountryAlpha2::KZ, Self::Kenya => CountryAlpha2::KE, Self::Kiribati => CountryAlpha2::KI, Self::KoreaDemocraticPeoplesRepublic => CountryAlpha2::KP, Self::KoreaRepublic => CountryAlpha2::KR, Self::Kuwait => CountryAlpha2::KW, Self::Kyrgyzstan => CountryAlpha2::KG, Self::LaoPeoplesDemocraticRepublic => CountryAlpha2::LA, Self::Latvia => CountryAlpha2::LV, Self::Lebanon => CountryAlpha2::LB, Self::Lesotho => CountryAlpha2::LS, Self::Liberia => CountryAlpha2::LR, Self::Libya => CountryAlpha2::LY, Self::Liechtenstein => CountryAlpha2::LI, Self::Lithuania => CountryAlpha2::LT, Self::Luxembourg => CountryAlpha2::LU, Self::Macao => CountryAlpha2::MO, Self::MacedoniaTheFormerYugoslavRepublic => CountryAlpha2::MK, Self::Madagascar => CountryAlpha2::MG, Self::Malawi => CountryAlpha2::MW, Self::Malaysia => CountryAlpha2::MY, Self::Maldives => CountryAlpha2::MV, Self::Mali => CountryAlpha2::ML, Self::Malta => CountryAlpha2::MT, Self::MarshallIslands => CountryAlpha2::MH, Self::Martinique => CountryAlpha2::MQ, Self::Mauritania => CountryAlpha2::MR, Self::Mauritius => CountryAlpha2::MU, Self::Mayotte => CountryAlpha2::YT, Self::Mexico => CountryAlpha2::MX, Self::MicronesiaFederatedStates => CountryAlpha2::FM, Self::MoldovaRepublic => CountryAlpha2::MD, Self::Monaco => CountryAlpha2::MC, Self::Mongolia => CountryAlpha2::MN, Self::Montenegro => CountryAlpha2::ME, Self::Montserrat => CountryAlpha2::MS, Self::Morocco => CountryAlpha2::MA, Self::Mozambique => CountryAlpha2::MZ, Self::Myanmar => CountryAlpha2::MM, Self::Namibia => CountryAlpha2::NA, Self::Nauru => CountryAlpha2::NR, Self::Nepal => CountryAlpha2::NP, Self::Netherlands => CountryAlpha2::NL, Self::NewCaledonia => CountryAlpha2::NC, Self::NewZealand => CountryAlpha2::NZ, Self::Nicaragua => CountryAlpha2::NI, Self::Niger => CountryAlpha2::NE, Self::Nigeria => CountryAlpha2::NG, Self::Niue => CountryAlpha2::NU, Self::NorfolkIsland => CountryAlpha2::NF, Self::NorthernMarianaIslands => CountryAlpha2::MP, Self::Norway => CountryAlpha2::NO, Self::Oman => CountryAlpha2::OM, Self::Pakistan => CountryAlpha2::PK, Self::Palau => CountryAlpha2::PW, Self::PalestineState => CountryAlpha2::PS, Self::Panama => CountryAlpha2::PA, Self::PapuaNewGuinea => CountryAlpha2::PG, Self::Paraguay => CountryAlpha2::PY, Self::Peru => CountryAlpha2::PE, Self::Philippines => CountryAlpha2::PH, Self::Pitcairn => CountryAlpha2::PN, Self::Poland => CountryAlpha2::PL, Self::Portugal => CountryAlpha2::PT, Self::PuertoRico => CountryAlpha2::PR, Self::Qatar => CountryAlpha2::QA, Self::Reunion => CountryAlpha2::RE, Self::Romania => CountryAlpha2::RO, Self::RussianFederation => CountryAlpha2::RU, Self::Rwanda => CountryAlpha2::RW, Self::SaintBarthelemy => CountryAlpha2::BL, Self::SaintHelenaAscensionAndTristandaCunha => CountryAlpha2::SH, Self::SaintKittsAndNevis => CountryAlpha2::KN, Self::SaintLucia => CountryAlpha2::LC, Self::SaintMartinFrenchpart => CountryAlpha2::MF, Self::SaintPierreAndMiquelon => CountryAlpha2::PM, Self::SaintVincentAndTheGrenadines => CountryAlpha2::VC, Self::Samoa => CountryAlpha2::WS, Self::SanMarino => CountryAlpha2::SM, Self::SaoTomeAndPrincipe => CountryAlpha2::ST, Self::SaudiArabia => CountryAlpha2::SA, Self::Senegal => CountryAlpha2::SN, Self::Serbia => CountryAlpha2::RS, Self::Seychelles => CountryAlpha2::SC, Self::SierraLeone => CountryAlpha2::SL, Self::Singapore => CountryAlpha2::SG, Self::SintMaartenDutchpart => CountryAlpha2::SX, Self::Slovakia => CountryAlpha2::SK, Self::Slovenia => CountryAlpha2::SI, Self::SolomonIslands => CountryAlpha2::SB, Self::Somalia => CountryAlpha2::SO, Self::SouthAfrica => CountryAlpha2::ZA, Self::SouthGeorgiaAndTheSouthSandwichIslands => CountryAlpha2::GS, Self::SouthSudan => CountryAlpha2::SS, Self::Spain => CountryAlpha2::ES, Self::SriLanka => CountryAlpha2::LK, Self::Sudan => CountryAlpha2::SD, Self::Suriname => CountryAlpha2::SR, Self::SvalbardAndJanMayen => CountryAlpha2::SJ, Self::Swaziland => CountryAlpha2::SZ, Self::Sweden => CountryAlpha2::SE, Self::Switzerland => CountryAlpha2::CH, Self::SyrianArabRepublic => CountryAlpha2::SY, Self::TaiwanProvinceOfChina => CountryAlpha2::TW, Self::Tajikistan => CountryAlpha2::TJ, Self::TanzaniaUnitedRepublic => CountryAlpha2::TZ, Self::Thailand => CountryAlpha2::TH, Self::TimorLeste => CountryAlpha2::TL, Self::Togo => CountryAlpha2::TG, Self::Tokelau => CountryAlpha2::TK, Self::Tonga => CountryAlpha2::TO, Self::TrinidadAndTobago => CountryAlpha2::TT, Self::Tunisia => CountryAlpha2::TN, Self::Turkey => CountryAlpha2::TR, Self::Turkmenistan => CountryAlpha2::TM, Self::TurksAndCaicosIslands => CountryAlpha2::TC, Self::Tuvalu => CountryAlpha2::TV, Self::Uganda => CountryAlpha2::UG, Self::Ukraine => CountryAlpha2::UA, Self::UnitedArabEmirates => CountryAlpha2::AE, Self::UnitedKingdomOfGreatBritainAndNorthernIreland => CountryAlpha2::GB, Self::UnitedStatesOfAmerica => CountryAlpha2::US, Self::UnitedStatesMinorOutlyingIslands => CountryAlpha2::UM, Self::Uruguay => CountryAlpha2::UY, Self::Uzbekistan => CountryAlpha2::UZ, Self::Vanuatu => CountryAlpha2::VU, Self::VenezuelaBolivarianRepublic => CountryAlpha2::VE, Self::Vietnam => CountryAlpha2::VN, Self::VirginIslandsBritish => CountryAlpha2::VG, Self::VirginIslandsUS => CountryAlpha2::VI, Self::WallisAndFutuna => CountryAlpha2::WF, Self::WesternSahara => CountryAlpha2::EH, Self::Yemen => CountryAlpha2::YE, Self::Zambia => CountryAlpha2::ZM, Self::Zimbabwe => CountryAlpha2::ZW, } } pub const fn from_alpha3(code: CountryAlpha3) -> Self { match code { CountryAlpha3::AFG => Self::Afghanistan, CountryAlpha3::ALA => Self::AlandIslands, CountryAlpha3::ALB => Self::Albania, CountryAlpha3::DZA => Self::Algeria, CountryAlpha3::ASM => Self::AmericanSamoa, CountryAlpha3::AND => Self::Andorra, CountryAlpha3::AGO => Self::Angola, CountryAlpha3::AIA => Self::Anguilla, CountryAlpha3::ATA => Self::Antarctica, CountryAlpha3::ATG => Self::AntiguaAndBarbuda, CountryAlpha3::ARG => Self::Argentina, CountryAlpha3::ARM => Self::Armenia, CountryAlpha3::ABW => Self::Aruba, CountryAlpha3::AUS => Self::Australia, CountryAlpha3::AUT => Self::Austria, CountryAlpha3::AZE => Self::Azerbaijan, CountryAlpha3::BHS => Self::Bahamas, CountryAlpha3::BHR => Self::Bahrain, CountryAlpha3::BGD => Self::Bangladesh, CountryAlpha3::BRB => Self::Barbados, CountryAlpha3::BLR => Self::Belarus, CountryAlpha3::BEL => Self::Belgium, CountryAlpha3::BLZ => Self::Belize, CountryAlpha3::BEN => Self::Benin, CountryAlpha3::BMU => Self::Bermuda, CountryAlpha3::BTN => Self::Bhutan, CountryAlpha3::BOL => Self::BoliviaPlurinationalState, CountryAlpha3::BES => Self::BonaireSintEustatiusAndSaba, CountryAlpha3::BIH => Self::BosniaAndHerzegovina, CountryAlpha3::BWA => Self::Botswana, CountryAlpha3::BVT => Self::BouvetIsland, CountryAlpha3::BRA => Self::Brazil, CountryAlpha3::IOT => Self::BritishIndianOceanTerritory, CountryAlpha3::BRN => Self::BruneiDarussalam, CountryAlpha3::BGR => Self::Bulgaria, CountryAlpha3::BFA => Self::BurkinaFaso, CountryAlpha3::BDI => Self::Burundi, CountryAlpha3::CPV => Self::CaboVerde, CountryAlpha3::KHM => Self::Cambodia, CountryAlpha3::CMR => Self::Cameroon, CountryAlpha3::CAN => Self::Canada, CountryAlpha3::CYM => Self::CaymanIslands, CountryAlpha3::CAF => Self::CentralAfricanRepublic, CountryAlpha3::TCD => Self::Chad, CountryAlpha3::CHL => Self::Chile, CountryAlpha3::CHN => Self::China, CountryAlpha3::CXR => Self::ChristmasIsland, CountryAlpha3::CCK => Self::CocosKeelingIslands, CountryAlpha3::COL => Self::Colombia, CountryAlpha3::COM => Self::Comoros, CountryAlpha3::COG => Self::Congo, CountryAlpha3::COD => Self::CongoDemocraticRepublic, CountryAlpha3::COK => Self::CookIslands, CountryAlpha3::CRI => Self::CostaRica, CountryAlpha3::CIV => Self::CotedIvoire, CountryAlpha3::HRV => Self::Croatia, CountryAlpha3::CUB => Self::Cuba, CountryAlpha3::CUW => Self::Curacao, CountryAlpha3::CYP => Self::Cyprus, CountryAlpha3::CZE => Self::Czechia, CountryAlpha3::DNK => Self::Denmark, CountryAlpha3::DJI => Self::Djibouti, CountryAlpha3::DMA => Self::Dominica, CountryAlpha3::DOM => Self::DominicanRepublic, CountryAlpha3::ECU => Self::Ecuador, CountryAlpha3::EGY => Self::Egypt, CountryAlpha3::SLV => Self::ElSalvador, CountryAlpha3::GNQ => Self::EquatorialGuinea, CountryAlpha3::ERI => Self::Eritrea, CountryAlpha3::EST => Self::Estonia, CountryAlpha3::ETH => Self::Ethiopia, CountryAlpha3::FLK => Self::FalklandIslandsMalvinas, CountryAlpha3::FRO => Self::FaroeIslands, CountryAlpha3::FJI => Self::Fiji, CountryAlpha3::FIN => Self::Finland, CountryAlpha3::FRA => Self::France, CountryAlpha3::GUF => Self::FrenchGuiana, CountryAlpha3::PYF => Self::FrenchPolynesia, CountryAlpha3::ATF => Self::FrenchSouthernTerritories, CountryAlpha3::GAB => Self::Gabon, CountryAlpha3::GMB => Self::Gambia, CountryAlpha3::GEO => Self::Georgia, CountryAlpha3::DEU => Self::Germany, CountryAlpha3::GHA => Self::Ghana, CountryAlpha3::GIB => Self::Gibraltar, CountryAlpha3::GRC => Self::Greece, CountryAlpha3::GRL => Self::Greenland, CountryAlpha3::GRD => Self::Grenada, CountryAlpha3::GLP => Self::Guadeloupe, CountryAlpha3::GUM => Self::Guam, CountryAlpha3::GTM => Self::Guatemala, CountryAlpha3::GGY => Self::Guernsey, CountryAlpha3::GIN => Self::Guinea, CountryAlpha3::GNB => Self::GuineaBissau, CountryAlpha3::GUY => Self::Guyana, CountryAlpha3::HTI => Self::Haiti, CountryAlpha3::HMD => Self::HeardIslandAndMcDonaldIslands, CountryAlpha3::VAT => Self::HolySee, CountryAlpha3::HND => Self::Honduras, CountryAlpha3::HKG => Self::HongKong, CountryAlpha3::HUN => Self::Hungary, CountryAlpha3::ISL => Self::Iceland, CountryAlpha3::IND => Self::India, CountryAlpha3::IDN => Self::Indonesia, CountryAlpha3::IRN => Self::IranIslamicRepublic, CountryAlpha3::IRQ => Self::Iraq, CountryAlpha3::IRL => Self::Ireland, CountryAlpha3::IMN => Self::IsleOfMan, CountryAlpha3::ISR => Self::Israel, CountryAlpha3::ITA => Self::Italy, CountryAlpha3::JAM => Self::Jamaica, CountryAlpha3::JPN => Self::Japan, CountryAlpha3::JEY => Self::Jersey, CountryAlpha3::JOR => Self::Jordan, CountryAlpha3::KAZ => Self::Kazakhstan, CountryAlpha3::KEN => Self::Kenya, CountryAlpha3::KIR => Self::Kiribati, CountryAlpha3::PRK => Self::KoreaDemocraticPeoplesRepublic, CountryAlpha3::KOR => Self::KoreaRepublic, CountryAlpha3::KWT => Self::Kuwait, CountryAlpha3::KGZ => Self::Kyrgyzstan, CountryAlpha3::LAO => Self::LaoPeoplesDemocraticRepublic, CountryAlpha3::LVA => Self::Latvia, CountryAlpha3::LBN => Self::Lebanon, CountryAlpha3::LSO => Self::Lesotho, CountryAlpha3::LBR => Self::Liberia, CountryAlpha3::LBY => Self::Libya, CountryAlpha3::LIE => Self::Liechtenstein, CountryAlpha3::LTU => Self::Lithuania, CountryAlpha3::LUX => Self::Luxembourg, CountryAlpha3::MAC => Self::Macao, CountryAlpha3::MKD => Self::MacedoniaTheFormerYugoslavRepublic, CountryAlpha3::MDG => Self::Madagascar, CountryAlpha3::MWI => Self::Malawi, CountryAlpha3::MYS => Self::Malaysia, CountryAlpha3::MDV => Self::Maldives, CountryAlpha3::MLI => Self::Mali, CountryAlpha3::MLT => Self::Malta, CountryAlpha3::MHL => Self::MarshallIslands, CountryAlpha3::MTQ => Self::Martinique, CountryAlpha3::MRT => Self::Mauritania, CountryAlpha3::MUS => Self::Mauritius, CountryAlpha3::MYT => Self::Mayotte, CountryAlpha3::MEX => Self::Mexico, CountryAlpha3::FSM => Self::MicronesiaFederatedStates, CountryAlpha3::MDA => Self::MoldovaRepublic, CountryAlpha3::MCO => Self::Monaco, CountryAlpha3::MNG => Self::Mongolia, CountryAlpha3::MNE => Self::Montenegro, CountryAlpha3::MSR => Self::Montserrat, CountryAlpha3::MAR => Self::Morocco, CountryAlpha3::MOZ => Self::Mozambique, CountryAlpha3::MMR => Self::Myanmar, CountryAlpha3::NAM => Self::Namibia, CountryAlpha3::NRU => Self::Nauru, CountryAlpha3::NPL => Self::Nepal, CountryAlpha3::NLD => Self::Netherlands, CountryAlpha3::NCL => Self::NewCaledonia, CountryAlpha3::NZL => Self::NewZealand, CountryAlpha3::NIC => Self::Nicaragua, CountryAlpha3::NER => Self::Niger, CountryAlpha3::NGA => Self::Nigeria, CountryAlpha3::NIU => Self::Niue, CountryAlpha3::NFK => Self::NorfolkIsland, CountryAlpha3::MNP => Self::NorthernMarianaIslands, CountryAlpha3::NOR => Self::Norway, CountryAlpha3::OMN => Self::Oman, CountryAlpha3::PAK => Self::Pakistan, CountryAlpha3::PLW => Self::Palau, CountryAlpha3::PSE => Self::PalestineState, CountryAlpha3::PAN => Self::Panama, CountryAlpha3::PNG => Self::PapuaNewGuinea, CountryAlpha3::PRY => Self::Paraguay, CountryAlpha3::PER => Self::Peru, CountryAlpha3::PHL => Self::Philippines, CountryAlpha3::PCN => Self::Pitcairn, CountryAlpha3::POL => Self::Poland, CountryAlpha3::PRT => Self::Portugal, CountryAlpha3::PRI => Self::PuertoRico, CountryAlpha3::QAT => Self::Qatar, CountryAlpha3::REU => Self::Reunion, CountryAlpha3::ROU => Self::Romania, CountryAlpha3::RUS => Self::RussianFederation, CountryAlpha3::RWA => Self::Rwanda, CountryAlpha3::BLM => Self::SaintBarthelemy, CountryAlpha3::SHN => Self::SaintHelenaAscensionAndTristandaCunha, CountryAlpha3::KNA => Self::SaintKittsAndNevis, CountryAlpha3::LCA => Self::SaintLucia, CountryAlpha3::MAF => Self::SaintMartinFrenchpart, CountryAlpha3::SPM => Self::SaintPierreAndMiquelon, CountryAlpha3::VCT => Self::SaintVincentAndTheGrenadines, CountryAlpha3::WSM => Self::Samoa, CountryAlpha3::SMR => Self::SanMarino, CountryAlpha3::STP => Self::SaoTomeAndPrincipe, CountryAlpha3::SAU => Self::SaudiArabia, CountryAlpha3::SEN => Self::Senegal, CountryAlpha3::SRB => Self::Serbia, CountryAlpha3::SYC => Self::Seychelles, CountryAlpha3::SLE => Self::SierraLeone, CountryAlpha3::SGP => Self::Singapore, CountryAlpha3::SXM => Self::SintMaartenDutchpart, CountryAlpha3::SVK => Self::Slovakia, CountryAlpha3::SVN => Self::Slovenia, CountryAlpha3::SLB => Self::SolomonIslands, CountryAlpha3::SOM => Self::Somalia, CountryAlpha3::ZAF => Self::SouthAfrica, CountryAlpha3::SGS => Self::SouthGeorgiaAndTheSouthSandwichIslands, CountryAlpha3::SSD => Self::SouthSudan, CountryAlpha3::ESP => Self::Spain, CountryAlpha3::LKA => Self::SriLanka, CountryAlpha3::SDN => Self::Sudan, CountryAlpha3::SUR => Self::Suriname, CountryAlpha3::SJM => Self::SvalbardAndJanMayen, CountryAlpha3::SWZ => Self::Swaziland, CountryAlpha3::SWE => Self::Sweden, CountryAlpha3::CHE => Self::Switzerland, CountryAlpha3::SYR => Self::SyrianArabRepublic, CountryAlpha3::TWN => Self::TaiwanProvinceOfChina, CountryAlpha3::TJK => Self::Tajikistan, CountryAlpha3::TZA => Self::TanzaniaUnitedRepublic, CountryAlpha3::THA => Self::Thailand, CountryAlpha3::TLS => Self::TimorLeste, CountryAlpha3::TGO => Self::Togo, CountryAlpha3::TKL => Self::Tokelau, CountryAlpha3::TON => Self::Tonga, CountryAlpha3::TTO => Self::TrinidadAndTobago, CountryAlpha3::TUN => Self::Tunisia, CountryAlpha3::TUR => Self::Turkey, CountryAlpha3::TKM => Self::Turkmenistan, CountryAlpha3::TCA => Self::TurksAndCaicosIslands, CountryAlpha3::TUV => Self::Tuvalu, CountryAlpha3::UGA => Self::Uganda, CountryAlpha3::UKR => Self::Ukraine, CountryAlpha3::ARE => Self::UnitedArabEmirates, CountryAlpha3::GBR => Self::UnitedKingdomOfGreatBritainAndNorthernIreland, CountryAlpha3::USA => Self::UnitedStatesOfAmerica, CountryAlpha3::UMI => Self::UnitedStatesMinorOutlyingIslands, CountryAlpha3::URY => Self::Uruguay, CountryAlpha3::UZB => Self::Uzbekistan, CountryAlpha3::VUT => Self::Vanuatu, CountryAlpha3::VEN => Self::VenezuelaBolivarianRepublic, CountryAlpha3::VNM => Self::Vietnam, CountryAlpha3::VGB => Self::VirginIslandsBritish, CountryAlpha3::VIR => Self::VirginIslandsUS, CountryAlpha3::WLF => Self::WallisAndFutuna, CountryAlpha3::ESH => Self::WesternSahara, CountryAlpha3::YEM => Self::Yemen, CountryAlpha3::ZMB => Self::Zambia, CountryAlpha3::ZWE => Self::Zimbabwe, } } pub const fn to_alpha3(self) -> CountryAlpha3 { match self { Self::Afghanistan => CountryAlpha3::AFG, Self::AlandIslands => CountryAlpha3::ALA, Self::Albania => CountryAlpha3::ALB, Self::Algeria => CountryAlpha3::DZA, Self::AmericanSamoa => CountryAlpha3::ASM, Self::Andorra => CountryAlpha3::AND, Self::Angola => CountryAlpha3::AGO, Self::Anguilla => CountryAlpha3::AIA, Self::Antarctica => CountryAlpha3::ATA, Self::AntiguaAndBarbuda => CountryAlpha3::ATG, Self::Argentina => CountryAlpha3::ARG, Self::Armenia => CountryAlpha3::ARM, Self::Aruba => CountryAlpha3::ABW, Self::Australia => CountryAlpha3::AUS, Self::Austria => CountryAlpha3::AUT, Self::Azerbaijan => CountryAlpha3::AZE, Self::Bahamas => CountryAlpha3::BHS, Self::Bahrain => CountryAlpha3::BHR, Self::Bangladesh => CountryAlpha3::BGD, Self::Barbados => CountryAlpha3::BRB, Self::Belarus => CountryAlpha3::BLR, Self::Belgium => CountryAlpha3::BEL, Self::Belize => CountryAlpha3::BLZ, Self::Benin => CountryAlpha3::BEN, Self::Bermuda => CountryAlpha3::BMU, Self::Bhutan => CountryAlpha3::BTN, Self::BoliviaPlurinationalState => CountryAlpha3::BOL, Self::BonaireSintEustatiusAndSaba => CountryAlpha3::BES, Self::BosniaAndHerzegovina => CountryAlpha3::BIH, Self::Botswana => CountryAlpha3::BWA, Self::BouvetIsland => CountryAlpha3::BVT, Self::Brazil => CountryAlpha3::BRA, Self::BritishIndianOceanTerritory => CountryAlpha3::IOT, Self::BruneiDarussalam => CountryAlpha3::BRN, Self::Bulgaria => CountryAlpha3::BGR, Self::BurkinaFaso => CountryAlpha3::BFA, Self::Burundi => CountryAlpha3::BDI, Self::CaboVerde => CountryAlpha3::CPV, Self::Cambodia => CountryAlpha3::KHM, Self::Cameroon => CountryAlpha3::CMR, Self::Canada => CountryAlpha3::CAN, Self::CaymanIslands => CountryAlpha3::CYM, Self::CentralAfricanRepublic => CountryAlpha3::CAF, Self::Chad => CountryAlpha3::TCD, Self::Chile => CountryAlpha3::CHL, Self::China => CountryAlpha3::CHN, Self::ChristmasIsland => CountryAlpha3::CXR, Self::CocosKeelingIslands => CountryAlpha3::CCK, Self::Colombia => CountryAlpha3::COL, Self::Comoros => CountryAlpha3::COM, Self::Congo => CountryAlpha3::COG, Self::CongoDemocraticRepublic => CountryAlpha3::COD, Self::CookIslands => CountryAlpha3::COK, Self::CostaRica => CountryAlpha3::CRI, Self::CotedIvoire => CountryAlpha3::CIV, Self::Croatia => CountryAlpha3::HRV, Self::Cuba => CountryAlpha3::CUB, Self::Curacao => CountryAlpha3::CUW, Self::Cyprus => CountryAlpha3::CYP, Self::Czechia => CountryAlpha3::CZE, Self::Denmark => CountryAlpha3::DNK, Self::Djibouti => CountryAlpha3::DJI, Self::Dominica => CountryAlpha3::DMA, Self::DominicanRepublic => CountryAlpha3::DOM, Self::Ecuador => CountryAlpha3::ECU, Self::Egypt => CountryAlpha3::EGY, Self::ElSalvador => CountryAlpha3::SLV, Self::EquatorialGuinea => CountryAlpha3::GNQ, Self::Eritrea => CountryAlpha3::ERI, Self::Estonia => CountryAlpha3::EST, Self::Ethiopia => CountryAlpha3::ETH, Self::FalklandIslandsMalvinas => CountryAlpha3::FLK, Self::FaroeIslands => CountryAlpha3::FRO, Self::Fiji => CountryAlpha3::FJI, Self::Finland => CountryAlpha3::FIN, Self::France => CountryAlpha3::FRA, Self::FrenchGuiana => CountryAlpha3::GUF, Self::FrenchPolynesia => CountryAlpha3::PYF, Self::FrenchSouthernTerritories => CountryAlpha3::ATF, Self::Gabon => CountryAlpha3::GAB, Self::Gambia => CountryAlpha3::GMB, Self::Georgia => CountryAlpha3::GEO, Self::Germany => CountryAlpha3::DEU, Self::Ghana => CountryAlpha3::GHA, Self::Gibraltar => CountryAlpha3::GIB, Self::Greece => CountryAlpha3::GRC, Self::Greenland => CountryAlpha3::GRL, Self::Grenada => CountryAlpha3::GRD, Self::Guadeloupe => CountryAlpha3::GLP, Self::Guam => CountryAlpha3::GUM, Self::Guatemala => CountryAlpha3::GTM, Self::Guernsey => CountryAlpha3::GGY, Self::Guinea => CountryAlpha3::GIN, Self::GuineaBissau => CountryAlpha3::GNB, Self::Guyana => CountryAlpha3::GUY, Self::Haiti => CountryAlpha3::HTI, Self::HeardIslandAndMcDonaldIslands => CountryAlpha3::HMD, Self::HolySee => CountryAlpha3::VAT, Self::Honduras => CountryAlpha3::HND, Self::HongKong => CountryAlpha3::HKG, Self::Hungary => CountryAlpha3::HUN, Self::Iceland => CountryAlpha3::ISL, Self::India => CountryAlpha3::IND, Self::Indonesia => CountryAlpha3::IDN, Self::IranIslamicRepublic => CountryAlpha3::IRN, Self::Iraq => CountryAlpha3::IRQ, Self::Ireland => CountryAlpha3::IRL, Self::IsleOfMan => CountryAlpha3::IMN, Self::Israel => CountryAlpha3::ISR, Self::Italy => CountryAlpha3::ITA, Self::Jamaica => CountryAlpha3::JAM, Self::Japan => CountryAlpha3::JPN, Self::Jersey => CountryAlpha3::JEY, Self::Jordan => CountryAlpha3::JOR, Self::Kazakhstan => CountryAlpha3::KAZ, Self::Kenya => CountryAlpha3::KEN, Self::Kiribati => CountryAlpha3::KIR, Self::KoreaDemocraticPeoplesRepublic => CountryAlpha3::PRK, Self::KoreaRepublic => CountryAlpha3::KOR, Self::Kuwait => CountryAlpha3::KWT, Self::Kyrgyzstan => CountryAlpha3::KGZ, Self::LaoPeoplesDemocraticRepublic => CountryAlpha3::LAO, Self::Latvia => CountryAlpha3::LVA, Self::Lebanon => CountryAlpha3::LBN, Self::Lesotho => CountryAlpha3::LSO, Self::Liberia => CountryAlpha3::LBR, Self::Libya => CountryAlpha3::LBY, Self::Liechtenstein => CountryAlpha3::LIE, Self::Lithuania => CountryAlpha3::LTU, Self::Luxembourg => CountryAlpha3::LUX, Self::Macao => CountryAlpha3::MAC, Self::MacedoniaTheFormerYugoslavRepublic => CountryAlpha3::MKD, Self::Madagascar => CountryAlpha3::MDG, Self::Malawi => CountryAlpha3::MWI, Self::Malaysia => CountryAlpha3::MYS, Self::Maldives => CountryAlpha3::MDV, Self::Mali => CountryAlpha3::MLI, Self::Malta => CountryAlpha3::MLT, Self::MarshallIslands => CountryAlpha3::MHL, Self::Martinique => CountryAlpha3::MTQ, Self::Mauritania => CountryAlpha3::MRT, Self::Mauritius => CountryAlpha3::MUS, Self::Mayotte => CountryAlpha3::MYT, Self::Mexico => CountryAlpha3::MEX, Self::MicronesiaFederatedStates => CountryAlpha3::FSM, Self::MoldovaRepublic => CountryAlpha3::MDA, Self::Monaco => CountryAlpha3::MCO, Self::Mongolia => CountryAlpha3::MNG, Self::Montenegro => CountryAlpha3::MNE, Self::Montserrat => CountryAlpha3::MSR, Self::Morocco => CountryAlpha3::MAR, Self::Mozambique => CountryAlpha3::MOZ, Self::Myanmar => CountryAlpha3::MMR, Self::Namibia => CountryAlpha3::NAM, Self::Nauru => CountryAlpha3::NRU, Self::Nepal => CountryAlpha3::NPL, Self::Netherlands => CountryAlpha3::NLD, Self::NewCaledonia => CountryAlpha3::NCL, Self::NewZealand => CountryAlpha3::NZL, Self::Nicaragua => CountryAlpha3::NIC, Self::Niger => CountryAlpha3::NER, Self::Nigeria => CountryAlpha3::NGA, Self::Niue => CountryAlpha3::NIU, Self::NorfolkIsland => CountryAlpha3::NFK, Self::NorthernMarianaIslands => CountryAlpha3::MNP, Self::Norway => CountryAlpha3::NOR, Self::Oman => CountryAlpha3::OMN, Self::Pakistan => CountryAlpha3::PAK, Self::Palau => CountryAlpha3::PLW, Self::PalestineState => CountryAlpha3::PSE, Self::Panama => CountryAlpha3::PAN, Self::PapuaNewGuinea => CountryAlpha3::PNG, Self::Paraguay => CountryAlpha3::PRY, Self::Peru => CountryAlpha3::PER, Self::Philippines => CountryAlpha3::PHL, Self::Pitcairn => CountryAlpha3::PCN, Self::Poland => CountryAlpha3::POL, Self::Portugal => CountryAlpha3::PRT, Self::PuertoRico => CountryAlpha3::PRI, Self::Qatar => CountryAlpha3::QAT, Self::Reunion => CountryAlpha3::REU, Self::Romania => CountryAlpha3::ROU, Self::RussianFederation => CountryAlpha3::RUS, Self::Rwanda => CountryAlpha3::RWA, Self::SaintBarthelemy => CountryAlpha3::BLM, Self::SaintHelenaAscensionAndTristandaCunha => CountryAlpha3::SHN, Self::SaintKittsAndNevis => CountryAlpha3::KNA, Self::SaintLucia => CountryAlpha3::LCA, Self::SaintMartinFrenchpart => CountryAlpha3::MAF, Self::SaintPierreAndMiquelon => CountryAlpha3::SPM, Self::SaintVincentAndTheGrenadines => CountryAlpha3::VCT, Self::Samoa => CountryAlpha3::WSM, Self::SanMarino => CountryAlpha3::SMR, Self::SaoTomeAndPrincipe => CountryAlpha3::STP, Self::SaudiArabia => CountryAlpha3::SAU, Self::Senegal => CountryAlpha3::SEN, Self::Serbia => CountryAlpha3::SRB, Self::Seychelles => CountryAlpha3::SYC, Self::SierraLeone => CountryAlpha3::SLE, Self::Singapore => CountryAlpha3::SGP, Self::SintMaartenDutchpart => CountryAlpha3::SXM, Self::Slovakia => CountryAlpha3::SVK, Self::Slovenia => CountryAlpha3::SVN, Self::SolomonIslands => CountryAlpha3::SLB, Self::Somalia => CountryAlpha3::SOM, Self::SouthAfrica => CountryAlpha3::ZAF, Self::SouthGeorgiaAndTheSouthSandwichIslands => CountryAlpha3::SGS, Self::SouthSudan => CountryAlpha3::SSD, Self::Spain => CountryAlpha3::ESP, Self::SriLanka => CountryAlpha3::LKA, Self::Sudan => CountryAlpha3::SDN, Self::Suriname => CountryAlpha3::SUR, Self::SvalbardAndJanMayen => CountryAlpha3::SJM, Self::Swaziland => CountryAlpha3::SWZ, Self::Sweden => CountryAlpha3::SWE, Self::Switzerland => CountryAlpha3::CHE, Self::SyrianArabRepublic => CountryAlpha3::SYR, Self::TaiwanProvinceOfChina => CountryAlpha3::TWN, Self::Tajikistan => CountryAlpha3::TJK, Self::TanzaniaUnitedRepublic => CountryAlpha3::TZA, Self::Thailand => CountryAlpha3::THA, Self::TimorLeste => CountryAlpha3::TLS, Self::Togo => CountryAlpha3::TGO, Self::Tokelau => CountryAlpha3::TKL, Self::Tonga => CountryAlpha3::TON, Self::TrinidadAndTobago => CountryAlpha3::TTO, Self::Tunisia => CountryAlpha3::TUN, Self::Turkey => CountryAlpha3::TUR, Self::Turkmenistan => CountryAlpha3::TKM, Self::TurksAndCaicosIslands => CountryAlpha3::TCA, Self::Tuvalu => CountryAlpha3::TUV, Self::Uganda => CountryAlpha3::UGA, Self::Ukraine => CountryAlpha3::UKR, Self::UnitedArabEmirates => CountryAlpha3::ARE, Self::UnitedKingdomOfGreatBritainAndNorthernIreland => CountryAlpha3::GBR, Self::UnitedStatesOfAmerica => CountryAlpha3::USA, Self::UnitedStatesMinorOutlyingIslands => CountryAlpha3::UMI, Self::Uruguay => CountryAlpha3::URY, Self::Uzbekistan => CountryAlpha3::UZB, Self::Vanuatu => CountryAlpha3::VUT, Self::VenezuelaBolivarianRepublic => CountryAlpha3::VEN, Self::Vietnam => CountryAlpha3::VNM, Self::VirginIslandsBritish => CountryAlpha3::VGB, Self::VirginIslandsUS => CountryAlpha3::VIR, Self::WallisAndFutuna => CountryAlpha3::WLF, Self::WesternSahara => CountryAlpha3::ESH, Self::Yemen => CountryAlpha3::YEM, Self::Zambia => CountryAlpha3::ZMB, Self::Zimbabwe => CountryAlpha3::ZWE, } } pub const fn from_numeric(code: u32) -> Result<Self, NumericCountryCodeParseError> { match code { 4 => Ok(Self::Afghanistan), 248 => Ok(Self::AlandIslands), 8 => Ok(Self::Albania), 12 => Ok(Self::Algeria), 16 => Ok(Self::AmericanSamoa), 20 => Ok(Self::Andorra), 24 => Ok(Self::Angola), 660 => Ok(Self::Anguilla), 10 => Ok(Self::Antarctica), 28 => Ok(Self::AntiguaAndBarbuda), 32 => Ok(Self::Argentina), 51 => Ok(Self::Armenia), 533 => Ok(Self::Aruba), 36 => Ok(Self::Australia), 40 => Ok(Self::Austria), 31 => Ok(Self::Azerbaijan), 44 => Ok(Self::Bahamas), 48 => Ok(Self::Bahrain), 50 => Ok(Self::Bangladesh), 52 => Ok(Self::Barbados), 112 => Ok(Self::Belarus), 56 => Ok(Self::Belgium), 84 => Ok(Self::Belize), 204 => Ok(Self::Benin), 60 => Ok(Self::Bermuda), 64 => Ok(Self::Bhutan), 68 => Ok(Self::BoliviaPlurinationalState), 535 => Ok(Self::BonaireSintEustatiusAndSaba), 70 => Ok(Self::BosniaAndHerzegovina), 72 => Ok(Self::Botswana), 74 => Ok(Self::BouvetIsland), 76 => Ok(Self::Brazil), 86 => Ok(Self::BritishIndianOceanTerritory), 96 => Ok(Self::BruneiDarussalam), 100 => Ok(Self::Bulgaria), 854 => Ok(Self::BurkinaFaso), 108 => Ok(Self::Burundi), 132 => Ok(Self::CaboVerde), 116 => Ok(Self::Cambodia), 120 => Ok(Self::Cameroon), 124 => Ok(Self::Canada), 136 => Ok(Self::CaymanIslands), 140 => Ok(Self::CentralAfricanRepublic), 148 => Ok(Self::Chad), 152 => Ok(Self::Chile), 156 => Ok(Self::China), 162 => Ok(Self::ChristmasIsland), 166 => Ok(Self::CocosKeelingIslands), 170 => Ok(Self::Colombia), 174 => Ok(Self::Comoros), 178 => Ok(Self::Congo), 180 => Ok(Self::CongoDemocraticRepublic), 184 => Ok(Self::CookIslands), 188 => Ok(Self::CostaRica), 384 => Ok(Self::CotedIvoire), 191 => Ok(Self::Croatia), 192 => Ok(Self::Cuba), 531 => Ok(Self::Curacao), 196 => Ok(Self::Cyprus), 203 => Ok(Self::Czechia), 208 => Ok(Self::Denmark), 262 => Ok(Self::Djibouti), 212 => Ok(Self::Dominica), 214 => Ok(Self::DominicanRepublic), 218 => Ok(Self::Ecuador), 818 => Ok(Self::Egypt), 222 => Ok(Self::ElSalvador), 226 => Ok(Self::EquatorialGuinea), 232 => Ok(Self::Eritrea), 233 => Ok(Self::Estonia), 231 => Ok(Self::Ethiopia), 238 => Ok(Self::FalklandIslandsMalvinas), 234 => Ok(Self::FaroeIslands), 242 => Ok(Self::Fiji), 246 => Ok(Self::Finland), 250 => Ok(Self::France), 254 => Ok(Self::FrenchGuiana), 258 => Ok(Self::FrenchPolynesia), 260 => Ok(Self::FrenchSouthernTerritories), 266 => Ok(Self::Gabon), 270 => Ok(Self::Gambia), 268 => Ok(Self::Georgia), 276 => Ok(Self::Germany), 288 => Ok(Self::Ghana), 292 => Ok(Self::Gibraltar), 300 => Ok(Self::Greece), 304 => Ok(Self::Greenland), 308 => Ok(Self::Grenada), 312 => Ok(Self::Guadeloupe), 316 => Ok(Self::Guam), 320 => Ok(Self::Guatemala), 831 => Ok(Self::Guernsey), 324 => Ok(Self::Guinea), 624 => Ok(Self::GuineaBissau), 328 => Ok(Self::Guyana), 332 => Ok(Self::Haiti), 334 => Ok(Self::HeardIslandAndMcDonaldIslands), 336 => Ok(Self::HolySee), 340 => Ok(Self::Honduras), 344 => Ok(Self::HongKong), 348 => Ok(Self::Hungary), 352 => Ok(Self::Iceland), 356 => Ok(Self::India), 360 => Ok(Self::Indonesia), 364 => Ok(Self::IranIslamicRepublic), 368 => Ok(Self::Iraq), 372 => Ok(Self::Ireland), 833 => Ok(Self::IsleOfMan), 376 => Ok(Self::Israel), 380 => Ok(Self::Italy), 388 => Ok(Self::Jamaica), 392 => Ok(Self::Japan), 832 => Ok(Self::Jersey), 400 => Ok(Self::Jordan), 398 => Ok(Self::Kazakhstan), 404 => Ok(Self::Kenya), 296 => Ok(Self::Kiribati), 408 => Ok(Self::KoreaDemocraticPeoplesRepublic), 410 => Ok(Self::KoreaRepublic), 414 => Ok(Self::Kuwait), 417 => Ok(Self::Kyrgyzstan), 418 => Ok(Self::LaoPeoplesDemocraticRepublic), 428 => Ok(Self::Latvia), 422 => Ok(Self::Lebanon), 426 => Ok(Self::Lesotho), 430 => Ok(Self::Liberia), 434 => Ok(Self::Libya), 438 => Ok(Self::Liechtenstein), 440 => Ok(Self::Lithuania), 442 => Ok(Self::Luxembourg), 446 => Ok(Self::Macao), 807 => Ok(Self::MacedoniaTheFormerYugoslavRepublic), 450 => Ok(Self::Madagascar), 454 => Ok(Self::Malawi), 458 => Ok(Self::Malaysia), 462 => Ok(Self::Maldives), 466 => Ok(Self::Mali), 470 => Ok(Self::Malta), 584 => Ok(Self::MarshallIslands), 474 => Ok(Self::Martinique), 478 => Ok(Self::Mauritania), 480 => Ok(Self::Mauritius), 175 => Ok(Self::Mayotte), 484 => Ok(Self::Mexico), 583 => Ok(Self::MicronesiaFederatedStates), 498 => Ok(Self::MoldovaRepublic), 492 => Ok(Self::Monaco), 496 => Ok(Self::Mongolia), 499 => Ok(Self::Montenegro), 500 => Ok(Self::Montserrat), 504 => Ok(Self::Morocco), 508 => Ok(Self::Mozambique), 104 => Ok(Self::Myanmar), 516 => Ok(Self::Namibia), 520 => Ok(Self::Nauru), 524 => Ok(Self::Nepal), 528 => Ok(Self::Netherlands), 540 => Ok(Self::NewCaledonia), 554 => Ok(Self::NewZealand), 558 => Ok(Self::Nicaragua), 562 => Ok(Self::Niger), 566 => Ok(Self::Nigeria), 570 => Ok(Self::Niue), 574 => Ok(Self::NorfolkIsland), 580 => Ok(Self::NorthernMarianaIslands), 578 => Ok(Self::Norway), 512 => Ok(Self::Oman), 586 => Ok(Self::Pakistan), 585 => Ok(Self::Palau), 275 => Ok(Self::PalestineState), 591 => Ok(Self::Panama), 598 => Ok(Self::PapuaNewGuinea), 600 => Ok(Self::Paraguay), 604 => Ok(Self::Peru), 608 => Ok(Self::Philippines), 612 => Ok(Self::Pitcairn), 616 => Ok(Self::Poland), 620 => Ok(Self::Portugal), 630 => Ok(Self::PuertoRico), 634 => Ok(Self::Qatar), 638 => Ok(Self::Reunion), 642 => Ok(Self::Romania), 643 => Ok(Self::RussianFederation), 646 => Ok(Self::Rwanda), 652 => Ok(Self::SaintBarthelemy), 654 => Ok(Self::SaintHelenaAscensionAndTristandaCunha), 659 => Ok(Self::SaintKittsAndNevis), 662 => Ok(Self::SaintLucia), 663 => Ok(Self::SaintMartinFrenchpart), 666 => Ok(Self::SaintPierreAndMiquelon), 670 => Ok(Self::SaintVincentAndTheGrenadines), 882 => Ok(Self::Samoa), 674 => Ok(Self::SanMarino), 678 => Ok(Self::SaoTomeAndPrincipe), 682 => Ok(Self::SaudiArabia), 686 => Ok(Self::Senegal), 688 => Ok(Self::Serbia), 690 => Ok(Self::Seychelles), 694 => Ok(Self::SierraLeone), 702 => Ok(Self::Singapore), 534 => Ok(Self::SintMaartenDutchpart), 703 => Ok(Self::Slovakia), 705 => Ok(Self::Slovenia), 90 => Ok(Self::SolomonIslands), 706 => Ok(Self::Somalia), 710 => Ok(Self::SouthAfrica), 239 => Ok(Self::SouthGeorgiaAndTheSouthSandwichIslands), 728 => Ok(Self::SouthSudan), 724 => Ok(Self::Spain), 144 => Ok(Self::SriLanka), 729 => Ok(Self::Sudan), 740 => Ok(Self::Suriname), 744 => Ok(Self::SvalbardAndJanMayen), 748 => Ok(Self::Swaziland), 752 => Ok(Self::Sweden), 756 => Ok(Self::Switzerland), 760 => Ok(Self::SyrianArabRepublic), 158 => Ok(Self::TaiwanProvinceOfChina), 762 => Ok(Self::Tajikistan), 834 => Ok(Self::TanzaniaUnitedRepublic), 764 => Ok(Self::Thailand), 626 => Ok(Self::TimorLeste), 768 => Ok(Self::Togo), 772 => Ok(Self::Tokelau), 776 => Ok(Self::Tonga), 780 => Ok(Self::TrinidadAndTobago), 788 => Ok(Self::Tunisia), 792 => Ok(Self::Turkey), 795 => Ok(Self::Turkmenistan), 796 => Ok(Self::TurksAndCaicosIslands), 798 => Ok(Self::Tuvalu), 800 => Ok(Self::Uganda), 804 => Ok(Self::Ukraine), 784 => Ok(Self::UnitedArabEmirates), 826 => Ok(Self::UnitedKingdomOfGreatBritainAndNorthernIreland), 840 => Ok(Self::UnitedStatesOfAmerica), 581 => Ok(Self::UnitedStatesMinorOutlyingIslands), 858 => Ok(Self::Uruguay), 860 => Ok(Self::Uzbekistan), 548 => Ok(Self::Vanuatu), 862 => Ok(Self::VenezuelaBolivarianRepublic), 704 => Ok(Self::Vietnam), 92 => Ok(Self::VirginIslandsBritish), 850 => Ok(Self::VirginIslandsUS), 876 => Ok(Self::WallisAndFutuna), 732 => Ok(Self::WesternSahara), 887 => Ok(Self::Yemen), 894 => Ok(Self::Zambia), 716 => Ok(Self::Zimbabwe), _ => Err(NumericCountryCodeParseError), } } pub const fn to_numeric(self) -> u32 { match self { Self::Afghanistan => 4, Self::AlandIslands => 248, Self::Albania => 8, Self::Algeria => 12, Self::AmericanSamoa => 16, Self::Andorra => 20, Self::Angola => 24, Self::Anguilla => 660, Self::Antarctica => 10, Self::AntiguaAndBarbuda => 28, Self::Argentina => 32, Self::Armenia => 51, Self::Aruba => 533, Self::Australia => 36, Self::Austria => 40, Self::Azerbaijan => 31, Self::Bahamas => 44, Self::Bahrain => 48, Self::Bangladesh => 50, Self::Barbados => 52, Self::Belarus => 112, Self::Belgium => 56, Self::Belize => 84, Self::Benin => 204, Self::Bermuda => 60, Self::Bhutan => 64, Self::BoliviaPlurinationalState => 68, Self::BonaireSintEustatiusAndSaba => 535, Self::BosniaAndHerzegovina => 70, Self::Botswana => 72, Self::BouvetIsland => 74, Self::Brazil => 76, Self::BritishIndianOceanTerritory => 86, Self::BruneiDarussalam => 96, Self::Bulgaria => 100, Self::BurkinaFaso => 854, Self::Burundi => 108, Self::CaboVerde => 132, Self::Cambodia => 116, Self::Cameroon => 120, Self::Canada => 124, Self::CaymanIslands => 136, Self::CentralAfricanRepublic => 140, Self::Chad => 148, Self::Chile => 152, Self::China => 156, Self::ChristmasIsland => 162, Self::CocosKeelingIslands => 166, Self::Colombia => 170, Self::Comoros => 174, Self::Congo => 178, Self::CongoDemocraticRepublic => 180, Self::CookIslands => 184, Self::CostaRica => 188, Self::CotedIvoire => 384, Self::Croatia => 191, Self::Cuba => 192, Self::Curacao => 531, Self::Cyprus => 196, Self::Czechia => 203, Self::Denmark => 208, Self::Djibouti => 262, Self::Dominica => 212, Self::DominicanRepublic => 214, Self::Ecuador => 218, Self::Egypt => 818, Self::ElSalvador => 222, Self::EquatorialGuinea => 226, Self::Eritrea => 232, Self::Estonia => 233, Self::Ethiopia => 231, Self::FalklandIslandsMalvinas => 238, Self::FaroeIslands => 234, Self::Fiji => 242, Self::Finland => 246, Self::France => 250, Self::FrenchGuiana => 254, Self::FrenchPolynesia => 258, Self::FrenchSouthernTerritories => 260, Self::Gabon => 266, Self::Gambia => 270, Self::Georgia => 268, Self::Germany => 276, Self::Ghana => 288, Self::Gibraltar => 292, Self::Greece => 300, Self::Greenland => 304, Self::Grenada => 308, Self::Guadeloupe => 312, Self::Guam => 316, Self::Guatemala => 320, Self::Guernsey => 831, Self::Guinea => 324, Self::GuineaBissau => 624, Self::Guyana => 328, Self::Haiti => 332, Self::HeardIslandAndMcDonaldIslands => 334, Self::HolySee => 336, Self::Honduras => 340, Self::HongKong => 344, Self::Hungary => 348, Self::Iceland => 352, Self::India => 356, Self::Indonesia => 360, Self::IranIslamicRepublic => 364, Self::Iraq => 368, Self::Ireland => 372, Self::IsleOfMan => 833, Self::Israel => 376, Self::Italy => 380, Self::Jamaica => 388, Self::Japan => 392, Self::Jersey => 832, Self::Jordan => 400, Self::Kazakhstan => 398, Self::Kenya => 404, Self::Kiribati => 296, Self::KoreaDemocraticPeoplesRepublic => 408, Self::KoreaRepublic => 410, Self::Kuwait => 414, Self::Kyrgyzstan => 417, Self::LaoPeoplesDemocraticRepublic => 418, Self::Latvia => 428, Self::Lebanon => 422, Self::Lesotho => 426, Self::Liberia => 430, Self::Libya => 434, Self::Liechtenstein => 438, Self::Lithuania => 440, Self::Luxembourg => 442, Self::Macao => 446, Self::MacedoniaTheFormerYugoslavRepublic => 807, Self::Madagascar => 450, Self::Malawi => 454, Self::Malaysia => 458, Self::Maldives => 462, Self::Mali => 466, Self::Malta => 470, Self::MarshallIslands => 584, Self::Martinique => 474, Self::Mauritania => 478, Self::Mauritius => 480, Self::Mayotte => 175, Self::Mexico => 484, Self::MicronesiaFederatedStates => 583, Self::MoldovaRepublic => 498, Self::Monaco => 492, Self::Mongolia => 496, Self::Montenegro => 499, Self::Montserrat => 500, Self::Morocco => 504, Self::Mozambique => 508, Self::Myanmar => 104, Self::Namibia => 516, Self::Nauru => 520, Self::Nepal => 524, Self::Netherlands => 528, Self::NewCaledonia => 540, Self::NewZealand => 554, Self::Nicaragua => 558, Self::Niger => 562, Self::Nigeria => 566, Self::Niue => 570, Self::NorfolkIsland => 574, Self::NorthernMarianaIslands => 580, Self::Norway => 578, Self::Oman => 512, Self::Pakistan => 586, Self::Palau => 585, Self::PalestineState => 275, Self::Panama => 591, Self::PapuaNewGuinea => 598, Self::Paraguay => 600, Self::Peru => 604, Self::Philippines => 608, Self::Pitcairn => 612, Self::Poland => 616, Self::Portugal => 620, Self::PuertoRico => 630, Self::Qatar => 634, Self::Reunion => 638, Self::Romania => 642, Self::RussianFederation => 643, Self::Rwanda => 646, Self::SaintBarthelemy => 652, Self::SaintHelenaAscensionAndTristandaCunha => 654, Self::SaintKittsAndNevis => 659, Self::SaintLucia => 662, Self::SaintMartinFrenchpart => 663, Self::SaintPierreAndMiquelon => 666, Self::SaintVincentAndTheGrenadines => 670, Self::Samoa => 882, Self::SanMarino => 674, Self::SaoTomeAndPrincipe => 678, Self::SaudiArabia => 682, Self::Senegal => 686, Self::Serbia => 688, Self::Seychelles => 690, Self::SierraLeone => 694, Self::Singapore => 702, Self::SintMaartenDutchpart => 534, Self::Slovakia => 703, Self::Slovenia => 705, Self::SolomonIslands => 90, Self::Somalia => 706, Self::SouthAfrica => 710, Self::SouthGeorgiaAndTheSouthSandwichIslands => 239, Self::SouthSudan => 728, Self::Spain => 724, Self::SriLanka => 144, Self::Sudan => 729, Self::Suriname => 740, Self::SvalbardAndJanMayen => 744, Self::Swaziland => 748, Self::Sweden => 752, Self::Switzerland => 756, Self::SyrianArabRepublic => 760, Self::TaiwanProvinceOfChina => 158, Self::Tajikistan => 762, Self::TanzaniaUnitedRepublic => 834, Self::Thailand => 764, Self::TimorLeste => 626, Self::Togo => 768, Self::Tokelau => 772, Self::Tonga => 776, Self::TrinidadAndTobago => 780, Self::Tunisia => 788, Self::Turkey => 792, Self::Turkmenistan => 795, Self::TurksAndCaicosIslands => 796, Self::Tuvalu => 798, Self::Uganda => 800, Self::Ukraine => 804, Self::UnitedArabEmirates => 784, Self::UnitedKingdomOfGreatBritainAndNorthernIreland => 826, Self::UnitedStatesOfAmerica => 840, Self::UnitedStatesMinorOutlyingIslands => 581, Self::Uruguay => 858, Self::Uzbekistan => 860, Self::Vanuatu => 548, Self::VenezuelaBolivarianRepublic => 862, Self::Vietnam => 704, Self::VirginIslandsBritish => 92, Self::VirginIslandsUS => 850, Self::WallisAndFutuna => 876, Self::WesternSahara => 732, Self::Yemen => 887, Self::Zambia => 894, Self::Zimbabwe => 716, } } } impl From<PaymentMethodType> for PaymentMethod { fn from(value: PaymentMethodType) -> Self { match value { PaymentMethodType::Ach => Self::BankDebit, PaymentMethodType::Affirm => Self::PayLater, PaymentMethodType::AfterpayClearpay => Self::PayLater, PaymentMethodType::AliPay => Self::Wallet, PaymentMethodType::AliPayHk => Self::Wallet, PaymentMethodType::Alma => Self::PayLater, PaymentMethodType::AmazonPay => Self::Wallet, PaymentMethodType::Paysera => Self::Wallet, PaymentMethodType::Skrill => Self::Wallet, PaymentMethodType::ApplePay => Self::Wallet, PaymentMethodType::Bacs => Self::BankDebit, PaymentMethodType::BancontactCard => Self::BankRedirect, PaymentMethodType::BcaBankTransfer => Self::BankTransfer, PaymentMethodType::Becs => Self::BankDebit, PaymentMethodType::BniVa => Self::BankTransfer, PaymentMethodType::Breadpay => Self::PayLater, PaymentMethodType::BriVa => Self::BankTransfer, PaymentMethodType::Benefit => Self::CardRedirect, PaymentMethodType::Bizum => Self::BankRedirect, PaymentMethodType::Blik => Self::BankRedirect, PaymentMethodType::Bluecode => Self::Wallet, PaymentMethodType::Alfamart => Self::Voucher, PaymentMethodType::CardRedirect => Self::CardRedirect, PaymentMethodType::CimbVa => Self::BankTransfer, PaymentMethodType::ClassicReward => Self::Reward, PaymentMethodType::Credit => Self::Card, #[cfg(feature = "v2")] PaymentMethodType::Card => Self::Card, PaymentMethodType::CryptoCurrency => Self::Crypto, PaymentMethodType::Dana => Self::Wallet, PaymentMethodType::DanamonVa => Self::BankTransfer, PaymentMethodType::Debit => Self::Card, PaymentMethodType::Flexiti => Self::PayLater, PaymentMethodType::Fps => Self::RealTimePayment, PaymentMethodType::DuitNow => Self::RealTimePayment, PaymentMethodType::Eft => Self::BankRedirect, PaymentMethodType::Eps => Self::BankRedirect, PaymentMethodType::Evoucher => Self::Reward, PaymentMethodType::Giropay => Self::BankRedirect, PaymentMethodType::GooglePay => Self::Wallet, PaymentMethodType::GoPay => Self::Wallet, PaymentMethodType::Gcash => Self::Wallet, PaymentMethodType::Mifinity => Self::Wallet, PaymentMethodType::Ideal => Self::BankRedirect, PaymentMethodType::Klarna => Self::PayLater, PaymentMethodType::KakaoPay => Self::Wallet, PaymentMethodType::Knet => Self::CardRedirect, PaymentMethodType::LocalBankRedirect => Self::BankRedirect, PaymentMethodType::MbWay => Self::Wallet, PaymentMethodType::MobilePay => Self::Wallet, PaymentMethodType::Momo => Self::Wallet, PaymentMethodType::MomoAtm => Self::CardRedirect, PaymentMethodType::Multibanco => Self::BankTransfer, PaymentMethodType::MandiriVa => Self::BankTransfer, PaymentMethodType::Interac => Self::BankRedirect, PaymentMethodType::InstantBankTransfer => Self::BankTransfer, PaymentMethodType::InstantBankTransferFinland => Self::BankTransfer, PaymentMethodType::InstantBankTransferPoland => Self::BankTransfer, PaymentMethodType::Indomaret => Self::Voucher, PaymentMethodType::OnlineBankingCzechRepublic => Self::BankRedirect, PaymentMethodType::OnlineBankingFinland => Self::BankRedirect, PaymentMethodType::OnlineBankingFpx => Self::BankRedirect, PaymentMethodType::OnlineBankingThailand => Self::BankRedirect, PaymentMethodType::OnlineBankingPoland => Self::BankRedirect, PaymentMethodType::OnlineBankingSlovakia => Self::BankRedirect, PaymentMethodType::Paze => Self::Wallet, PaymentMethodType::PermataBankTransfer => Self::BankTransfer, PaymentMethodType::Pix => Self::BankTransfer, PaymentMethodType::Pse => Self::BankTransfer, PaymentMethodType::LocalBankTransfer => Self::BankTransfer, PaymentMethodType::PayBright => Self::PayLater, PaymentMethodType::Paypal => Self::Wallet, PaymentMethodType::PaySafeCard => Self::GiftCard, PaymentMethodType::Przelewy24 => Self::BankRedirect, PaymentMethodType::PromptPay => Self::RealTimePayment, PaymentMethodType::SamsungPay => Self::Wallet, PaymentMethodType::Sepa => Self::BankDebit, PaymentMethodType::SepaGuarenteedDebit => Self::BankDebit, PaymentMethodType::SepaBankTransfer => Self::BankTransfer, PaymentMethodType::Sofort => Self::BankRedirect, PaymentMethodType::Swish => Self::BankRedirect, PaymentMethodType::Trustly => Self::BankRedirect, PaymentMethodType::Twint => Self::Wallet, PaymentMethodType::UpiCollect => Self::Upi, PaymentMethodType::UpiIntent => Self::Upi, PaymentMethodType::UpiQr => Self::Upi, PaymentMethodType::Vipps => Self::Wallet, PaymentMethodType::Venmo => Self::Wallet, PaymentMethodType::VietQr => Self::RealTimePayment, PaymentMethodType::Walley => Self::PayLater, PaymentMethodType::WeChatPay => Self::Wallet, PaymentMethodType::TouchNGo => Self::Wallet, PaymentMethodType::Atome => Self::PayLater, PaymentMethodType::Boleto => Self::Voucher, PaymentMethodType::Efecty => Self::Voucher, PaymentMethodType::PagoEfectivo => Self::Voucher, PaymentMethodType::RedCompra => Self::Voucher, PaymentMethodType::RedPagos => Self::Voucher, PaymentMethodType::Cashapp => Self::Wallet, PaymentMethodType::BhnCardNetwork => Self::GiftCard, PaymentMethodType::Givex => Self::GiftCard, PaymentMethodType::Oxxo => Self::Voucher, PaymentMethodType::OpenBankingUk => Self::BankRedirect, PaymentMethodType::SevenEleven => Self::Voucher, PaymentMethodType::Lawson => Self::Voucher, PaymentMethodType::MiniStop => Self::Voucher, PaymentMethodType::FamilyMart => Self::Voucher, PaymentMethodType::Seicomart => Self::Voucher, PaymentMethodType::PayEasy => Self::Voucher, PaymentMethodType::OpenBankingPIS => Self::OpenBanking, PaymentMethodType::DirectCarrierBilling => Self::MobilePayment, PaymentMethodType::RevolutPay => Self::Wallet, PaymentMethodType::IndonesianBankTransfer => Self::BankTransfer, } } } #[derive(Debug)] pub struct NumericCountryCodeParseError; #[allow(dead_code)] mod custom_serde { use super::*; pub mod alpha2_country_code { use std::fmt; use serde::de::Visitor; use super::*; // `serde::Serialize` implementation needs the function to accept `&Country` #[allow(clippy::trivially_copy_pass_by_ref)] pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { code.to_alpha2().serialize(serializer) } struct FieldVisitor; impl Visitor<'_> for FieldVisitor { type Value = CountryAlpha2; fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { formatter.write_str("CountryAlpha2 as a string") } } pub fn deserialize<'a, D>(deserializer: D) -> Result<Country, D::Error> where D: serde::Deserializer<'a>, { CountryAlpha2::deserialize(deserializer).map(Country::from_alpha2) } } pub mod alpha3_country_code { use std::fmt; use serde::de::Visitor; use super::*; // `serde::Serialize` implementation needs the function to accept `&Country` #[allow(clippy::trivially_copy_pass_by_ref)] pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { code.to_alpha3().serialize(serializer) } struct FieldVisitor; impl Visitor<'_> for FieldVisitor { type Value = CountryAlpha3; fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { formatter.write_str("CountryAlpha3 as a string") } } pub fn deserialize<'a, D>(deserializer: D) -> Result<Country, D::Error> where D: serde::Deserializer<'a>, { CountryAlpha3::deserialize(deserializer).map(Country::from_alpha3) } } pub mod numeric_country_code { use std::fmt; use serde::de::Visitor; use super::*; // `serde::Serialize` implementation needs the function to accept `&Country` #[allow(clippy::trivially_copy_pass_by_ref)] pub fn serialize<S>(code: &Country, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { code.to_numeric().serialize(serializer) } struct FieldVisitor; impl Visitor<'_> for FieldVisitor { type Value = u32; fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { formatter.write_str("Numeric country code passed as an u32") } } pub fn deserialize<'a, D>(deserializer: D) -> Result<Country, D::Error> where D: serde::Deserializer<'a>, { u32::deserialize(deserializer) .and_then(|value| Country::from_numeric(value).map_err(serde::de::Error::custom)) } } } impl From<Option<bool>> for super::External3dsAuthenticationRequest { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Enable, _ => Self::Skip, } } } /// Get the boolean value of the `External3dsAuthenticationRequest`. impl super::External3dsAuthenticationRequest { pub fn as_bool(&self) -> bool { match self { Self::Enable => true, Self::Skip => false, } } } impl super::EnablePaymentLinkRequest { pub fn as_bool(&self) -> bool { match self { Self::Enable => true, Self::Skip => false, } } } impl From<Option<bool>> for super::EnablePaymentLinkRequest { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Enable, _ => Self::Skip, } } } impl From<Option<bool>> for super::MitExemptionRequest { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Apply, _ => Self::Skip, } } } impl super::MitExemptionRequest { pub fn as_bool(&self) -> bool { match self { Self::Apply => true, Self::Skip => false, } } } impl From<Option<bool>> for super::PresenceOfCustomerDuringPayment { fn from(value: Option<bool>) -> Self { match value { Some(false) => Self::Absent, _ => Self::Present, } } } impl super::PresenceOfCustomerDuringPayment { pub fn as_bool(&self) -> bool { match self { Self::Present => true, Self::Absent => false, } } } impl From<AttemptStatus> for IntentStatus { fn from(s: AttemptStatus) -> Self { match s { AttemptStatus::Charged | AttemptStatus::AutoRefunded => Self::Succeeded, AttemptStatus::ConfirmationAwaited => Self::RequiresConfirmation, AttemptStatus::PaymentMethodAwaited => Self::RequiresPaymentMethod, AttemptStatus::Authorized => Self::RequiresCapture, AttemptStatus::AuthenticationPending | AttemptStatus::DeviceDataCollectionPending => { Self::RequiresCustomerAction } AttemptStatus::Unresolved => Self::RequiresMerchantAction, AttemptStatus::IntegrityFailure => Self::Conflicted, AttemptStatus::PartialCharged => Self::PartiallyCaptured, AttemptStatus::PartialChargedAndChargeable => Self::PartiallyCapturedAndCapturable, AttemptStatus::Started | AttemptStatus::AuthenticationSuccessful | AttemptStatus::Authorizing | AttemptStatus::CodInitiated | AttemptStatus::VoidInitiated | AttemptStatus::CaptureInitiated | AttemptStatus::Pending => Self::Processing, AttemptStatus::AuthenticationFailed | AttemptStatus::AuthorizationFailed | AttemptStatus::VoidFailed | AttemptStatus::RouterDeclined | AttemptStatus::CaptureFailed | AttemptStatus::Failure => Self::Failed, AttemptStatus::Voided => Self::Cancelled, AttemptStatus::VoidedPostCharge => Self::CancelledPostCapture, AttemptStatus::Expired => Self::Expired, AttemptStatus::PartiallyAuthorized => Self::PartiallyAuthorizedAndRequiresCapture, } } } impl From<IntentStatus> for Option<EventType> { fn from(value: IntentStatus) -> Self { match value { IntentStatus::Succeeded => Some(EventType::PaymentSucceeded), IntentStatus::Failed => Some(EventType::PaymentFailed), IntentStatus::Processing => Some(EventType::PaymentProcessing), IntentStatus::RequiresMerchantAction | IntentStatus::RequiresCustomerAction | IntentStatus::Conflicted => Some(EventType::ActionRequired), IntentStatus::Cancelled => Some(EventType::PaymentCancelled), IntentStatus::CancelledPostCapture => Some(EventType::PaymentCancelledPostCapture), IntentStatus::Expired => Some(EventType::PaymentExpired), IntentStatus::PartiallyCaptured | IntentStatus::PartiallyCapturedAndCapturable => { Some(EventType::PaymentCaptured) } IntentStatus::RequiresCapture => Some(EventType::PaymentAuthorized), IntentStatus::RequiresPaymentMethod | IntentStatus::RequiresConfirmation => None, IntentStatus::PartiallyAuthorizedAndRequiresCapture => { Some(EventType::PaymentPartiallyAuthorized) } } } } impl From<RefundStatus> for Option<EventType> { fn from(value: RefundStatus) -> Self { match value { RefundStatus::Success => Some(EventType::RefundSucceeded), RefundStatus::Failure => Some(EventType::RefundFailed), RefundStatus::ManualReview | RefundStatus::Pending | RefundStatus::TransactionFailure => None, } } } #[cfg(feature = "payouts")] impl From<PayoutStatus> for Option<EventType> { fn from(value: PayoutStatus) -> Self { match value { PayoutStatus::Success => Some(EventType::PayoutSuccess), PayoutStatus::Failed => Some(EventType::PayoutFailed), PayoutStatus::Cancelled => Some(EventType::PayoutCancelled), PayoutStatus::Initiated => Some(EventType::PayoutInitiated), PayoutStatus::Expired => Some(EventType::PayoutExpired), PayoutStatus::Reversed => Some(EventType::PayoutReversed), PayoutStatus::Ineligible | PayoutStatus::Pending | PayoutStatus::RequiresCreation | PayoutStatus::RequiresFulfillment | PayoutStatus::RequiresPayoutMethodData | PayoutStatus::RequiresVendorAccountCreation | PayoutStatus::RequiresConfirmation => None, } } } impl From<DisputeStatus> for EventType { fn from(value: DisputeStatus) -> Self { match value { DisputeStatus::DisputeOpened => Self::DisputeOpened, DisputeStatus::DisputeExpired => Self::DisputeExpired, DisputeStatus::DisputeAccepted => Self::DisputeAccepted, DisputeStatus::DisputeCancelled => Self::DisputeCancelled, DisputeStatus::DisputeChallenged => Self::DisputeChallenged, DisputeStatus::DisputeWon => Self::DisputeWon, DisputeStatus::DisputeLost => Self::DisputeLost, } } } impl From<MandateStatus> for Option<EventType> { fn from(value: MandateStatus) -> Self { match value { MandateStatus::Active => Some(EventType::MandateActive), MandateStatus::Revoked => Some(EventType::MandateRevoked), MandateStatus::Inactive | MandateStatus::Pending => None, } } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[derive(serde::Serialize)] struct Alpha2Request { #[serde(with = "custom_serde::alpha2_country_code")] pub country: Country, } #[derive(serde::Serialize)] struct Alpha3Request { #[serde(with = "custom_serde::alpha3_country_code")] pub country: Country, } #[derive(serde::Serialize)] struct NumericRequest { #[serde(with = "custom_serde::numeric_country_code")] pub country: Country, } #[derive(serde::Serialize, serde::Deserialize)] struct HyperswitchRequestAlpha2 { #[serde(with = "custom_serde::alpha2_country_code")] pub country: Country, } #[derive(serde::Serialize, serde::Deserialize)] struct HyperswitchRequestAlpha3 { #[serde(with = "custom_serde::alpha3_country_code")] pub country: Country, } #[derive(serde::Serialize, serde::Deserialize, Debug)] struct HyperswitchRequestNumeric { #[serde(with = "custom_serde::numeric_country_code")] pub country: Country, } #[test] fn test_serialize_alpha2() { let x_request = Alpha2Request { country: Country::India, }; let serialized_country = serde_json::to_string(&x_request).unwrap(); assert_eq!(serialized_country, r#"{"country":"IN"}"#); let x_request = Alpha2Request { country: Country::MacedoniaTheFormerYugoslavRepublic, }; let serialized_country = serde_json::to_string(&x_request).unwrap(); assert_eq!(serialized_country, r#"{"country":"MK"}"#); let x_request = Alpha2Request { country: Country::FrenchSouthernTerritories, }; let serialized_country = serde_json::to_string(&x_request).unwrap(); assert_eq!(serialized_country, r#"{"country":"TF"}"#); } #[test] fn test_serialize_alpha3() { let y_request = Alpha3Request { country: Country::India, }; let serialized_country = serde_json::to_string(&y_request).unwrap(); assert_eq!(serialized_country, r#"{"country":"IND"}"#); let y_request = Alpha3Request { country: Country::HeardIslandAndMcDonaldIslands, }; let serialized_country = serde_json::to_string(&y_request).unwrap(); assert_eq!(serialized_country, r#"{"country":"HMD"}"#); let y_request = Alpha3Request { country: Country::Argentina, }; let serialized_country = serde_json::to_string(&y_request).unwrap(); assert_eq!(serialized_country, r#"{"country":"ARG"}"#); } #[test] fn test_serialize_numeric() { let y_request = NumericRequest { country: Country::India, }; let serialized_country = serde_json::to_string(&y_request).unwrap(); assert_eq!(serialized_country, r#"{"country":356}"#); let y_request = NumericRequest { country: Country::Bermuda, }; let serialized_country = serde_json::to_string(&y_request).unwrap(); assert_eq!(serialized_country, r#"{"country":60}"#); let y_request = NumericRequest { country: Country::GuineaBissau, }; let serialized_country = serde_json::to_string(&y_request).unwrap(); assert_eq!(serialized_country, r#"{"country":624}"#); } #[test] fn test_deserialize_alpha2() { let request_str = r#"{"country":"IN"}"#; let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap(); assert_eq!(request.country, Country::India); let request_str = r#"{"country":"GR"}"#; let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap(); assert_eq!(request.country, Country::Greece); let request_str = r#"{"country":"IQ"}"#; let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap(); assert_eq!(request.country, Country::Iraq); } #[test] fn test_deserialize_alpha3() { let request_str = r#"{"country":"IND"}"#; let request = serde_json::from_str::<HyperswitchRequestAlpha3>(request_str).unwrap(); assert_eq!(request.country, Country::India); let request_str = r#"{"country":"LVA"}"#; let request = serde_json::from_str::<HyperswitchRequestAlpha3>(request_str).unwrap(); assert_eq!(request.country, Country::Latvia); let request_str = r#"{"country":"PNG"}"#; let request = serde_json::from_str::<HyperswitchRequestAlpha3>(request_str).unwrap(); assert_eq!(request.country, Country::PapuaNewGuinea); } #[test] fn test_deserialize_numeric() { let request_str = r#"{"country":356}"#; let request = serde_json::from_str::<HyperswitchRequestNumeric>(request_str).unwrap(); assert_eq!(request.country, Country::India); let request_str = r#"{"country":239}"#; let request = serde_json::from_str::<HyperswitchRequestNumeric>(request_str).unwrap(); assert_eq!( request.country, Country::SouthGeorgiaAndTheSouthSandwichIslands ); let request_str = r#"{"country":826}"#; let request = serde_json::from_str::<HyperswitchRequestNumeric>(request_str).unwrap(); assert_eq!( request.country, Country::UnitedKingdomOfGreatBritainAndNorthernIreland ); } #[test] fn test_deserialize_and_serialize() { // Deserialize the country as alpha2 code // Serialize the country as alpha3 code let request_str = r#"{"country":"IN"}"#; let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap(); let alpha3_request = Alpha3Request { country: request.country, }; let response = serde_json::to_string::<Alpha3Request>(&alpha3_request).unwrap(); assert_eq!(response, r#"{"country":"IND"}"#) } #[test] fn test_serialize_and_deserialize() { let request_str = r#"{"country":"AX"}"#; let request = serde_json::from_str::<HyperswitchRequestAlpha2>(request_str).unwrap(); let alpha3_request = Alpha3Request { country: request.country, }; let response = serde_json::to_string::<Alpha3Request>(&alpha3_request).unwrap(); assert_eq!(response, r#"{"country":"ALA"}"#); let result = serde_json::from_str::<HyperswitchRequestAlpha3>(response.as_str()).unwrap(); assert_eq!(result.country, Country::AlandIslands); } #[test] fn test_deserialize_invalid_country_code() { let request_str = r#"{"country": 123456}"#; let result: Result<HyperswitchRequestNumeric, _> = serde_json::from_str::<HyperswitchRequestNumeric>(request_str); assert!(result.is_err()); } }
crates/common_enums/src/transformers.rs
common_enums::src::transformers
28,538
true
// File: crates/common_enums/src/lib.rs // Module: common_enums::src::lib pub mod connector_enums; pub mod enums; pub mod transformers; pub use enums::*; pub use transformers::*;
crates/common_enums/src/lib.rs
common_enums::src::lib
44
true
// File: crates/common_enums/src/enums.rs // Module: common_enums::src::enums mod accounts; mod payments; mod ui; use std::{ collections::HashSet, num::{ParseFloatError, TryFromIntError}, }; pub use accounts::{ MerchantAccountRequestType, MerchantAccountType, MerchantProductType, OrganizationType, }; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; use utoipa::ToSchema; pub use super::connector_enums::{InvoiceStatus, RoutableConnectors}; #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbRoutingApproach as RoutingApproach, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbTokenizationFlag as TokenizationFlag, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub type ApplicationResult<T> = Result<T, ApplicationError>; #[derive(Debug, thiserror::Error)] pub enum ApplicationError { #[error("Application configuration error")] ConfigurationError, #[error("Invalid configuration value provided: {0}")] InvalidConfigurationValueError(String), #[error("Metrics error")] MetricsError, #[error("I/O: {0}")] IoError(std::io::Error), #[error("Error while constructing api client: {0}")] ApiClientError(ApiClientError), } #[derive(Debug, thiserror::Error, PartialEq, Clone)] pub enum ApiClientError { #[error("Header map construction failed")] HeaderMapConstructionFailed, #[error("Invalid proxy configuration")] InvalidProxyConfiguration, #[error("Client construction failed")] ClientConstructionFailed, #[error("Certificate decode failed")] CertificateDecodeFailed, #[error("Request body serialization failed")] BodySerializationFailed, #[error("Unexpected state reached/Invariants conflicted")] UnexpectedState, #[error("Failed to parse URL")] UrlParsingFailed, #[error("URL encoding of request payload failed")] UrlEncodingFailed, #[error("Failed to send request to connector {0}")] RequestNotSent(String), #[error("Failed to decode response")] ResponseDecodingFailed, #[error("Server responded with Request Timeout")] RequestTimeoutReceived, #[error("connection closed before a message could complete")] ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, #[error("Server responded with Bad Gateway")] BadGatewayReceived, #[error("Server responded with Service Unavailable")] ServiceUnavailableReceived, #[error("Server responded with Gateway Timeout")] GatewayTimeoutReceived, #[error("Server responded with unexpected response")] UnexpectedServerResponse, } impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } pub fn is_connection_closed_before_message_could_complete(&self) -> bool { self == &Self::ConnectionClosedIncompleteMessage } } impl From<std::io::Error> for ApplicationError { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } /// The status of the attempt #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AttemptStatus { Started, AuthenticationFailed, RouterDeclined, AuthenticationPending, AuthenticationSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CodInitiated, Voided, VoidedPostCharge, VoidInitiated, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, PartiallyAuthorized, PartialChargedAndChargeable, Unresolved, #[default] Pending, Failure, PaymentMethodAwaited, ConfirmationAwaited, DeviceDataCollectionPending, IntegrityFailure, Expired, } impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { Self::RouterDeclined | Self::Charged | Self::AutoRefunded | Self::Voided | Self::VoidedPostCharge | Self::VoidFailed | Self::CaptureFailed | Self::Failure | Self::PartialCharged | Self::Expired => true, Self::Started | Self::AuthenticationFailed | Self::AuthenticationPending | Self::AuthenticationSuccessful | Self::Authorized | Self::PartiallyAuthorized | Self::AuthorizationFailed | Self::Authorizing | Self::CodInitiated | Self::VoidInitiated | Self::CaptureInitiated | Self::PartialChargedAndChargeable | Self::Unresolved | Self::Pending | Self::PaymentMethodAwaited | Self::ConfirmationAwaited | Self::DeviceDataCollectionPending | Self::IntegrityFailure => false, } } pub fn is_success(self) -> bool { matches!(self, Self::Charged | Self::PartialCharged) } } #[derive( Clone, Copy, Debug, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ApplePayPaymentMethodType { Debit, Credit, Prepaid, Store, } /// Indicates the method by which a card is discovered during a payment #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardDiscovery { #[default] Manual, SavedCard, ClickToPay, } #[derive( Clone, Copy, Debug, Default, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RevenueRecoveryAlgorithmType { #[default] Monitoring, Smart, Cascading, } #[derive( Default, Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GsmDecision { Retry, #[default] DoDefault, } #[derive( Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "text")] pub enum GsmFeature { Retry, } /// Specifies the type of cardholder authentication to be applied for a payment. /// /// - `ThreeDs`: Requests 3D Secure (3DS) authentication. If the card is enrolled, 3DS authentication will be activated, potentially shifting chargeback liability to the issuer. /// - `NoThreeDs`: Indicates that 3D Secure authentication should not be performed. The liability for chargebacks typically remains with the merchant. This is often the default if not specified. /// /// Note: The actual authentication behavior can also be influenced by merchant configuration and specific connector defaults. Some connectors might still enforce 3DS or bypass it regardless of this parameter. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationType { /// If the card is enrolled for 3DS authentication, the 3DS based authentication will be activated. The liability of chargeback shift to the issuer ThreeDs, /// 3DS based authentication will not be activated. The liability of chargeback stays with the merchant. #[default] NoThreeDs, } /// The status of the capture #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckStatus { Fraud, ManualReview, #[default] Pending, Legit, TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureStatus { // Capture request initiated #[default] Started, // Capture request was successful Charged, // Capture is pending at connector side Pending, // Capture request failed Failed, } #[derive( Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthorizationStatus { Success, Failure, // Processing state is before calling connector #[default] Processing, // Requires merchant action Unresolved, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentResourceUpdateStatus { Success, Failure, } impl PaymentResourceUpdateStatus { pub fn is_success(&self) -> bool { matches!(self, Self::Success) } } #[derive( Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BlocklistDataKind { PaymentMethod, CardBin, ExtendedCardBin, } /// Specifies how the payment is captured. /// - `automatic`: Funds are captured immediately after successful authorization. This is the default behavior if the field is omitted. /// - `manual`: Funds are authorized but not captured. A separate request to the `/payments/{payment_id}/capture` endpoint is required to capture the funds. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { /// Post the payment authorization, the capture will be executed on the full amount immediately. #[default] Automatic, /// The capture will happen only if the merchant triggers a Capture API request. Allows for a single capture of the authorized amount. Manual, /// The capture will happen only if the merchant triggers a Capture API request. Allows for multiple partial captures up to the authorized amount. ManualMultiple, /// The capture can be scheduled to automatically get triggered at a specific date & time. Scheduled, /// Handles separate auth and capture sequentially; effectively the same as `Automatic` for most connectors. SequentialAutomatic, } /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorType { /// PayFacs, Acquirers, Gateways, BNPL etc PaymentProcessor, /// Fraud, Currency Conversion, Crypto etc PaymentVas, /// Accounting, Billing, Invoicing, Tax etc FinOperations, /// Inventory, ERP, CRM, KYC etc FizOperations, /// Payment Networks like Visa, MasterCard etc Networks, /// All types of banks including corporate / commercial / personal / neo banks BankingEntities, /// All types of non-banking financial institutions including Insurance, Credit / Lending etc NonBankingFinance, /// Acquirers, Gateways etc PayoutProcessor, /// PaymentMethods Auth Services PaymentMethodAuth, /// 3DS Authentication Service Providers AuthenticationProcessor, /// Tax Calculation Processor TaxProcessor, /// Represents billing processors that handle subscription management, invoicing, /// and recurring payments. Examples include Chargebee, Recurly, and Stripe Billing. BillingProcessor, /// Represents vaulting processors that handle the storage and management of payment method data VaultProcessor, } #[derive(Debug, Eq, PartialEq)] pub enum PaymentAction { PSync, CompleteAuthorize, PaymentAuthenticateCompleteAuthorize, } #[derive(Clone, PartialEq)] pub enum CallConnectorAction { Trigger, Avoid, StatusUpdate { status: AttemptStatus, error_code: Option<String>, error_message: Option<String>, }, HandleResponse(Vec<u8>), UCSHandleResponse(Vec<u8>), } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[serde(rename_all = "UPPERCASE")] pub enum DocumentKind { Cnpj, Cpf, } /// The three-letter ISO 4217 currency code (e.g., "USD", "EUR") for the payment amount. This field is mandatory for creating a payment. #[allow(clippy::upper_case_acronyms)] #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum Currency { AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLE, SLL, SOS, SRD, SSP, STD, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, #[default] USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL, } impl Currency { /// Convert the amount to its base denomination based on Currency and return String pub fn to_currency_base_unit(self, amount: i64) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; Ok(format!("{amount_f64:.2}")) } /// Convert the amount to its base denomination based on Currency and return f64 pub fn to_currency_base_unit_asf64(self, amount: i64) -> Result<f64, TryFromIntError> { let amount_f64: f64 = u32::try_from(amount)?.into(); let amount = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 / 1000.00 } else { amount_f64 / 100.00 }; Ok(amount) } ///Convert the higher decimal amount to its base absolute units pub fn to_currency_lower_unit(self, amount: String) -> Result<String, ParseFloatError> { let amount_f64 = amount.parse::<f64>()?; let amount_string = if self.is_zero_decimal_currency() { amount_f64 } else if self.is_three_decimal_currency() { amount_f64 * 1000.00 } else { amount_f64 * 100.00 }; Ok(amount_string.to_string()) } /// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ pub fn to_currency_base_unit_with_zero_decimal_check( self, amount: i64, ) -> Result<String, TryFromIntError> { let amount_f64 = self.to_currency_base_unit_asf64(amount)?; if self.is_zero_decimal_currency() { Ok(amount_f64.to_string()) } else { Ok(format!("{amount_f64:.2}")) } } pub fn iso_4217(self) -> &'static str { match self { Self::AED => "784", Self::AFN => "971", Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", Self::BND => "096", Self::BOB => "068", Self::BRL => "986", Self::BSD => "044", Self::BTN => "064", Self::BWP => "072", Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", Self::DOP => "214", Self::DZD => "012", Self::EGP => "818", Self::ERN => "232", Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", Self::FKP => "238", Self::GBP => "826", Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", Self::GNF => "324", Self::GTQ => "320", Self::GYD => "328", Self::HKD => "344", Self::HNL => "340", Self::HTG => "332", Self::HUF => "348", Self::HRK => "191", Self::IDR => "360", Self::ILS => "376", Self::INR => "356", Self::IQD => "368", Self::IRR => "364", Self::ISK => "352", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", Self::KES => "404", Self::KGS => "417", Self::KHR => "116", Self::KMF => "174", Self::KPW => "408", Self::KRW => "410", Self::KWD => "414", Self::KYD => "136", Self::KZT => "398", Self::LAK => "418", Self::LBP => "422", Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", Self::MKD => "807", Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", Self::NOK => "578", Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", Self::PKR => "586", Self::PLN => "985", Self::PYG => "600", Self::QAR => "634", Self::RON => "946", Self::CNY => "156", Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", Self::SBD => "090", Self::SCR => "690", Self::SDG => "938", Self::SEK => "752", Self::SGD => "702", Self::SHP => "654", Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", Self::SZL => "748", Self::THB => "764", Self::TJS => "972", Self::TMT => "934", Self::TND => "788", Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", Self::VES => "928", Self::VND => "704", Self::VUV => "548", Self::WST => "882", Self::XAF => "950", Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", Self::ZMW => "967", Self::ZWL => "932", } } pub fn is_zero_decimal_currency(self) -> bool { match self { Self::BIF | Self::CLP | Self::DJF | Self::GNF | Self::IRR | Self::JPY | Self::KMF | Self::KRW | Self::MGA | Self::PYG | Self::RWF | Self::UGX | Self::VND | Self::VUV | Self::XAF | Self::XOF | Self::XPF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::ANG | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::ISK | Self::JMD | Self::JOD | Self::KES | Self::KGS | Self::KHR | Self::KPW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::WST | Self::XCD | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { true } Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IRR | Self::ISK | Self::JMD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn is_four_decimal_currency(self) -> bool { match self { Self::CLF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::IRR | Self::ISK | Self::JMD | Self::JOD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } } pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 } else if self.is_four_decimal_currency() { 4 } else { 2 } } } #[derive( Clone, Copy, Debug, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventClass { Payments, Refunds, Disputes, Mandates, #[cfg(feature = "payouts")] Payouts, } impl EventClass { #[inline] pub fn event_types(self) -> HashSet<EventType> { match self { Self::Payments => HashSet::from([ EventType::PaymentSucceeded, EventType::PaymentFailed, EventType::PaymentProcessing, EventType::PaymentCancelled, EventType::PaymentCancelledPostCapture, EventType::PaymentAuthorized, EventType::PaymentCaptured, EventType::PaymentExpired, EventType::ActionRequired, ]), Self::Refunds => HashSet::from([EventType::RefundSucceeded, EventType::RefundFailed]), Self::Disputes => HashSet::from([ EventType::DisputeOpened, EventType::DisputeExpired, EventType::DisputeAccepted, EventType::DisputeCancelled, EventType::DisputeChallenged, EventType::DisputeWon, EventType::DisputeLost, ]), Self::Mandates => HashSet::from([EventType::MandateActive, EventType::MandateRevoked]), #[cfg(feature = "payouts")] Self::Payouts => HashSet::from([ EventType::PayoutSuccess, EventType::PayoutFailed, EventType::PayoutInitiated, EventType::PayoutProcessing, EventType::PayoutCancelled, EventType::PayoutExpired, EventType::PayoutReversed, ]), } } } #[derive( Clone, Copy, Debug, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] // Reminder: Whenever an EventType variant is added or removed, make sure to update the `event_types` method in `EventClass` pub enum EventType { /// Authorize + Capture success PaymentSucceeded, /// Authorize + Capture failed PaymentFailed, PaymentProcessing, PaymentCancelled, PaymentCancelledPostCapture, PaymentAuthorized, PaymentPartiallyAuthorized, PaymentCaptured, PaymentExpired, ActionRequired, RefundSucceeded, RefundFailed, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, DisputeWon, DisputeLost, MandateActive, MandateRevoked, #[cfg(feature = "payouts")] PayoutSuccess, #[cfg(feature = "payouts")] PayoutFailed, #[cfg(feature = "payouts")] PayoutInitiated, #[cfg(feature = "payouts")] PayoutProcessing, #[cfg(feature = "payouts")] PayoutCancelled, #[cfg(feature = "payouts")] PayoutExpired, #[cfg(feature = "payouts")] PayoutReversed, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum WebhookDeliveryAttempt { InitialAttempt, AutomaticRetry, ManualRetry, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OutgoingWebhookEndpointStatus { /// The webhook endpoint is active and operational. Active, /// The webhook endpoint is temporarily disabled. Inactive, /// The webhook endpoint is deprecated and can no longer be reactivated. Deprecated, } // TODO: This decision about using KV mode or not, // should be taken at a top level rather than pushing it down to individual functions via an enum. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantStorageScheme { #[default] PostgresOnly, RedisKv, } /// Represents the overall status of a payment intent. /// The status transitions through various states depending on the payment method, confirmation, capture method, and any subsequent actions (like customer authentication or manual capture). #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum IntentStatus { /// The payment has succeeded. Refunds and disputes can be initiated. /// Manual retries are not allowed to be performed. Succeeded, /// The payment has failed. Refunds and disputes cannot be initiated. /// This payment can be retried manually with a new payment attempt. Failed, /// This payment has been cancelled. Cancelled, /// This payment has been cancelled post capture. CancelledPostCapture, /// This payment is still being processed by the payment processor. /// The status update might happen through webhooks or polling with the connector. Processing, /// The payment is waiting on some action from the customer. RequiresCustomerAction, /// The payment is waiting on some action from the merchant /// This would be in case of manual fraud approval RequiresMerchantAction, /// The payment is waiting to be confirmed with the payment method by the customer. RequiresPaymentMethod, #[default] RequiresConfirmation, /// The payment has been authorized, and it waiting to be captured. RequiresCapture, /// The payment has been captured partially. The remaining amount is cannot be captured. PartiallyCaptured, /// The payment has been captured partially and the remaining amount is capturable PartiallyCapturedAndCapturable, /// The payment has been authorized for a partial amount and requires capture PartiallyAuthorizedAndRequiresCapture, /// There has been a discrepancy between the amount/currency sent in the request and the amount/currency received by the processor Conflicted, /// The payment expired before it could be captured. Expired, } impl IntentStatus { /// Indicates whether the payment intent is in terminal state or not pub fn is_in_terminal_state(self) -> bool { match self { Self::Succeeded | Self::Failed | Self::Cancelled | Self::CancelledPostCapture | Self::PartiallyCaptured | Self::Expired => true, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::RequiresPaymentMethod | Self::RequiresConfirmation | Self::RequiresCapture | Self::PartiallyCapturedAndCapturable | Self::PartiallyAuthorizedAndRequiresCapture | Self::Conflicted => false, } } /// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { // Confirm has not happened yet Self::RequiresConfirmation | Self::RequiresPaymentMethod // Once the status is success, failed or cancelled need not force sync with the connector | Self::Succeeded | Self::Failed | Self::Cancelled | Self::CancelledPostCapture | Self::PartiallyCaptured | Self::RequiresCapture | Self::Conflicted | Self::Expired=> false, Self::Processing | Self::RequiresCustomerAction | Self::RequiresMerchantAction | Self::PartiallyCapturedAndCapturable | Self::PartiallyAuthorizedAndRequiresCapture => true, } } } /// Specifies how the payment method can be used for future payments. /// - `off_session`: The payment method can be used for future payments when the customer is not present. /// - `on_session`: The payment method is intended for use only when the customer is present during checkout. /// If omitted, defaults to `on_session`. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { OffSession, #[default] OnSession, } impl FutureUsage { /// Indicates whether the payment method should be saved for future use or not pub fn is_off_session(self) -> bool { match self { Self::OffSession => true, Self::OnSession => false, } } } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodIssuerCode { JpHdfc, JpIcici, JpGooglepay, JpApplepay, JpPhonepay, JpWechat, JpSofort, JpGiropay, JpSepa, JpBacs, } /// Payment Method Status #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodStatus { /// Indicates that the payment method is active and can be used for payments. Active, /// Indicates that the payment method is not active and hence cannot be used for payments. Inactive, /// Indicates that the payment method is awaiting some data or action before it can be marked /// as 'active'. Processing, /// Indicates that the payment method is awaiting some data before changing state to active AwaitingData, } impl From<AttemptStatus> for PaymentMethodStatus { fn from(attempt_status: AttemptStatus) -> Self { match attempt_status { AttemptStatus::Failure | AttemptStatus::Voided | AttemptStatus::VoidedPostCharge | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved | AttemptStatus::CodInitiated | AttemptStatus::Authorizing | AttemptStatus::VoidInitiated | AttemptStatus::AuthorizationFailed | AttemptStatus::RouterDeclined | AttemptStatus::AuthenticationSuccessful | AttemptStatus::PaymentMethodAwaited | AttemptStatus::AuthenticationFailed | AttemptStatus::AuthenticationPending | AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed | AttemptStatus::VoidFailed | AttemptStatus::AutoRefunded | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable | AttemptStatus::PartiallyAuthorized | AttemptStatus::ConfirmationAwaited | AttemptStatus::DeviceDataCollectionPending | AttemptStatus::IntegrityFailure | AttemptStatus::Expired => Self::Inactive, AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active, } } } /// To indicate the type of payment experience that the customer would go through #[derive( Eq, strum::EnumString, PartialEq, Hash, Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentExperience { /// The URL to which the customer needs to be redirected for completing the payment. #[default] RedirectToUrl, /// Contains the data for invoking the sdk client for completing the payment. InvokeSdkClient, /// The QR code data to be displayed to the customer. DisplayQrCode, /// Contains data to finish one click payment. OneClick, /// Redirect customer to link wallet LinkWallet, /// Contains the data for invoking the sdk client for completing the payment. InvokePaymentApp, /// Contains the data for displaying wait screen DisplayWaitScreen, /// Represents that otp needs to be collect and contains if consent is required CollectOtp, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { Visa, MasterCard, Amex, Discover, Unknown, } /// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets. #[derive( Clone, Copy, Debug, Eq, Ord, Hash, PartialOrd, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { Ach, Affirm, AfterpayClearpay, Alfamart, AliPay, AliPayHk, Alma, AmazonPay, Paysera, ApplePay, Atome, Bacs, BancontactCard, Becs, Benefit, Bizum, Blik, Bluecode, Boleto, BcaBankTransfer, BniVa, Breadpay, BriVa, BhnCardNetwork, #[cfg(feature = "v2")] Card, CardRedirect, CimbVa, #[serde(rename = "classic")] ClassicReward, Credit, CryptoCurrency, Cashapp, Dana, DanamonVa, Debit, DuitNow, Efecty, Eft, Eps, Flexiti, Fps, Evoucher, Giropay, Givex, GooglePay, GoPay, Gcash, Ideal, Interac, Indomaret, Klarna, KakaoPay, LocalBankRedirect, MandiriVa, Knet, MbWay, MobilePay, Momo, MomoAtm, Multibanco, OnlineBankingThailand, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingFpx, OnlineBankingPoland, OnlineBankingSlovakia, Oxxo, PagoEfectivo, PermataBankTransfer, OpenBankingUk, PayBright, Paypal, Paze, Pix, PaySafeCard, Przelewy24, PromptPay, Pse, RedCompra, RedPagos, SamsungPay, Sepa, SepaBankTransfer, SepaGuarenteedDebit, Skrill, Sofort, Swish, TouchNGo, Trustly, Twint, UpiCollect, UpiIntent, UpiQr, Vipps, VietQr, Venmo, Walley, WeChatPay, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, LocalBankTransfer, Mifinity, #[serde(rename = "open_banking_pis")] OpenBankingPIS, DirectCarrierBilling, InstantBankTransfer, InstantBankTransferFinland, InstantBankTransferPoland, RevolutPay, IndonesianBankTransfer, } impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { matches!( self, Self::ApplePay | Self::GooglePay | Self::SamsungPay | Self::Paypal | Self::Klarna ) } pub fn to_display_name(&self) -> String { let display_name = match self { Self::Ach => "ACH Direct Debit", Self::Bacs => "BACS Direct Debit", Self::Affirm => "Affirm", Self::AfterpayClearpay => "Afterpay Clearpay", Self::Alfamart => "Alfamart", Self::AliPay => "Alipay", Self::AliPayHk => "AlipayHK", Self::Alma => "Alma", Self::AmazonPay => "Amazon Pay", Self::Paysera => "Paysera", Self::ApplePay => "Apple Pay", Self::Atome => "Atome", Self::BancontactCard => "Bancontact Card", Self::Becs => "BECS Direct Debit", Self::Benefit => "Benefit", Self::Bizum => "Bizum", Self::Blik => "BLIK", Self::Bluecode => "Bluecode", Self::Boleto => "Boleto Bancário", Self::BcaBankTransfer => "BCA Bank Transfer", Self::BniVa => "BNI Virtual Account", Self::Breadpay => "Breadpay", Self::BriVa => "BRI Virtual Account", Self::BhnCardNetwork => "BHN Card Network", Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", #[cfg(feature = "v2")] Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", Self::Dana => "DANA", Self::DanamonVa => "Danamon Virtual Account", Self::Debit => "Debit Card", Self::DuitNow => "DuitNow", Self::Efecty => "Efecty", Self::Eft => "EFT", Self::Eps => "EPS", Self::Flexiti => "Flexiti", Self::Fps => "FPS", Self::Evoucher => "Evoucher", Self::Giropay => "Giropay", Self::Givex => "Givex", Self::GooglePay => "Google Pay", Self::GoPay => "GoPay", Self::Gcash => "GCash", Self::Ideal => "iDEAL", Self::Interac => "Interac", Self::Indomaret => "Indomaret", Self::InstantBankTransfer => "Instant Bank Transfer", Self::InstantBankTransferFinland => "Instant Bank Transfer Finland", Self::InstantBankTransferPoland => "Instant Bank Transfer Poland", Self::Klarna => "Klarna", Self::KakaoPay => "KakaoPay", Self::LocalBankRedirect => "Local Bank Redirect", Self::MandiriVa => "Mandiri Virtual Account", Self::Knet => "KNET", Self::MbWay => "MB WAY", Self::MobilePay => "MobilePay", Self::Momo => "MoMo", Self::MomoAtm => "MoMo ATM", Self::Multibanco => "Multibanco", Self::OnlineBankingThailand => "Online Banking Thailand", Self::OnlineBankingCzechRepublic => "Online Banking Czech Republic", Self::OnlineBankingFinland => "Online Banking Finland", Self::OnlineBankingFpx => "Online Banking FPX", Self::OnlineBankingPoland => "Online Banking Poland", Self::OnlineBankingSlovakia => "Online Banking Slovakia", Self::Oxxo => "OXXO", Self::PagoEfectivo => "PagoEfectivo", Self::PermataBankTransfer => "Permata Bank Transfer", Self::OpenBankingUk => "Open Banking UK", Self::PayBright => "PayBright", Self::Paypal => "PayPal", Self::Paze => "Paze", Self::Pix => "Pix", Self::PaySafeCard => "PaySafeCard", Self::Przelewy24 => "Przelewy24", Self::PromptPay => "PromptPay", Self::Pse => "PSE", Self::RedCompra => "RedCompra", Self::RedPagos => "RedPagos", Self::SamsungPay => "Samsung Pay", Self::Sepa => "SEPA Direct Debit", Self::SepaGuarenteedDebit => "SEPA Guarenteed Direct Debit", Self::SepaBankTransfer => "SEPA Bank Transfer", Self::Sofort => "Sofort", Self::Skrill => "Skrill", Self::Swish => "Swish", Self::TouchNGo => "Touch 'n Go", Self::Trustly => "Trustly", Self::Twint => "TWINT", Self::UpiCollect => "UPI Collect", Self::UpiIntent => "UPI Intent", Self::UpiQr => "UPI QR", Self::Vipps => "Vipps", Self::VietQr => "VietQR", Self::Venmo => "Venmo", Self::Walley => "Walley", Self::WeChatPay => "WeChat Pay", Self::SevenEleven => "7-Eleven", Self::Lawson => "Lawson", Self::MiniStop => "Mini Stop", Self::FamilyMart => "FamilyMart", Self::Seicomart => "Seicomart", Self::PayEasy => "PayEasy", Self::LocalBankTransfer => "Local Bank Transfer", Self::Mifinity => "MiFinity", Self::OpenBankingPIS => "Open Banking PIS", Self::DirectCarrierBilling => "Direct Carrier Billing", Self::RevolutPay => "RevolutPay", Self::IndonesianBankTransfer => "Indonesian Bank Transfer", }; display_name.to_string() } } impl masking::SerializableSecret for PaymentMethodType {} /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. #[derive( Clone, Copy, Debug, Default, Eq, PartialOrd, Ord, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethod { #[default] Card, CardRedirect, PayLater, Wallet, BankRedirect, BankTransfer, Crypto, BankDebit, Reward, RealTimePayment, Upi, Voucher, GiftCard, OpenBanking, MobilePayment, } /// Indicates the gateway system through which the payment is processed. #[derive( Clone, Copy, Debug, Default, Eq, PartialOrd, Ord, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GatewaySystem { #[default] Direct, UnifiedConnectorService, } #[derive( Clone, Copy, Debug, Default, Eq, PartialOrd, Ord, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] /// Indicates the execution path through which the payment is processed. pub enum ExecutionPath { #[default] Direct, UnifiedConnectorService, ShadowUnifiedConnectorService, } #[derive( Clone, Copy, Debug, Eq, PartialOrd, Ord, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ShadowRolloutAvailability { IsAvailable, NotAvailable, } #[derive( Clone, Copy, Debug, Eq, PartialOrd, Ord, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UcsAvailability { Enabled, Disabled, } #[derive( Clone, Copy, Debug, Default, Eq, PartialOrd, Ord, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ExecutionMode { #[default] Primary, Shadow, } #[derive( Clone, Copy, Debug, Eq, PartialOrd, Ord, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ConnectorIntegrationType { UcsConnector, DirectConnector, } /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentType { #[default] Normal, NewMandate, SetupMandate, RecurringMandate, } /// SCA Exemptions types available for authentication #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ScaExemptionType { #[default] LowValue, TransactionRiskAnalysis, } #[derive( Clone, Debug, Default, Eq, PartialOrd, Ord, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] /// Describes the channel through which the payment was initiated. pub enum PaymentChannel { #[default] Ecommerce, MailOrder, TelephoneOrder, #[serde(untagged)] #[strum(default)] Other(String), } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CtpServiceProvider { Visa, Mastercard, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { #[serde(alias = "Failure")] Failure, #[serde(alias = "ManualReview")] ManualReview, #[default] #[serde(alias = "Pending")] Pending, #[serde(alias = "Success")] Success, #[serde(alias = "TransactionFailure")] TransactionFailure, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayStatus { Created, #[default] Pending, Success, Failure, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RelayType { Refund, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, strum::Display, strum::EnumString, strum::EnumIter, serde::Serialize, serde::Deserialize, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } /// The status of the mandate, which indicates whether it can be used to initiate a payment. #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateStatus { #[default] Active, Inactive, Pending, Revoked, } /// Indicates the card network. #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum CardNetwork { #[serde(alias = "VISA")] Visa, #[serde(alias = "MASTERCARD")] Mastercard, #[serde(alias = "AMERICANEXPRESS")] #[serde(alias = "AMEX")] AmericanExpress, JCB, #[serde(alias = "DINERSCLUB")] DinersClub, #[serde(alias = "DISCOVER")] Discover, #[serde(alias = "CARTESBANCAIRES")] CartesBancaires, #[serde(alias = "UNIONPAY")] UnionPay, #[serde(alias = "INTERAC")] Interac, #[serde(alias = "RUPAY")] RuPay, #[serde(alias = "MAESTRO")] Maestro, #[serde(alias = "STAR")] Star, #[serde(alias = "PULSE")] Pulse, #[serde(alias = "ACCEL")] Accel, #[serde(alias = "NYCE")] Nyce, } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] pub enum RegulatedName { #[serde(rename = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")] #[strum(serialize = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")] NonExemptWithFraud, #[serde(untagged)] #[strum(default)] Unknown(String), } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "lowercase")] pub enum PanOrToken { Pan, Token, } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "UPPERCASE")] #[serde(rename_all = "snake_case")] pub enum CardType { Credit, Debit, } #[derive(Debug, Clone, Serialize, Deserialize, strum::EnumString, strum::Display)] #[serde(rename_all = "snake_case")] pub enum DecisionEngineMerchantCategoryCode { #[serde(rename = "merchant_category_code_0001")] Mcc0001, } impl CardNetwork { pub fn is_signature_network(&self) -> bool { match self { Self::Interac | Self::Star | Self::Pulse | Self::Accel | Self::Nyce | Self::CartesBancaires => false, Self::Visa | Self::Mastercard | Self::AmericanExpress | Self::JCB | Self::DinersClub | Self::Discover | Self::UnionPay | Self::RuPay | Self::Maestro => true, } } pub fn is_us_local_network(&self) -> bool { match self { Self::Star | Self::Pulse | Self::Accel | Self::Nyce => true, Self::Interac | Self::CartesBancaires | Self::Visa | Self::Mastercard | Self::AmericanExpress | Self::JCB | Self::DinersClub | Self::Discover | Self::UnionPay | Self::RuPay | Self::Maestro => false, } } } /// Stage of the dispute #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStage { PreDispute, #[default] Dispute, PreArbitration, Arbitration, DisputeReversal, } /// Status of the dispute #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeStatus { #[default] DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] pub enum MerchantCategory { #[serde(rename = "Grocery Stores, Supermarkets (5411)")] GroceryStoresSupermarkets, #[serde(rename = "Lodging-Hotels, Motels, Resorts-not elsewhere classified (7011)")] LodgingHotelsMotelsResorts, #[serde(rename = "Agricultural Cooperatives (0763)")] AgriculturalCooperatives, #[serde(rename = "Attorneys, Legal Services (8111)")] AttorneysLegalServices, #[serde(rename = "Office and Commercial Furniture (5021)")] OfficeAndCommercialFurniture, #[serde(rename = "Computer Network/Information Services (4816)")] ComputerNetworkInformationServices, #[serde(rename = "Shoe Stores (5661)")] ShoeStores, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum MerchantCategoryCode { #[serde(rename = "5411")] #[strum(serialize = "5411")] Mcc5411, #[serde(rename = "7011")] #[strum(serialize = "7011")] Mcc7011, #[serde(rename = "0763")] #[strum(serialize = "0763")] Mcc0763, #[serde(rename = "8111")] #[strum(serialize = "8111")] Mcc8111, #[serde(rename = "5021")] #[strum(serialize = "5021")] Mcc5021, #[serde(rename = "4816")] #[strum(serialize = "4816")] Mcc4816, #[serde(rename = "5661")] #[strum(serialize = "5661")] Mcc5661, } impl MerchantCategoryCode { pub fn to_merchant_category_name(&self) -> MerchantCategory { match self { Self::Mcc5411 => MerchantCategory::GroceryStoresSupermarkets, Self::Mcc7011 => MerchantCategory::LodgingHotelsMotelsResorts, Self::Mcc0763 => MerchantCategory::AgriculturalCooperatives, Self::Mcc8111 => MerchantCategory::AttorneysLegalServices, Self::Mcc5021 => MerchantCategory::OfficeAndCommercialFurniture, Self::Mcc4816 => MerchantCategory::ComputerNetworkInformationServices, Self::Mcc5661 => MerchantCategory::ShoeStores, } } } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] pub struct MerchantCategoryCodeWithName { pub code: MerchantCategoryCode, pub name: MerchantCategory, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, utoipa::ToSchema, Copy )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[rustfmt::skip] pub enum CountryAlpha2 { AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT, AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW, BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU, GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR, IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW, KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP, NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA, SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK, SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, UM, UY, UZ, VU, VE, VN, VG, VI, WF, EH, YE, ZM, ZW, #[default] US } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RequestIncrementalAuthorization { True, #[default] False, Default, } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SplitTxnsEnabled { Enable, #[default] Skip, } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ActiveAttemptIDType { AttemptsGroupID, #[default] AttemptID, } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { AFG, ALA, ALB, DZA, ASM, AND, AGO, AIA, ATA, ATG, ARG, ARM, ABW, AUS, AUT, AZE, BHS, BHR, BGD, BRB, BLR, BEL, BLZ, BEN, BMU, BTN, BOL, BES, BIH, BWA, BVT, BRA, IOT, BRN, BGR, BFA, BDI, CPV, KHM, CMR, CAN, CYM, CAF, TCD, CHL, CHN, CXR, CCK, COL, COM, COG, COD, COK, CRI, CIV, HRV, CUB, CUW, CYP, CZE, DNK, DJI, DMA, DOM, ECU, EGY, SLV, GNQ, ERI, EST, ETH, FLK, FRO, FJI, FIN, FRA, GUF, PYF, ATF, GAB, GMB, GEO, DEU, GHA, GIB, GRC, GRL, GRD, GLP, GUM, GTM, GGY, GIN, GNB, GUY, HTI, HMD, VAT, HND, HKG, HUN, ISL, IND, IDN, IRN, IRQ, IRL, IMN, ISR, ITA, JAM, JPN, JEY, JOR, KAZ, KEN, KIR, PRK, KOR, KWT, KGZ, LAO, LVA, LBN, LSO, LBR, LBY, LIE, LTU, LUX, MAC, MKD, MDG, MWI, MYS, MDV, MLI, MLT, MHL, MTQ, MRT, MUS, MYT, MEX, FSM, MDA, MCO, MNG, MNE, MSR, MAR, MOZ, MMR, NAM, NRU, NPL, NLD, NCL, NZL, NIC, NER, NGA, NIU, NFK, MNP, NOR, OMN, PAK, PLW, PSE, PAN, PNG, PRY, PER, PHL, PCN, POL, PRT, PRI, QAT, REU, ROU, RUS, RWA, BLM, SHN, KNA, LCA, MAF, SPM, VCT, WSM, SMR, STP, SAU, SEN, SRB, SYC, SLE, SGP, SXM, SVK, SVN, SLB, SOM, ZAF, SGS, SSD, ESP, LKA, SDN, SUR, SJM, SWZ, SWE, CHE, SYR, TWN, TJK, TZA, THA, TLS, TGO, TKL, TON, TTO, TUN, TUR, TKM, TCA, TUV, UGA, UKR, ARE, GBR, USA, UMI, URY, UZB, VUT, VEN, VNM, VGB, VIR, WLF, ESH, YEM, ZMB, ZWE } #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, Deserialize, Serialize, utoipa::ToSchema, )] pub enum Country { Afghanistan, AlandIslands, Albania, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antarctica, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, BoliviaPlurinationalState, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, BouvetIsland, Brazil, BritishIndianOceanTerritory, BruneiDarussalam, Bulgaria, BurkinaFaso, Burundi, CaboVerde, Cambodia, Cameroon, Canada, CaymanIslands, CentralAfricanRepublic, Chad, Chile, China, ChristmasIsland, CocosKeelingIslands, Colombia, Comoros, Congo, CongoDemocraticRepublic, CookIslands, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, Czechia, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FalklandIslandsMalvinas, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, FrenchSouthernTerritories, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, HeardIslandAndMcDonaldIslands, HolySee, Honduras, HongKong, Hungary, Iceland, India, Indonesia, IranIslamicRepublic, Iraq, Ireland, IsleOfMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, KoreaDemocraticPeoplesRepublic, KoreaRepublic, Kuwait, Kyrgyzstan, LaoPeoplesDemocraticRepublic, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macao, MacedoniaTheFormerYugoslavRepublic, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, MicronesiaFederatedStates, MoldovaRepublic, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Niue, NorfolkIsland, NorthernMarianaIslands, Norway, Oman, Pakistan, Palau, PalestineState, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Pitcairn, Poland, Portugal, PuertoRico, Qatar, Reunion, Romania, RussianFederation, Rwanda, SaintBarthelemy, SaintHelenaAscensionAndTristandaCunha, SaintKittsAndNevis, SaintLucia, SaintMartinFrenchpart, SaintPierreAndMiquelon, SaintVincentAndTheGrenadines, Samoa, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaartenDutchpart, Slovakia, Slovenia, SolomonIslands, Somalia, SouthAfrica, SouthGeorgiaAndTheSouthSandwichIslands, SouthSudan, Spain, SriLanka, Sudan, Suriname, SvalbardAndJanMayen, Swaziland, Sweden, Switzerland, SyrianArabRepublic, TaiwanProvinceOfChina, Tajikistan, TanzaniaUnitedRepublic, Thailand, TimorLeste, Togo, Tokelau, Tonga, TrinidadAndTobago, Tunisia, Turkey, Turkmenistan, TurksAndCaicosIslands, Tuvalu, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdomOfGreatBritainAndNorthernIreland, UnitedStatesOfAmerica, UnitedStatesMinorOutlyingIslands, Uruguay, Uzbekistan, Vanuatu, VenezuelaBolivarianRepublic, Vietnam, VirginIslandsBritish, VirginIslandsUS, WallisAndFutuna, WesternSahara, Yemen, Zambia, Zimbabwe, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FileUploadProvider { #[default] Router, Stripe, Checkout, Worldpayvantiv, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UsStatesAbbreviation { AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FM, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MH, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VI, VA, WA, WV, WI, WY, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AustraliaStatesAbbreviation { ACT, NT, NSW, QLD, SA, TAS, VIC, WA, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum JapanStatesAbbreviation { #[strum(serialize = "23")] Aichi, #[strum(serialize = "05")] Akita, #[strum(serialize = "02")] Aomori, #[strum(serialize = "38")] Ehime, #[strum(serialize = "21")] Gifu, #[strum(serialize = "10")] Gunma, #[strum(serialize = "34")] Hiroshima, #[strum(serialize = "01")] Hokkaido, #[strum(serialize = "18")] Fukui, #[strum(serialize = "40")] Fukuoka, #[strum(serialize = "07")] Fukushima, #[strum(serialize = "28")] Hyogo, #[strum(serialize = "08")] Ibaraki, #[strum(serialize = "17")] Ishikawa, #[strum(serialize = "03")] Iwate, #[strum(serialize = "37")] Kagawa, #[strum(serialize = "46")] Kagoshima, #[strum(serialize = "14")] Kanagawa, #[strum(serialize = "39")] Kochi, #[strum(serialize = "43")] Kumamoto, #[strum(serialize = "26")] Kyoto, #[strum(serialize = "24")] Mie, #[strum(serialize = "04")] Miyagi, #[strum(serialize = "45")] Miyazaki, #[strum(serialize = "20")] Nagano, #[strum(serialize = "42")] Nagasaki, #[strum(serialize = "29")] Nara, #[strum(serialize = "15")] Niigata, #[strum(serialize = "44")] Oita, #[strum(serialize = "33")] Okayama, #[strum(serialize = "47")] Okinawa, #[strum(serialize = "27")] Osaka, #[strum(serialize = "41")] Saga, #[strum(serialize = "11")] Saitama, #[strum(serialize = "25")] Shiga, #[strum(serialize = "32")] Shimane, #[strum(serialize = "22")] Shizuoka, #[strum(serialize = "12")] Chiba, #[strum(serialize = "36")] Tokusima, #[strum(serialize = "13")] Tokyo, #[strum(serialize = "09")] Tochigi, #[strum(serialize = "31")] Tottori, #[strum(serialize = "16")] Toyama, #[strum(serialize = "30")] Wakayama, #[strum(serialize = "06")] Yamagata, #[strum(serialize = "35")] Yamaguchi, #[strum(serialize = "19")] Yamanashi, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NewZealandStatesAbbreviation { #[strum(serialize = "AUK")] Auckland, #[strum(serialize = "BOP")] BayOfPlenty, #[strum(serialize = "CAN")] Canterbury, #[strum(serialize = "GIS")] Gisborne, #[strum(serialize = "HKB")] HawkesBay, #[strum(serialize = "MWT")] ManawatūWhanganui, #[strum(serialize = "MBH")] Marlborough, #[strum(serialize = "NSN")] Nelson, #[strum(serialize = "NTL")] Northland, #[strum(serialize = "OTA")] Otago, #[strum(serialize = "STL")] Southland, #[strum(serialize = "TKI")] Taranaki, #[strum(serialize = "TAS")] Tasman, #[strum(serialize = "WKO")] Waikato, #[strum(serialize = "CIT")] ChathamIslandsTerritory, #[strum(serialize = "WGN")] GreaterWellington, #[strum(serialize = "WTC")] WestCoast, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SingaporeStatesAbbreviation { #[strum(serialize = "01")] CentralSingapore, #[strum(serialize = "02")] NorthEast, #[strum(serialize = "03")] NorthWest, #[strum(serialize = "04")] SouthEast, #[strum(serialize = "05")] SouthWest, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum ThailandStatesAbbreviation { #[strum(serialize = "37")] AmnatCharoen, #[strum(serialize = "15")] AngThong, #[strum(serialize = "10")] Bangkok, #[strum(serialize = "38")] BuengKan, #[strum(serialize = "31")] BuriRam, #[strum(serialize = "24")] Chachoengsao, #[strum(serialize = "18")] ChaiNat, #[strum(serialize = "36")] Chaiyaphum, #[strum(serialize = "22")] Chanthaburi, #[strum(serialize = "57")] ChiangRai, #[strum(serialize = "50")] ChiangMai, #[strum(serialize = "20")] ChonBuri, #[strum(serialize = "86")] Chumphon, #[strum(serialize = "46")] Kalasin, #[strum(serialize = "62")] KamphaengPhet, #[strum(serialize = "71")] Kanchanaburi, #[strum(serialize = "40")] KhonKaen, #[strum(serialize = "81")] Krabi, #[strum(serialize = "52")] Lampang, #[strum(serialize = "51")] Lamphun, #[strum(serialize = "42")] Loei, #[strum(serialize = "16")] LopBuri, #[strum(serialize = "58")] MaeHongSon, #[strum(serialize = "44")] MahaSarakham, #[strum(serialize = "49")] Mukdahan, #[strum(serialize = "26")] NakhonNayok, #[strum(serialize = "73")] NakhonPathom, #[strum(serialize = "48")] NakhonPhanom, #[strum(serialize = "30")] NakhonRatchasima, #[strum(serialize = "60")] NakhonSawan, #[strum(serialize = "80")] NakhonSiThammarat, #[strum(serialize = "55")] Nan, #[strum(serialize = "96")] Narathiwat, #[strum(serialize = "39")] NongBuaLamPhu, #[strum(serialize = "43")] NongKhai, #[strum(serialize = "12")] Nonthaburi, #[strum(serialize = "13")] PathumThani, #[strum(serialize = "94")] Pattani, #[strum(serialize = "82")] Phangnga, #[strum(serialize = "93")] Phatthalung, #[strum(serialize = "56")] Phayao, #[strum(serialize = "S")] Phatthaya, #[strum(serialize = "67")] Phetchabun, #[strum(serialize = "76")] Phetchaburi, #[strum(serialize = "66")] Phichit, #[strum(serialize = "65")] Phitsanulok, #[strum(serialize = "54")] Phrae, #[strum(serialize = "14")] PhraNakhonSiAyutthaya, #[strum(serialize = "83")] Phuket, #[strum(serialize = "25")] PrachinBuri, #[strum(serialize = "77")] PrachuapKhiriKhan, #[strum(serialize = "85")] Ranong, #[strum(serialize = "70")] Ratchaburi, #[strum(serialize = "21")] Rayong, #[strum(serialize = "45")] RoiEt, #[strum(serialize = "27")] SaKaeo, #[strum(serialize = "47")] SakonNakhon, #[strum(serialize = "11")] SamutPrakan, #[strum(serialize = "74")] SamutSakhon, #[strum(serialize = "75")] SamutSongkhram, #[strum(serialize = "19")] Saraburi, #[strum(serialize = "91")] Satun, #[strum(serialize = "33")] SiSaKet, #[strum(serialize = "17")] SingBuri, #[strum(serialize = "90")] Songkhla, #[strum(serialize = "64")] Sukhothai, #[strum(serialize = "72")] SuphanBuri, #[strum(serialize = "84")] SuratThani, #[strum(serialize = "32")] Surin, #[strum(serialize = "63")] Tak, #[strum(serialize = "92")] Trang, #[strum(serialize = "23")] Trat, #[strum(serialize = "34")] UbonRatchathani, #[strum(serialize = "41")] UdonThani, #[strum(serialize = "61")] UthaiThani, #[strum(serialize = "53")] Uttaradit, #[strum(serialize = "95")] Yala, #[strum(serialize = "35")] Yasothon, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PhilippinesStatesAbbreviation { #[strum(serialize = "ABR")] Abra, #[strum(serialize = "AGN")] AgusanDelNorte, #[strum(serialize = "AGS")] AgusanDelSur, #[strum(serialize = "AKL")] Aklan, #[strum(serialize = "ALB")] Albay, #[strum(serialize = "ANT")] Antique, #[strum(serialize = "APA")] Apayao, #[strum(serialize = "AUR")] Aurora, #[strum(serialize = "14")] AutonomousRegionInMuslimMindanao, #[strum(serialize = "BAS")] Basilan, #[strum(serialize = "BAN")] Bataan, #[strum(serialize = "BTN")] Batanes, #[strum(serialize = "BTG")] Batangas, #[strum(serialize = "BEN")] Benguet, #[strum(serialize = "05")] Bicol, #[strum(serialize = "BIL")] Biliran, #[strum(serialize = "BOH")] Bohol, #[strum(serialize = "BUK")] Bukidnon, #[strum(serialize = "BUL")] Bulacan, #[strum(serialize = "CAG")] Cagayan, #[strum(serialize = "02")] CagayanValley, #[strum(serialize = "40")] Calabarzon, #[strum(serialize = "CAN")] CamarinesNorte, #[strum(serialize = "CAS")] CamarinesSur, #[strum(serialize = "CAM")] Camiguin, #[strum(serialize = "CAP")] Capiz, #[strum(serialize = "13")] Caraga, #[strum(serialize = "CAT")] Catanduanes, #[strum(serialize = "CAV")] Cavite, #[strum(serialize = "CEB")] Cebu, #[strum(serialize = "03")] CentralLuzon, #[strum(serialize = "07")] CentralVisayas, #[strum(serialize = "15")] CordilleraAdministrativeRegion, #[strum(serialize = "NCO")] Cotabato, #[strum(serialize = "11")] Davao, #[strum(serialize = "DVO")] DavaoOccidental, #[strum(serialize = "DAO")] DavaoOriental, #[strum(serialize = "COM")] DavaoDeOro, #[strum(serialize = "DAV")] DavaoDelNorte, #[strum(serialize = "DAS")] DavaoDelSur, #[strum(serialize = "DIN")] DinagatIslands, #[strum(serialize = "EAS")] EasternSamar, #[strum(serialize = "08")] EasternVisayas, #[strum(serialize = "GUI")] Guimaras, #[strum(serialize = "ILN")] HilagangIloko, #[strum(serialize = "LAN")] HilagangLanaw, #[strum(serialize = "MGN")] HilagangMagindanaw, #[strum(serialize = "NSA")] HilagangSamar, #[strum(serialize = "ZAN")] HilagangSambuwangga, #[strum(serialize = "SUN")] HilagangSurigaw, #[strum(serialize = "IFU")] Ifugao, #[strum(serialize = "01")] Ilocos, #[strum(serialize = "ILS")] IlocosSur, #[strum(serialize = "ILI")] Iloilo, #[strum(serialize = "ISA")] Isabela, #[strum(serialize = "KAL")] Kalinga, #[strum(serialize = "MDC")] KanlurangMindoro, #[strum(serialize = "MSC")] KanlurangMisamis, #[strum(serialize = "NEC")] KanlurangNegros, #[strum(serialize = "SLE")] KatimogangLeyte, #[strum(serialize = "QUE")] Keson, #[strum(serialize = "QUI")] Kirino, #[strum(serialize = "LUN")] LaUnion, #[strum(serialize = "LAG")] Laguna, #[strum(serialize = "MOU")] LalawigangBulubundukin, #[strum(serialize = "LAS")] LanaoDelSur, #[strum(serialize = "LEY")] Leyte, #[strum(serialize = "MGS")] MaguindanaoDelSur, #[strum(serialize = "MAD")] Marinduque, #[strum(serialize = "MAS")] Masbate, #[strum(serialize = "41")] Mimaropa, #[strum(serialize = "MDR")] MindoroOriental, #[strum(serialize = "MSR")] MisamisOccidental, #[strum(serialize = "00")] NationalCapitalRegion, #[strum(serialize = "NER")] NegrosOriental, #[strum(serialize = "10")] NorthernMindanao, #[strum(serialize = "NUE")] NuevaEcija, #[strum(serialize = "NUV")] NuevaVizcaya, #[strum(serialize = "PLW")] Palawan, #[strum(serialize = "PAM")] Pampanga, #[strum(serialize = "PAN")] Pangasinan, #[strum(serialize = "06")] RehiyonNgKanlurangBisaya, #[strum(serialize = "12")] RehiyonNgSoccsksargen, #[strum(serialize = "09")] RehiyonNgTangwayNgSambuwangga, #[strum(serialize = "RIZ")] Risal, #[strum(serialize = "ROM")] Romblon, #[strum(serialize = "WSA")] Samar, #[strum(serialize = "ZMB")] Sambales, #[strum(serialize = "ZSI")] SambuwanggaSibugay, #[strum(serialize = "SAR")] Sarangani, #[strum(serialize = "SIG")] Sikihor, #[strum(serialize = "SOR")] Sorsogon, #[strum(serialize = "SCO")] SouthCotabato, #[strum(serialize = "SUK")] SultanKudarat, #[strum(serialize = "SLU")] Sulu, #[strum(serialize = "SUR")] SurigaoDelSur, #[strum(serialize = "TAR")] Tarlac, #[strum(serialize = "TAW")] TawiTawi, #[strum(serialize = "ZAS")] TimogSambuwangga, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IndiaStatesAbbreviation { #[strum(serialize = "AN")] AndamanAndNicobarIslands, #[strum(serialize = "AP")] AndhraPradesh, #[strum(serialize = "AR")] ArunachalPradesh, #[strum(serialize = "AS")] Assam, #[strum(serialize = "BR")] Bihar, #[strum(serialize = "CH")] Chandigarh, #[strum(serialize = "CG")] Chhattisgarh, #[strum(serialize = "DL")] Delhi, #[strum(serialize = "DH")] DadraAndNagarHaveliAndDamanAndDiu, #[strum(serialize = "GA")] Goa, #[strum(serialize = "GJ")] Gujarat, #[strum(serialize = "HR")] Haryana, #[strum(serialize = "HP")] HimachalPradesh, #[strum(serialize = "JK")] JammuAndKashmir, #[strum(serialize = "JH")] Jharkhand, #[strum(serialize = "KA")] Karnataka, #[strum(serialize = "KL")] Kerala, #[strum(serialize = "LA")] Ladakh, #[strum(serialize = "LD")] Lakshadweep, #[strum(serialize = "MP")] MadhyaPradesh, #[strum(serialize = "MH")] Maharashtra, #[strum(serialize = "MN")] Manipur, #[strum(serialize = "ML")] Meghalaya, #[strum(serialize = "MZ")] Mizoram, #[strum(serialize = "NL")] Nagaland, #[strum(serialize = "OD")] Odisha, #[strum(serialize = "PY")] Puducherry, #[strum(serialize = "PB")] Punjab, #[strum(serialize = "RJ")] Rajasthan, #[strum(serialize = "SK")] Sikkim, #[strum(serialize = "TN")] TamilNadu, #[strum(serialize = "TG")] Telangana, #[strum(serialize = "TR")] Tripura, #[strum(serialize = "UP")] UttarPradesh, #[strum(serialize = "UK")] Uttarakhand, #[strum(serialize = "WB")] WestBengal, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CanadaStatesAbbreviation { AB, BC, MB, NB, NL, NT, NS, NU, ON, PE, QC, SK, YT, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AlbaniaStatesAbbreviation { #[strum(serialize = "01")] Berat, #[strum(serialize = "09")] Diber, #[strum(serialize = "02")] Durres, #[strum(serialize = "03")] Elbasan, #[strum(serialize = "04")] Fier, #[strum(serialize = "05")] Gjirokaster, #[strum(serialize = "06")] Korce, #[strum(serialize = "07")] Kukes, #[strum(serialize = "08")] Lezhe, #[strum(serialize = "10")] Shkoder, #[strum(serialize = "11")] Tirane, #[strum(serialize = "12")] Vlore, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AndorraStatesAbbreviation { #[strum(serialize = "07")] AndorraLaVella, #[strum(serialize = "02")] Canillo, #[strum(serialize = "03")] Encamp, #[strum(serialize = "08")] EscaldesEngordany, #[strum(serialize = "04")] LaMassana, #[strum(serialize = "05")] Ordino, #[strum(serialize = "06")] SantJuliaDeLoria, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum AustriaStatesAbbreviation { #[strum(serialize = "1")] Burgenland, #[strum(serialize = "2")] Carinthia, #[strum(serialize = "3")] LowerAustria, #[strum(serialize = "5")] Salzburg, #[strum(serialize = "6")] Styria, #[strum(serialize = "7")] Tyrol, #[strum(serialize = "4")] UpperAustria, #[strum(serialize = "9")] Vienna, #[strum(serialize = "8")] Vorarlberg, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelarusStatesAbbreviation { #[strum(serialize = "BR")] BrestRegion, #[strum(serialize = "HO")] GomelRegion, #[strum(serialize = "HR")] GrodnoRegion, #[strum(serialize = "HM")] Minsk, #[strum(serialize = "MI")] MinskRegion, #[strum(serialize = "MA")] MogilevRegion, #[strum(serialize = "VI")] VitebskRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BosniaAndHerzegovinaStatesAbbreviation { #[strum(serialize = "05")] BosnianPodrinjeCanton, #[strum(serialize = "BRC")] BrckoDistrict, #[strum(serialize = "10")] Canton10, #[strum(serialize = "06")] CentralBosniaCanton, #[strum(serialize = "BIH")] FederationOfBosniaAndHerzegovina, #[strum(serialize = "07")] HerzegovinaNeretvaCanton, #[strum(serialize = "02")] PosavinaCanton, #[strum(serialize = "SRP")] RepublikaSrpska, #[strum(serialize = "09")] SarajevoCanton, #[strum(serialize = "03")] TuzlaCanton, #[strum(serialize = "01")] UnaSanaCanton, #[strum(serialize = "08")] WestHerzegovinaCanton, #[strum(serialize = "04")] ZenicaDobojCanton, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BulgariaStatesAbbreviation { #[strum(serialize = "01")] BlagoevgradProvince, #[strum(serialize = "02")] BurgasProvince, #[strum(serialize = "08")] DobrichProvince, #[strum(serialize = "07")] GabrovoProvince, #[strum(serialize = "26")] HaskovoProvince, #[strum(serialize = "09")] KardzhaliProvince, #[strum(serialize = "10")] KyustendilProvince, #[strum(serialize = "11")] LovechProvince, #[strum(serialize = "12")] MontanaProvince, #[strum(serialize = "13")] PazardzhikProvince, #[strum(serialize = "14")] PernikProvince, #[strum(serialize = "15")] PlevenProvince, #[strum(serialize = "16")] PlovdivProvince, #[strum(serialize = "17")] RazgradProvince, #[strum(serialize = "18")] RuseProvince, #[strum(serialize = "27")] Shumen, #[strum(serialize = "19")] SilistraProvince, #[strum(serialize = "20")] SlivenProvince, #[strum(serialize = "21")] SmolyanProvince, #[strum(serialize = "22")] SofiaCityProvince, #[strum(serialize = "23")] SofiaProvince, #[strum(serialize = "24")] StaraZagoraProvince, #[strum(serialize = "25")] TargovishteProvince, #[strum(serialize = "03")] VarnaProvince, #[strum(serialize = "04")] VelikoTarnovoProvince, #[strum(serialize = "05")] VidinProvince, #[strum(serialize = "06")] VratsaProvince, #[strum(serialize = "28")] YambolProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CroatiaStatesAbbreviation { #[strum(serialize = "07")] BjelovarBilogoraCounty, #[strum(serialize = "12")] BrodPosavinaCounty, #[strum(serialize = "19")] DubrovnikNeretvaCounty, #[strum(serialize = "18")] IstriaCounty, #[strum(serialize = "06")] KoprivnicaKrizevciCounty, #[strum(serialize = "02")] KrapinaZagorjeCounty, #[strum(serialize = "09")] LikaSenjCounty, #[strum(serialize = "20")] MedimurjeCounty, #[strum(serialize = "14")] OsijekBaranjaCounty, #[strum(serialize = "11")] PozegaSlavoniaCounty, #[strum(serialize = "08")] PrimorjeGorskiKotarCounty, #[strum(serialize = "03")] SisakMoslavinaCounty, #[strum(serialize = "17")] SplitDalmatiaCounty, #[strum(serialize = "05")] VarazdinCounty, #[strum(serialize = "10")] ViroviticaPodravinaCounty, #[strum(serialize = "16")] VukovarSyrmiaCounty, #[strum(serialize = "13")] ZadarCounty, #[strum(serialize = "21")] Zagreb, #[strum(serialize = "01")] ZagrebCounty, #[strum(serialize = "15")] SibenikKninCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum CzechRepublicStatesAbbreviation { #[strum(serialize = "201")] BenesovDistrict, #[strum(serialize = "202")] BerounDistrict, #[strum(serialize = "641")] BlanskoDistrict, #[strum(serialize = "642")] BrnoCityDistrict, #[strum(serialize = "643")] BrnoCountryDistrict, #[strum(serialize = "801")] BruntalDistrict, #[strum(serialize = "644")] BreclavDistrict, #[strum(serialize = "20")] CentralBohemianRegion, #[strum(serialize = "411")] ChebDistrict, #[strum(serialize = "422")] ChomutovDistrict, #[strum(serialize = "531")] ChrudimDistrict, #[strum(serialize = "321")] DomazliceDistrict, #[strum(serialize = "421")] DecinDistrict, #[strum(serialize = "802")] FrydekMistekDistrict, #[strum(serialize = "631")] HavlickuvBrodDistrict, #[strum(serialize = "645")] HodoninDistrict, #[strum(serialize = "120")] HorniPocernice, #[strum(serialize = "521")] HradecKraloveDistrict, #[strum(serialize = "52")] HradecKraloveRegion, #[strum(serialize = "512")] JablonecNadNisouDistrict, #[strum(serialize = "711")] JesenikDistrict, #[strum(serialize = "632")] JihlavaDistrict, #[strum(serialize = "313")] JindrichuvHradecDistrict, #[strum(serialize = "522")] JicinDistrict, #[strum(serialize = "412")] KarlovyVaryDistrict, #[strum(serialize = "41")] KarlovyVaryRegion, #[strum(serialize = "803")] KarvinaDistrict, #[strum(serialize = "203")] KladnoDistrict, #[strum(serialize = "322")] KlatovyDistrict, #[strum(serialize = "204")] KolinDistrict, #[strum(serialize = "721")] KromerizDistrict, #[strum(serialize = "513")] LiberecDistrict, #[strum(serialize = "51")] LiberecRegion, #[strum(serialize = "423")] LitomericeDistrict, #[strum(serialize = "424")] LounyDistrict, #[strum(serialize = "207")] MladaBoleslavDistrict, #[strum(serialize = "80")] MoravianSilesianRegion, #[strum(serialize = "425")] MostDistrict, #[strum(serialize = "206")] MelnikDistrict, #[strum(serialize = "804")] NovyJicinDistrict, #[strum(serialize = "208")] NymburkDistrict, #[strum(serialize = "523")] NachodDistrict, #[strum(serialize = "712")] OlomoucDistrict, #[strum(serialize = "71")] OlomoucRegion, #[strum(serialize = "805")] OpavaDistrict, #[strum(serialize = "806")] OstravaCityDistrict, #[strum(serialize = "532")] PardubiceDistrict, #[strum(serialize = "53")] PardubiceRegion, #[strum(serialize = "633")] PelhrimovDistrict, #[strum(serialize = "32")] PlzenRegion, #[strum(serialize = "323")] PlzenCityDistrict, #[strum(serialize = "325")] PlzenNorthDistrict, #[strum(serialize = "324")] PlzenSouthDistrict, #[strum(serialize = "315")] PrachaticeDistrict, #[strum(serialize = "10")] Prague, #[strum(serialize = "101")] Prague1, #[strum(serialize = "110")] Prague10, #[strum(serialize = "111")] Prague11, #[strum(serialize = "112")] Prague12, #[strum(serialize = "113")] Prague13, #[strum(serialize = "114")] Prague14, #[strum(serialize = "115")] Prague15, #[strum(serialize = "116")] Prague16, #[strum(serialize = "102")] Prague2, #[strum(serialize = "121")] Prague21, #[strum(serialize = "103")] Prague3, #[strum(serialize = "104")] Prague4, #[strum(serialize = "105")] Prague5, #[strum(serialize = "106")] Prague6, #[strum(serialize = "107")] Prague7, #[strum(serialize = "108")] Prague8, #[strum(serialize = "109")] Prague9, #[strum(serialize = "209")] PragueEastDistrict, #[strum(serialize = "20A")] PragueWestDistrict, #[strum(serialize = "713")] ProstejovDistrict, #[strum(serialize = "314")] PisekDistrict, #[strum(serialize = "714")] PrerovDistrict, #[strum(serialize = "20B")] PribramDistrict, #[strum(serialize = "20C")] RakovnikDistrict, #[strum(serialize = "326")] RokycanyDistrict, #[strum(serialize = "524")] RychnovNadKneznouDistrict, #[strum(serialize = "514")] SemilyDistrict, #[strum(serialize = "413")] SokolovDistrict, #[strum(serialize = "31")] SouthBohemianRegion, #[strum(serialize = "64")] SouthMoravianRegion, #[strum(serialize = "316")] StrakoniceDistrict, #[strum(serialize = "533")] SvitavyDistrict, #[strum(serialize = "327")] TachovDistrict, #[strum(serialize = "426")] TepliceDistrict, #[strum(serialize = "525")] TrutnovDistrict, #[strum(serialize = "317")] TaborDistrict, #[strum(serialize = "634")] TrebicDistrict, #[strum(serialize = "722")] UherskeHradisteDistrict, #[strum(serialize = "723")] VsetinDistrict, #[strum(serialize = "63")] VysocinaRegion, #[strum(serialize = "646")] VyskovDistrict, #[strum(serialize = "724")] ZlinDistrict, #[strum(serialize = "72")] ZlinRegion, #[strum(serialize = "647")] ZnojmoDistrict, #[strum(serialize = "427")] UstiNadLabemDistrict, #[strum(serialize = "42")] UstiNadLabemRegion, #[strum(serialize = "534")] UstiNadOrliciDistrict, #[strum(serialize = "511")] CeskaLipaDistrict, #[strum(serialize = "311")] CeskeBudejoviceDistrict, #[strum(serialize = "312")] CeskyKrumlovDistrict, #[strum(serialize = "715")] SumperkDistrict, #[strum(serialize = "635")] ZdarNadSazavouDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum DenmarkStatesAbbreviation { #[strum(serialize = "84")] CapitalRegionOfDenmark, #[strum(serialize = "82")] CentralDenmarkRegion, #[strum(serialize = "81")] NorthDenmarkRegion, #[strum(serialize = "85")] RegionZealand, #[strum(serialize = "83")] RegionOfSouthernDenmark, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FinlandStatesAbbreviation { #[strum(serialize = "08")] CentralFinland, #[strum(serialize = "07")] CentralOstrobothnia, #[strum(serialize = "IS")] EasternFinlandProvince, #[strum(serialize = "19")] FinlandProper, #[strum(serialize = "05")] Kainuu, #[strum(serialize = "09")] Kymenlaakso, #[strum(serialize = "LL")] Lapland, #[strum(serialize = "13")] NorthKarelia, #[strum(serialize = "14")] NorthernOstrobothnia, #[strum(serialize = "15")] NorthernSavonia, #[strum(serialize = "12")] Ostrobothnia, #[strum(serialize = "OL")] OuluProvince, #[strum(serialize = "11")] Pirkanmaa, #[strum(serialize = "16")] PaijanneTavastia, #[strum(serialize = "17")] Satakunta, #[strum(serialize = "02")] SouthKarelia, #[strum(serialize = "03")] SouthernOstrobothnia, #[strum(serialize = "04")] SouthernSavonia, #[strum(serialize = "06")] TavastiaProper, #[strum(serialize = "18")] Uusimaa, #[strum(serialize = "01")] AlandIslands, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum FranceStatesAbbreviation { #[strum(serialize = "01")] Ain, #[strum(serialize = "02")] Aisne, #[strum(serialize = "03")] Allier, #[strum(serialize = "04")] AlpesDeHauteProvence, #[strum(serialize = "06")] AlpesMaritimes, #[strum(serialize = "6AE")] Alsace, #[strum(serialize = "07")] Ardeche, #[strum(serialize = "08")] Ardennes, #[strum(serialize = "09")] Ariege, #[strum(serialize = "10")] Aube, #[strum(serialize = "11")] Aude, #[strum(serialize = "ARA")] AuvergneRhoneAlpes, #[strum(serialize = "12")] Aveyron, #[strum(serialize = "67")] BasRhin, #[strum(serialize = "13")] BouchesDuRhone, #[strum(serialize = "BFC")] BourgogneFrancheComte, #[strum(serialize = "BRE")] Bretagne, #[strum(serialize = "14")] Calvados, #[strum(serialize = "15")] Cantal, #[strum(serialize = "CVL")] CentreValDeLoire, #[strum(serialize = "16")] Charente, #[strum(serialize = "17")] CharenteMaritime, #[strum(serialize = "18")] Cher, #[strum(serialize = "CP")] Clipperton, #[strum(serialize = "19")] Correze, #[strum(serialize = "20R")] Corse, #[strum(serialize = "2A")] CorseDuSud, #[strum(serialize = "21")] CoteDor, #[strum(serialize = "22")] CotesDarmor, #[strum(serialize = "23")] Creuse, #[strum(serialize = "79")] DeuxSevres, #[strum(serialize = "24")] Dordogne, #[strum(serialize = "25")] Doubs, #[strum(serialize = "26")] Drome, #[strum(serialize = "91")] Essonne, #[strum(serialize = "27")] Eure, #[strum(serialize = "28")] EureEtLoir, #[strum(serialize = "29")] Finistere, #[strum(serialize = "973")] FrenchGuiana, #[strum(serialize = "PF")] FrenchPolynesia, #[strum(serialize = "TF")] FrenchSouthernAndAntarcticLands, #[strum(serialize = "30")] Gard, #[strum(serialize = "32")] Gers, #[strum(serialize = "33")] Gironde, #[strum(serialize = "GES")] GrandEst, #[strum(serialize = "971")] Guadeloupe, #[strum(serialize = "68")] HautRhin, #[strum(serialize = "2B")] HauteCorse, #[strum(serialize = "31")] HauteGaronne, #[strum(serialize = "43")] HauteLoire, #[strum(serialize = "52")] HauteMarne, #[strum(serialize = "70")] HauteSaone, #[strum(serialize = "74")] HauteSavoie, #[strum(serialize = "87")] HauteVienne, #[strum(serialize = "05")] HautesAlpes, #[strum(serialize = "65")] HautesPyrenees, #[strum(serialize = "HDF")] HautsDeFrance, #[strum(serialize = "92")] HautsDeSeine, #[strum(serialize = "34")] Herault, #[strum(serialize = "IDF")] IleDeFrance, #[strum(serialize = "35")] IlleEtVilaine, #[strum(serialize = "36")] Indre, #[strum(serialize = "37")] IndreEtLoire, #[strum(serialize = "38")] Isere, #[strum(serialize = "39")] Jura, #[strum(serialize = "974")] LaReunion, #[strum(serialize = "40")] Landes, #[strum(serialize = "41")] LoirEtCher, #[strum(serialize = "42")] Loire, #[strum(serialize = "44")] LoireAtlantique, #[strum(serialize = "45")] Loiret, #[strum(serialize = "46")] Lot, #[strum(serialize = "47")] LotEtGaronne, #[strum(serialize = "48")] Lozere, #[strum(serialize = "49")] MaineEtLoire, #[strum(serialize = "50")] Manche, #[strum(serialize = "51")] Marne, #[strum(serialize = "972")] Martinique, #[strum(serialize = "53")] Mayenne, #[strum(serialize = "976")] Mayotte, #[strum(serialize = "69M")] MetropoleDeLyon, #[strum(serialize = "54")] MeurtheEtMoselle, #[strum(serialize = "55")] Meuse, #[strum(serialize = "56")] Morbihan, #[strum(serialize = "57")] Moselle, #[strum(serialize = "58")] Nievre, #[strum(serialize = "59")] Nord, #[strum(serialize = "NOR")] Normandie, #[strum(serialize = "NAQ")] NouvelleAquitaine, #[strum(serialize = "OCC")] Occitanie, #[strum(serialize = "60")] Oise, #[strum(serialize = "61")] Orne, #[strum(serialize = "75C")] Paris, #[strum(serialize = "62")] PasDeCalais, #[strum(serialize = "PDL")] PaysDeLaLoire, #[strum(serialize = "PAC")] ProvenceAlpesCoteDazur, #[strum(serialize = "63")] PuyDeDome, #[strum(serialize = "64")] PyreneesAtlantiques, #[strum(serialize = "66")] PyreneesOrientales, #[strum(serialize = "69")] Rhone, #[strum(serialize = "PM")] SaintPierreAndMiquelon, #[strum(serialize = "BL")] SaintBarthelemy, #[strum(serialize = "MF")] SaintMartin, #[strum(serialize = "71")] SaoneEtLoire, #[strum(serialize = "72")] Sarthe, #[strum(serialize = "73")] Savoie, #[strum(serialize = "77")] SeineEtMarne, #[strum(serialize = "76")] SeineMaritime, #[strum(serialize = "93")] SeineSaintDenis, #[strum(serialize = "80")] Somme, #[strum(serialize = "81")] Tarn, #[strum(serialize = "82")] TarnEtGaronne, #[strum(serialize = "90")] TerritoireDeBelfort, #[strum(serialize = "95")] ValDoise, #[strum(serialize = "94")] ValDeMarne, #[strum(serialize = "83")] Var, #[strum(serialize = "84")] Vaucluse, #[strum(serialize = "85")] Vendee, #[strum(serialize = "86")] Vienne, #[strum(serialize = "88")] Vosges, #[strum(serialize = "WF")] WallisAndFutuna, #[strum(serialize = "89")] Yonne, #[strum(serialize = "78")] Yvelines, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GermanyStatesAbbreviation { BW, BY, BE, BB, HB, HH, HE, NI, MV, NW, RP, SL, SN, ST, SH, TH, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum GreeceStatesAbbreviation { #[strum(serialize = "13")] AchaeaRegionalUnit, #[strum(serialize = "01")] AetoliaAcarnaniaRegionalUnit, #[strum(serialize = "12")] ArcadiaPrefecture, #[strum(serialize = "11")] ArgolisRegionalUnit, #[strum(serialize = "I")] AtticaRegion, #[strum(serialize = "03")] BoeotiaRegionalUnit, #[strum(serialize = "H")] CentralGreeceRegion, #[strum(serialize = "B")] CentralMacedonia, #[strum(serialize = "94")] ChaniaRegionalUnit, #[strum(serialize = "22")] CorfuPrefecture, #[strum(serialize = "15")] CorinthiaRegionalUnit, #[strum(serialize = "M")] CreteRegion, #[strum(serialize = "52")] DramaRegionalUnit, #[strum(serialize = "A2")] EastAtticaRegionalUnit, #[strum(serialize = "A")] EastMacedoniaAndThrace, #[strum(serialize = "D")] EpirusRegion, #[strum(serialize = "04")] Euboea, #[strum(serialize = "51")] GrevenaPrefecture, #[strum(serialize = "53")] ImathiaRegionalUnit, #[strum(serialize = "33")] IoanninaRegionalUnit, #[strum(serialize = "F")] IonianIslandsRegion, #[strum(serialize = "41")] KarditsaRegionalUnit, #[strum(serialize = "56")] KastoriaRegionalUnit, #[strum(serialize = "23")] KefaloniaPrefecture, #[strum(serialize = "57")] KilkisRegionalUnit, #[strum(serialize = "58")] KozaniPrefecture, #[strum(serialize = "16")] Laconia, #[strum(serialize = "42")] LarissaPrefecture, #[strum(serialize = "24")] LefkadaRegionalUnit, #[strum(serialize = "59")] PellaRegionalUnit, #[strum(serialize = "J")] PeloponneseRegion, #[strum(serialize = "06")] PhthiotisPrefecture, #[strum(serialize = "34")] PrevezaPrefecture, #[strum(serialize = "62")] SerresPrefecture, #[strum(serialize = "L")] SouthAegean, #[strum(serialize = "54")] ThessalonikiRegionalUnit, #[strum(serialize = "G")] WestGreeceRegion, #[strum(serialize = "C")] WestMacedoniaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum HungaryStatesAbbreviation { #[strum(serialize = "BA")] BaranyaCounty, #[strum(serialize = "BZ")] BorsodAbaujZemplenCounty, #[strum(serialize = "BU")] Budapest, #[strum(serialize = "BK")] BacsKiskunCounty, #[strum(serialize = "BE")] BekesCounty, #[strum(serialize = "BC")] Bekescsaba, #[strum(serialize = "CS")] CsongradCounty, #[strum(serialize = "DE")] Debrecen, #[strum(serialize = "DU")] Dunaujvaros, #[strum(serialize = "EG")] Eger, #[strum(serialize = "FE")] FejerCounty, #[strum(serialize = "GY")] Gyor, #[strum(serialize = "GS")] GyorMosonSopronCounty, #[strum(serialize = "HB")] HajduBiharCounty, #[strum(serialize = "HE")] HevesCounty, #[strum(serialize = "HV")] Hodmezovasarhely, #[strum(serialize = "JN")] JaszNagykunSzolnokCounty, #[strum(serialize = "KV")] Kaposvar, #[strum(serialize = "KM")] Kecskemet, #[strum(serialize = "MI")] Miskolc, #[strum(serialize = "NK")] Nagykanizsa, #[strum(serialize = "NY")] Nyiregyhaza, #[strum(serialize = "NO")] NogradCounty, #[strum(serialize = "PE")] PestCounty, #[strum(serialize = "PS")] Pecs, #[strum(serialize = "ST")] Salgotarjan, #[strum(serialize = "SO")] SomogyCounty, #[strum(serialize = "SN")] Sopron, #[strum(serialize = "SZ")] SzabolcsSzatmarBeregCounty, #[strum(serialize = "SD")] Szeged, #[strum(serialize = "SS")] Szekszard, #[strum(serialize = "SK")] Szolnok, #[strum(serialize = "SH")] Szombathely, #[strum(serialize = "SF")] Szekesfehervar, #[strum(serialize = "TB")] Tatabanya, #[strum(serialize = "TO")] TolnaCounty, #[strum(serialize = "VA")] VasCounty, #[strum(serialize = "VM")] Veszprem, #[strum(serialize = "VE")] VeszpremCounty, #[strum(serialize = "ZA")] ZalaCounty, #[strum(serialize = "ZE")] Zalaegerszeg, #[strum(serialize = "ER")] Erd, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IcelandStatesAbbreviation { #[strum(serialize = "1")] CapitalRegion, #[strum(serialize = "7")] EasternRegion, #[strum(serialize = "6")] NortheasternRegion, #[strum(serialize = "5")] NorthwesternRegion, #[strum(serialize = "2")] SouthernPeninsulaRegion, #[strum(serialize = "8")] SouthernRegion, #[strum(serialize = "3")] WesternRegion, #[strum(serialize = "4")] Westfjords, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum IrelandStatesAbbreviation { #[strum(serialize = "C")] Connacht, #[strum(serialize = "CW")] CountyCarlow, #[strum(serialize = "CN")] CountyCavan, #[strum(serialize = "CE")] CountyClare, #[strum(serialize = "CO")] CountyCork, #[strum(serialize = "DL")] CountyDonegal, #[strum(serialize = "D")] CountyDublin, #[strum(serialize = "G")] CountyGalway, #[strum(serialize = "KY")] CountyKerry, #[strum(serialize = "KE")] CountyKildare, #[strum(serialize = "KK")] CountyKilkenny, #[strum(serialize = "LS")] CountyLaois, #[strum(serialize = "LK")] CountyLimerick, #[strum(serialize = "LD")] CountyLongford, #[strum(serialize = "LH")] CountyLouth, #[strum(serialize = "MO")] CountyMayo, #[strum(serialize = "MH")] CountyMeath, #[strum(serialize = "MN")] CountyMonaghan, #[strum(serialize = "OY")] CountyOffaly, #[strum(serialize = "RN")] CountyRoscommon, #[strum(serialize = "SO")] CountySligo, #[strum(serialize = "TA")] CountyTipperary, #[strum(serialize = "WD")] CountyWaterford, #[strum(serialize = "WH")] CountyWestmeath, #[strum(serialize = "WX")] CountyWexford, #[strum(serialize = "WW")] CountyWicklow, #[strum(serialize = "L")] Leinster, #[strum(serialize = "M")] Munster, #[strum(serialize = "U")] Ulster, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LatviaStatesAbbreviation { #[strum(serialize = "001")] AglonaMunicipality, #[strum(serialize = "002")] AizkraukleMunicipality, #[strum(serialize = "003")] AizputeMunicipality, #[strum(serialize = "004")] AknīsteMunicipality, #[strum(serialize = "005")] AlojaMunicipality, #[strum(serialize = "006")] AlsungaMunicipality, #[strum(serialize = "007")] AlūksneMunicipality, #[strum(serialize = "008")] AmataMunicipality, #[strum(serialize = "009")] ApeMunicipality, #[strum(serialize = "010")] AuceMunicipality, #[strum(serialize = "012")] BabīteMunicipality, #[strum(serialize = "013")] BaldoneMunicipality, #[strum(serialize = "014")] BaltinavaMunicipality, #[strum(serialize = "015")] BalviMunicipality, #[strum(serialize = "016")] BauskaMunicipality, #[strum(serialize = "017")] BeverīnaMunicipality, #[strum(serialize = "018")] BrocēniMunicipality, #[strum(serialize = "019")] BurtniekiMunicipality, #[strum(serialize = "020")] CarnikavaMunicipality, #[strum(serialize = "021")] CesvaineMunicipality, #[strum(serialize = "023")] CiblaMunicipality, #[strum(serialize = "022")] CēsisMunicipality, #[strum(serialize = "024")] DagdaMunicipality, #[strum(serialize = "DGV")] Daugavpils, #[strum(serialize = "025")] DaugavpilsMunicipality, #[strum(serialize = "026")] DobeleMunicipality, #[strum(serialize = "027")] DundagaMunicipality, #[strum(serialize = "028")] DurbeMunicipality, #[strum(serialize = "029")] EngureMunicipality, #[strum(serialize = "031")] GarkalneMunicipality, #[strum(serialize = "032")] GrobiņaMunicipality, #[strum(serialize = "033")] GulbeneMunicipality, #[strum(serialize = "034")] IecavaMunicipality, #[strum(serialize = "035")] IkšķileMunicipality, #[strum(serialize = "036")] IlūksteMunicipality, #[strum(serialize = "037")] InčukalnsMunicipality, #[strum(serialize = "038")] JaunjelgavaMunicipality, #[strum(serialize = "039")] JaunpiebalgaMunicipality, #[strum(serialize = "040")] JaunpilsMunicipality, #[strum(serialize = "JEL")] Jelgava, #[strum(serialize = "041")] JelgavaMunicipality, #[strum(serialize = "JKB")] Jēkabpils, #[strum(serialize = "042")] JēkabpilsMunicipality, #[strum(serialize = "JUR")] Jūrmala, #[strum(serialize = "043")] KandavaMunicipality, #[strum(serialize = "045")] KocēniMunicipality, #[strum(serialize = "046")] KokneseMunicipality, #[strum(serialize = "048")] KrimuldaMunicipality, #[strum(serialize = "049")] KrustpilsMunicipality, #[strum(serialize = "047")] KrāslavaMunicipality, #[strum(serialize = "050")] KuldīgaMunicipality, #[strum(serialize = "044")] KārsavaMunicipality, #[strum(serialize = "053")] LielvārdeMunicipality, #[strum(serialize = "LPX")] Liepāja, #[strum(serialize = "054")] LimbažiMunicipality, #[strum(serialize = "057")] LubānaMunicipality, #[strum(serialize = "058")] LudzaMunicipality, #[strum(serialize = "055")] LīgatneMunicipality, #[strum(serialize = "056")] LīvāniMunicipality, #[strum(serialize = "059")] MadonaMunicipality, #[strum(serialize = "060")] MazsalacaMunicipality, #[strum(serialize = "061")] MālpilsMunicipality, #[strum(serialize = "062")] MārupeMunicipality, #[strum(serialize = "063")] MērsragsMunicipality, #[strum(serialize = "064")] NaukšēniMunicipality, #[strum(serialize = "065")] NeretaMunicipality, #[strum(serialize = "066")] NīcaMunicipality, #[strum(serialize = "067")] OgreMunicipality, #[strum(serialize = "068")] OlaineMunicipality, #[strum(serialize = "069")] OzolniekiMunicipality, #[strum(serialize = "073")] PreiļiMunicipality, #[strum(serialize = "074")] PriekuleMunicipality, #[strum(serialize = "075")] PriekuļiMunicipality, #[strum(serialize = "070")] PārgaujaMunicipality, #[strum(serialize = "071")] PāvilostaMunicipality, #[strum(serialize = "072")] PļaviņasMunicipality, #[strum(serialize = "076")] RaunaMunicipality, #[strum(serialize = "078")] RiebiņiMunicipality, #[strum(serialize = "RIX")] Riga, #[strum(serialize = "079")] RojaMunicipality, #[strum(serialize = "080")] RopažiMunicipality, #[strum(serialize = "081")] RucavaMunicipality, #[strum(serialize = "082")] RugājiMunicipality, #[strum(serialize = "083")] RundāleMunicipality, #[strum(serialize = "REZ")] Rēzekne, #[strum(serialize = "077")] RēzekneMunicipality, #[strum(serialize = "084")] RūjienaMunicipality, #[strum(serialize = "085")] SalaMunicipality, #[strum(serialize = "086")] SalacgrīvaMunicipality, #[strum(serialize = "087")] SalaspilsMunicipality, #[strum(serialize = "088")] SaldusMunicipality, #[strum(serialize = "089")] SaulkrastiMunicipality, #[strum(serialize = "091")] SiguldaMunicipality, #[strum(serialize = "093")] SkrundaMunicipality, #[strum(serialize = "092")] SkrīveriMunicipality, #[strum(serialize = "094")] SmilteneMunicipality, #[strum(serialize = "095")] StopiņiMunicipality, #[strum(serialize = "096")] StrenčiMunicipality, #[strum(serialize = "090")] SējaMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum ItalyStatesAbbreviation { #[strum(serialize = "65")] Abruzzo, #[strum(serialize = "23")] AostaValley, #[strum(serialize = "75")] Apulia, #[strum(serialize = "77")] Basilicata, #[strum(serialize = "BN")] BeneventoProvince, #[strum(serialize = "78")] Calabria, #[strum(serialize = "72")] Campania, #[strum(serialize = "45")] EmiliaRomagna, #[strum(serialize = "36")] FriuliVeneziaGiulia, #[strum(serialize = "62")] Lazio, #[strum(serialize = "42")] Liguria, #[strum(serialize = "25")] Lombardy, #[strum(serialize = "57")] Marche, #[strum(serialize = "67")] Molise, #[strum(serialize = "21")] Piedmont, #[strum(serialize = "88")] Sardinia, #[strum(serialize = "82")] Sicily, #[strum(serialize = "32")] TrentinoSouthTyrol, #[strum(serialize = "52")] Tuscany, #[strum(serialize = "55")] Umbria, #[strum(serialize = "34")] Veneto, #[strum(serialize = "AG")] Agrigento, #[strum(serialize = "CL")] Caltanissetta, #[strum(serialize = "EN")] Enna, #[strum(serialize = "RG")] Ragusa, #[strum(serialize = "SR")] Siracusa, #[strum(serialize = "TP")] Trapani, #[strum(serialize = "BA")] Bari, #[strum(serialize = "BO")] Bologna, #[strum(serialize = "CA")] Cagliari, #[strum(serialize = "CT")] Catania, #[strum(serialize = "FI")] Florence, #[strum(serialize = "GE")] Genoa, #[strum(serialize = "ME")] Messina, #[strum(serialize = "MI")] Milan, #[strum(serialize = "NA")] Naples, #[strum(serialize = "PA")] Palermo, #[strum(serialize = "RC")] ReggioCalabria, #[strum(serialize = "RM")] Rome, #[strum(serialize = "TO")] Turin, #[strum(serialize = "VE")] Venice, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LiechtensteinStatesAbbreviation { #[strum(serialize = "01")] Balzers, #[strum(serialize = "02")] Eschen, #[strum(serialize = "03")] Gamprin, #[strum(serialize = "04")] Mauren, #[strum(serialize = "05")] Planken, #[strum(serialize = "06")] Ruggell, #[strum(serialize = "07")] Schaan, #[strum(serialize = "08")] Schellenberg, #[strum(serialize = "09")] Triesen, #[strum(serialize = "10")] Triesenberg, #[strum(serialize = "11")] Vaduz, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LithuaniaStatesAbbreviation { #[strum(serialize = "01")] AkmeneDistrictMunicipality, #[strum(serialize = "02")] AlytusCityMunicipality, #[strum(serialize = "AL")] AlytusCounty, #[strum(serialize = "03")] AlytusDistrictMunicipality, #[strum(serialize = "05")] BirstonasMunicipality, #[strum(serialize = "06")] BirzaiDistrictMunicipality, #[strum(serialize = "07")] DruskininkaiMunicipality, #[strum(serialize = "08")] ElektrenaiMunicipality, #[strum(serialize = "09")] IgnalinaDistrictMunicipality, #[strum(serialize = "10")] JonavaDistrictMunicipality, #[strum(serialize = "11")] JoniskisDistrictMunicipality, #[strum(serialize = "12")] JurbarkasDistrictMunicipality, #[strum(serialize = "13")] KaisiadorysDistrictMunicipality, #[strum(serialize = "14")] KalvarijaMunicipality, #[strum(serialize = "15")] KaunasCityMunicipality, #[strum(serialize = "KU")] KaunasCounty, #[strum(serialize = "16")] KaunasDistrictMunicipality, #[strum(serialize = "17")] KazluRudaMunicipality, #[strum(serialize = "19")] KelmeDistrictMunicipality, #[strum(serialize = "20")] KlaipedaCityMunicipality, #[strum(serialize = "KL")] KlaipedaCounty, #[strum(serialize = "21")] KlaipedaDistrictMunicipality, #[strum(serialize = "22")] KretingaDistrictMunicipality, #[strum(serialize = "23")] KupiskisDistrictMunicipality, #[strum(serialize = "18")] KedainiaiDistrictMunicipality, #[strum(serialize = "24")] LazdijaiDistrictMunicipality, #[strum(serialize = "MR")] MarijampoleCounty, #[strum(serialize = "25")] MarijampoleMunicipality, #[strum(serialize = "26")] MazeikiaiDistrictMunicipality, #[strum(serialize = "27")] MoletaiDistrictMunicipality, #[strum(serialize = "28")] NeringaMunicipality, #[strum(serialize = "29")] PagegiaiMunicipality, #[strum(serialize = "30")] PakruojisDistrictMunicipality, #[strum(serialize = "31")] PalangaCityMunicipality, #[strum(serialize = "32")] PanevezysCityMunicipality, #[strum(serialize = "PN")] PanevezysCounty, #[strum(serialize = "33")] PanevezysDistrictMunicipality, #[strum(serialize = "34")] PasvalysDistrictMunicipality, #[strum(serialize = "35")] PlungeDistrictMunicipality, #[strum(serialize = "36")] PrienaiDistrictMunicipality, #[strum(serialize = "37")] RadviliskisDistrictMunicipality, #[strum(serialize = "38")] RaseiniaiDistrictMunicipality, #[strum(serialize = "39")] RietavasMunicipality, #[strum(serialize = "40")] RokiskisDistrictMunicipality, #[strum(serialize = "48")] SkuodasDistrictMunicipality, #[strum(serialize = "TA")] TaurageCounty, #[strum(serialize = "50")] TaurageDistrictMunicipality, #[strum(serialize = "TE")] TelsiaiCounty, #[strum(serialize = "51")] TelsiaiDistrictMunicipality, #[strum(serialize = "52")] TrakaiDistrictMunicipality, #[strum(serialize = "53")] UkmergeDistrictMunicipality, #[strum(serialize = "UT")] UtenaCounty, #[strum(serialize = "54")] UtenaDistrictMunicipality, #[strum(serialize = "55")] VarenaDistrictMunicipality, #[strum(serialize = "56")] VilkaviskisDistrictMunicipality, #[strum(serialize = "57")] VilniusCityMunicipality, #[strum(serialize = "VL")] VilniusCounty, #[strum(serialize = "58")] VilniusDistrictMunicipality, #[strum(serialize = "59")] VisaginasMunicipality, #[strum(serialize = "60")] ZarasaiDistrictMunicipality, #[strum(serialize = "41")] SakiaiDistrictMunicipality, #[strum(serialize = "42")] SalcininkaiDistrictMunicipality, #[strum(serialize = "43")] SiauliaiCityMunicipality, #[strum(serialize = "SA")] SiauliaiCounty, #[strum(serialize = "44")] SiauliaiDistrictMunicipality, #[strum(serialize = "45")] SilaleDistrictMunicipality, #[strum(serialize = "46")] SiluteDistrictMunicipality, #[strum(serialize = "47")] SirvintosDistrictMunicipality, #[strum(serialize = "49")] SvencionysDistrictMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MaltaStatesAbbreviation { #[strum(serialize = "01")] Attard, #[strum(serialize = "02")] Balzan, #[strum(serialize = "03")] Birgu, #[strum(serialize = "04")] Birkirkara, #[strum(serialize = "05")] Birżebbuġa, #[strum(serialize = "06")] Cospicua, #[strum(serialize = "07")] Dingli, #[strum(serialize = "08")] Fgura, #[strum(serialize = "09")] Floriana, #[strum(serialize = "10")] Fontana, #[strum(serialize = "11")] Gudja, #[strum(serialize = "12")] Gżira, #[strum(serialize = "13")] Għajnsielem, #[strum(serialize = "14")] Għarb, #[strum(serialize = "15")] Għargħur, #[strum(serialize = "16")] Għasri, #[strum(serialize = "17")] Għaxaq, #[strum(serialize = "18")] Ħamrun, #[strum(serialize = "19")] Iklin, #[strum(serialize = "20")] Senglea, #[strum(serialize = "21")] Kalkara, #[strum(serialize = "22")] Kerċem, #[strum(serialize = "23")] Kirkop, #[strum(serialize = "24")] Lija, #[strum(serialize = "25")] Luqa, #[strum(serialize = "26")] Marsa, #[strum(serialize = "27")] Marsaskala, #[strum(serialize = "28")] Marsaxlokk, #[strum(serialize = "29")] Mdina, #[strum(serialize = "30")] Mellieħa, #[strum(serialize = "31")] Mġarr, #[strum(serialize = "32")] Mosta, #[strum(serialize = "33")] Mqabba, #[strum(serialize = "34")] Msida, #[strum(serialize = "35")] Mtarfa, #[strum(serialize = "36")] Munxar, #[strum(serialize = "37")] Nadur, #[strum(serialize = "38")] Naxxar, #[strum(serialize = "39")] Paola, #[strum(serialize = "40")] Pembroke, #[strum(serialize = "41")] Pietà, #[strum(serialize = "42")] Qala, #[strum(serialize = "43")] Qormi, #[strum(serialize = "44")] Qrendi, #[strum(serialize = "45")] Victoria, #[strum(serialize = "46")] Rabat, #[strum(serialize = "48")] StJulians, #[strum(serialize = "49")] SanĠwann, #[strum(serialize = "50")] SaintLawrence, #[strum(serialize = "51")] StPaulsBay, #[strum(serialize = "52")] Sannat, #[strum(serialize = "53")] SantaLuċija, #[strum(serialize = "54")] SantaVenera, #[strum(serialize = "55")] Siġġiewi, #[strum(serialize = "56")] Sliema, #[strum(serialize = "57")] Swieqi, #[strum(serialize = "58")] TaXbiex, #[strum(serialize = "59")] Tarxien, #[strum(serialize = "60")] Valletta, #[strum(serialize = "61")] Xagħra, #[strum(serialize = "62")] Xewkija, #[strum(serialize = "63")] Xgħajra, #[strum(serialize = "64")] Żabbar, #[strum(serialize = "65")] ŻebbuġGozo, #[strum(serialize = "66")] ŻebbuġMalta, #[strum(serialize = "67")] Żejtun, #[strum(serialize = "68")] Żurrieq, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MoldovaStatesAbbreviation { #[strum(serialize = "AN")] AneniiNoiDistrict, #[strum(serialize = "BS")] BasarabeascaDistrict, #[strum(serialize = "BD")] BenderMunicipality, #[strum(serialize = "BR")] BriceniDistrict, #[strum(serialize = "BA")] BălțiMunicipality, #[strum(serialize = "CA")] CahulDistrict, #[strum(serialize = "CT")] CantemirDistrict, #[strum(serialize = "CU")] ChișinăuMunicipality, #[strum(serialize = "CM")] CimișliaDistrict, #[strum(serialize = "CR")] CriuleniDistrict, #[strum(serialize = "CL")] CălărașiDistrict, #[strum(serialize = "CS")] CăușeniDistrict, #[strum(serialize = "DO")] DondușeniDistrict, #[strum(serialize = "DR")] DrochiaDistrict, #[strum(serialize = "DU")] DubăsariDistrict, #[strum(serialize = "ED")] EdinețDistrict, #[strum(serialize = "FL")] FloreștiDistrict, #[strum(serialize = "FA")] FăleștiDistrict, #[strum(serialize = "GA")] Găgăuzia, #[strum(serialize = "GL")] GlodeniDistrict, #[strum(serialize = "HI")] HînceștiDistrict, #[strum(serialize = "IA")] IaloveniDistrict, #[strum(serialize = "NI")] NisporeniDistrict, #[strum(serialize = "OC")] OcnițaDistrict, #[strum(serialize = "OR")] OrheiDistrict, #[strum(serialize = "RE")] RezinaDistrict, #[strum(serialize = "RI")] RîșcaniDistrict, #[strum(serialize = "SO")] SorocaDistrict, #[strum(serialize = "ST")] StrășeniDistrict, #[strum(serialize = "SI")] SîngereiDistrict, #[strum(serialize = "TA")] TaracliaDistrict, #[strum(serialize = "TE")] TeleneștiDistrict, #[strum(serialize = "SN")] TransnistriaAutonomousTerritorialUnit, #[strum(serialize = "UN")] UngheniDistrict, #[strum(serialize = "SD")] ȘoldăneștiDistrict, #[strum(serialize = "SV")] ȘtefanVodăDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MonacoStatesAbbreviation { Monaco, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum MontenegroStatesAbbreviation { #[strum(serialize = "01")] AndrijevicaMunicipality, #[strum(serialize = "02")] BarMunicipality, #[strum(serialize = "03")] BeraneMunicipality, #[strum(serialize = "04")] BijeloPoljeMunicipality, #[strum(serialize = "05")] BudvaMunicipality, #[strum(serialize = "07")] DanilovgradMunicipality, #[strum(serialize = "22")] GusinjeMunicipality, #[strum(serialize = "09")] KolasinMunicipality, #[strum(serialize = "10")] KotorMunicipality, #[strum(serialize = "11")] MojkovacMunicipality, #[strum(serialize = "12")] NiksicMunicipality, #[strum(serialize = "06")] OldRoyalCapitalCetinje, #[strum(serialize = "23")] PetnjicaMunicipality, #[strum(serialize = "13")] PlavMunicipality, #[strum(serialize = "14")] PljevljaMunicipality, #[strum(serialize = "15")] PlužineMunicipality, #[strum(serialize = "16")] PodgoricaMunicipality, #[strum(serialize = "17")] RožajeMunicipality, #[strum(serialize = "19")] TivatMunicipality, #[strum(serialize = "20")] UlcinjMunicipality, #[strum(serialize = "18")] SavnikMunicipality, #[strum(serialize = "21")] ŽabljakMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NetherlandsStatesAbbreviation { #[strum(serialize = "BQ1")] Bonaire, #[strum(serialize = "DR")] Drenthe, #[strum(serialize = "FL")] Flevoland, #[strum(serialize = "FR")] Friesland, #[strum(serialize = "GE")] Gelderland, #[strum(serialize = "GR")] Groningen, #[strum(serialize = "LI")] Limburg, #[strum(serialize = "NB")] NorthBrabant, #[strum(serialize = "NH")] NorthHolland, #[strum(serialize = "OV")] Overijssel, #[strum(serialize = "BQ2")] Saba, #[strum(serialize = "BQ3")] SintEustatius, #[strum(serialize = "ZH")] SouthHolland, #[strum(serialize = "UT")] Utrecht, #[strum(serialize = "ZE")] Zeeland, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorthMacedoniaStatesAbbreviation { #[strum(serialize = "01")] AerodromMunicipality, #[strum(serialize = "02")] AracinovoMunicipality, #[strum(serialize = "03")] BerovoMunicipality, #[strum(serialize = "04")] BitolaMunicipality, #[strum(serialize = "05")] BogdanciMunicipality, #[strum(serialize = "06")] BogovinjeMunicipality, #[strum(serialize = "07")] BosilovoMunicipality, #[strum(serialize = "08")] BrvenicaMunicipality, #[strum(serialize = "09")] ButelMunicipality, #[strum(serialize = "77")] CentarMunicipality, #[strum(serialize = "78")] CentarZupaMunicipality, #[strum(serialize = "22")] DebarcaMunicipality, #[strum(serialize = "23")] DelcevoMunicipality, #[strum(serialize = "25")] DemirHisarMunicipality, #[strum(serialize = "24")] DemirKapijaMunicipality, #[strum(serialize = "26")] DojranMunicipality, #[strum(serialize = "27")] DolneniMunicipality, #[strum(serialize = "28")] DrugovoMunicipality, #[strum(serialize = "17")] GaziBabaMunicipality, #[strum(serialize = "18")] GevgelijaMunicipality, #[strum(serialize = "29")] GjorcePetrovMunicipality, #[strum(serialize = "19")] GostivarMunicipality, #[strum(serialize = "20")] GradskoMunicipality, #[strum(serialize = "85")] GreaterSkopje, #[strum(serialize = "34")] IlindenMunicipality, #[strum(serialize = "35")] JegunovceMunicipality, #[strum(serialize = "37")] Karbinci, #[strum(serialize = "38")] KarposMunicipality, #[strum(serialize = "36")] KavadarciMunicipality, #[strum(serialize = "39")] KiselaVodaMunicipality, #[strum(serialize = "40")] KicevoMunicipality, #[strum(serialize = "41")] KonceMunicipality, #[strum(serialize = "42")] KocaniMunicipality, #[strum(serialize = "43")] KratovoMunicipality, #[strum(serialize = "44")] KrivaPalankaMunicipality, #[strum(serialize = "45")] KrivogastaniMunicipality, #[strum(serialize = "46")] KrusevoMunicipality, #[strum(serialize = "47")] KumanovoMunicipality, #[strum(serialize = "48")] LipkovoMunicipality, #[strum(serialize = "49")] LozovoMunicipality, #[strum(serialize = "51")] MakedonskaKamenicaMunicipality, #[strum(serialize = "52")] MakedonskiBrodMunicipality, #[strum(serialize = "50")] MavrovoAndRostusaMunicipality, #[strum(serialize = "53")] MogilaMunicipality, #[strum(serialize = "54")] NegotinoMunicipality, #[strum(serialize = "55")] NovaciMunicipality, #[strum(serialize = "56")] NovoSeloMunicipality, #[strum(serialize = "58")] OhridMunicipality, #[strum(serialize = "57")] OslomejMunicipality, #[strum(serialize = "60")] PehcevoMunicipality, #[strum(serialize = "59")] PetrovecMunicipality, #[strum(serialize = "61")] PlasnicaMunicipality, #[strum(serialize = "62")] PrilepMunicipality, #[strum(serialize = "63")] ProbishtipMunicipality, #[strum(serialize = "64")] RadovisMunicipality, #[strum(serialize = "65")] RankovceMunicipality, #[strum(serialize = "66")] ResenMunicipality, #[strum(serialize = "67")] RosomanMunicipality, #[strum(serialize = "68")] SarajMunicipality, #[strum(serialize = "70")] SopisteMunicipality, #[strum(serialize = "71")] StaroNagoricaneMunicipality, #[strum(serialize = "72")] StrugaMunicipality, #[strum(serialize = "73")] StrumicaMunicipality, #[strum(serialize = "74")] StudenicaniMunicipality, #[strum(serialize = "69")] SvetiNikoleMunicipality, #[strum(serialize = "75")] TearceMunicipality, #[strum(serialize = "76")] TetovoMunicipality, #[strum(serialize = "10")] ValandovoMunicipality, #[strum(serialize = "11")] VasilevoMunicipality, #[strum(serialize = "13")] VelesMunicipality, #[strum(serialize = "12")] VevcaniMunicipality, #[strum(serialize = "14")] VinicaMunicipality, #[strum(serialize = "15")] VranesticaMunicipality, #[strum(serialize = "16")] VrapcisteMunicipality, #[strum(serialize = "31")] ZajasMunicipality, #[strum(serialize = "32")] ZelenikovoMunicipality, #[strum(serialize = "33")] ZrnovciMunicipality, #[strum(serialize = "79")] CairMunicipality, #[strum(serialize = "80")] CaskaMunicipality, #[strum(serialize = "81")] CesinovoOblesevoMunicipality, #[strum(serialize = "82")] CucerSandevoMunicipality, #[strum(serialize = "83")] StipMunicipality, #[strum(serialize = "84")] ShutoOrizariMunicipality, #[strum(serialize = "30")] ZelinoMunicipality, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum NorwayStatesAbbreviation { #[strum(serialize = "02")] Akershus, #[strum(serialize = "06")] Buskerud, #[strum(serialize = "20")] Finnmark, #[strum(serialize = "04")] Hedmark, #[strum(serialize = "12")] Hordaland, #[strum(serialize = "22")] JanMayen, #[strum(serialize = "15")] MoreOgRomsdal, #[strum(serialize = "17")] NordTrondelag, #[strum(serialize = "18")] Nordland, #[strum(serialize = "05")] Oppland, #[strum(serialize = "03")] Oslo, #[strum(serialize = "11")] Rogaland, #[strum(serialize = "14")] SognOgFjordane, #[strum(serialize = "21")] Svalbard, #[strum(serialize = "16")] SorTrondelag, #[strum(serialize = "08")] Telemark, #[strum(serialize = "19")] Troms, #[strum(serialize = "50")] Trondelag, #[strum(serialize = "10")] VestAgder, #[strum(serialize = "07")] Vestfold, #[strum(serialize = "01")] Ostfold, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PolandStatesAbbreviation { #[strum(serialize = "30")] GreaterPoland, #[strum(serialize = "26")] HolyCross, #[strum(serialize = "04")] KuyaviaPomerania, #[strum(serialize = "12")] LesserPoland, #[strum(serialize = "02")] LowerSilesia, #[strum(serialize = "06")] Lublin, #[strum(serialize = "08")] Lubusz, #[strum(serialize = "10")] Łódź, #[strum(serialize = "14")] Mazovia, #[strum(serialize = "20")] Podlaskie, #[strum(serialize = "22")] Pomerania, #[strum(serialize = "24")] Silesia, #[strum(serialize = "18")] Subcarpathia, #[strum(serialize = "16")] UpperSilesia, #[strum(serialize = "28")] WarmiaMasuria, #[strum(serialize = "32")] WestPomerania, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum PortugalStatesAbbreviation { #[strum(serialize = "01")] AveiroDistrict, #[strum(serialize = "20")] Azores, #[strum(serialize = "02")] BejaDistrict, #[strum(serialize = "03")] BragaDistrict, #[strum(serialize = "04")] BragancaDistrict, #[strum(serialize = "05")] CasteloBrancoDistrict, #[strum(serialize = "06")] CoimbraDistrict, #[strum(serialize = "08")] FaroDistrict, #[strum(serialize = "09")] GuardaDistrict, #[strum(serialize = "10")] LeiriaDistrict, #[strum(serialize = "11")] LisbonDistrict, #[strum(serialize = "30")] Madeira, #[strum(serialize = "12")] PortalegreDistrict, #[strum(serialize = "13")] PortoDistrict, #[strum(serialize = "14")] SantaremDistrict, #[strum(serialize = "15")] SetubalDistrict, #[strum(serialize = "16")] VianaDoCasteloDistrict, #[strum(serialize = "17")] VilaRealDistrict, #[strum(serialize = "18")] ViseuDistrict, #[strum(serialize = "07")] EvoraDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SpainStatesAbbreviation { #[strum(serialize = "C")] ACorunaProvince, #[strum(serialize = "AB")] AlbaceteProvince, #[strum(serialize = "A")] AlicanteProvince, #[strum(serialize = "AL")] AlmeriaProvince, #[strum(serialize = "AN")] Andalusia, #[strum(serialize = "VI")] ArabaAlava, #[strum(serialize = "AR")] Aragon, #[strum(serialize = "BA")] BadajozProvince, #[strum(serialize = "PM")] BalearicIslands, #[strum(serialize = "B")] BarcelonaProvince, #[strum(serialize = "PV")] BasqueCountry, #[strum(serialize = "BI")] Biscay, #[strum(serialize = "BU")] BurgosProvince, #[strum(serialize = "CN")] CanaryIslands, #[strum(serialize = "S")] Cantabria, #[strum(serialize = "CS")] CastellonProvince, #[strum(serialize = "CL")] CastileAndLeon, #[strum(serialize = "CM")] CastileLaMancha, #[strum(serialize = "CT")] Catalonia, #[strum(serialize = "CE")] Ceuta, #[strum(serialize = "CR")] CiudadRealProvince, #[strum(serialize = "MD")] CommunityOfMadrid, #[strum(serialize = "CU")] CuencaProvince, #[strum(serialize = "CC")] CaceresProvince, #[strum(serialize = "CA")] CadizProvince, #[strum(serialize = "CO")] CordobaProvince, #[strum(serialize = "EX")] Extremadura, #[strum(serialize = "GA")] Galicia, #[strum(serialize = "SS")] Gipuzkoa, #[strum(serialize = "GI")] GironaProvince, #[strum(serialize = "GR")] GranadaProvince, #[strum(serialize = "GU")] GuadalajaraProvince, #[strum(serialize = "H")] HuelvaProvince, #[strum(serialize = "HU")] HuescaProvince, #[strum(serialize = "J")] JaenProvince, #[strum(serialize = "RI")] LaRioja, #[strum(serialize = "GC")] LasPalmasProvince, #[strum(serialize = "LE")] LeonProvince, #[strum(serialize = "L")] LleidaProvince, #[strum(serialize = "LU")] LugoProvince, #[strum(serialize = "M")] MadridProvince, #[strum(serialize = "ML")] Melilla, #[strum(serialize = "MU")] MurciaProvince, #[strum(serialize = "MA")] MalagaProvince, #[strum(serialize = "NC")] Navarre, #[strum(serialize = "OR")] OurenseProvince, #[strum(serialize = "P")] PalenciaProvince, #[strum(serialize = "PO")] PontevedraProvince, #[strum(serialize = "O")] ProvinceOfAsturias, #[strum(serialize = "AV")] ProvinceOfAvila, #[strum(serialize = "MC")] RegionOfMurcia, #[strum(serialize = "SA")] SalamancaProvince, #[strum(serialize = "TF")] SantaCruzDeTenerifeProvince, #[strum(serialize = "SG")] SegoviaProvince, #[strum(serialize = "SE")] SevilleProvince, #[strum(serialize = "SO")] SoriaProvince, #[strum(serialize = "T")] TarragonaProvince, #[strum(serialize = "TE")] TeruelProvince, #[strum(serialize = "TO")] ToledoProvince, #[strum(serialize = "V")] ValenciaProvince, #[strum(serialize = "VC")] ValencianCommunity, #[strum(serialize = "VA")] ValladolidProvince, #[strum(serialize = "ZA")] ZamoraProvince, #[strum(serialize = "Z")] ZaragozaProvince, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwitzerlandStatesAbbreviation { #[strum(serialize = "AG")] Aargau, #[strum(serialize = "AR")] AppenzellAusserrhoden, #[strum(serialize = "AI")] AppenzellInnerrhoden, #[strum(serialize = "BL")] BaselLandschaft, #[strum(serialize = "FR")] CantonOfFribourg, #[strum(serialize = "GE")] CantonOfGeneva, #[strum(serialize = "JU")] CantonOfJura, #[strum(serialize = "LU")] CantonOfLucerne, #[strum(serialize = "NE")] CantonOfNeuchatel, #[strum(serialize = "SH")] CantonOfSchaffhausen, #[strum(serialize = "SO")] CantonOfSolothurn, #[strum(serialize = "SG")] CantonOfStGallen, #[strum(serialize = "VS")] CantonOfValais, #[strum(serialize = "VD")] CantonOfVaud, #[strum(serialize = "ZG")] CantonOfZug, #[strum(serialize = "GL")] Glarus, #[strum(serialize = "GR")] Graubunden, #[strum(serialize = "NW")] Nidwalden, #[strum(serialize = "OW")] Obwalden, #[strum(serialize = "SZ")] Schwyz, #[strum(serialize = "TG")] Thurgau, #[strum(serialize = "TI")] Ticino, #[strum(serialize = "UR")] Uri, #[strum(serialize = "BE")] CantonOfBern, #[strum(serialize = "ZH")] CantonOfZurich, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UnitedKingdomStatesAbbreviation { #[strum(serialize = "ABE")] Aberdeen, #[strum(serialize = "ABD")] Aberdeenshire, #[strum(serialize = "ANS")] Angus, #[strum(serialize = "ANT")] Antrim, #[strum(serialize = "ANN")] AntrimAndNewtownabbey, #[strum(serialize = "ARD")] Ards, #[strum(serialize = "AND")] ArdsAndNorthDown, #[strum(serialize = "AGB")] ArgyllAndBute, #[strum(serialize = "ARM")] ArmaghCityAndDistrictCouncil, #[strum(serialize = "ABC")] ArmaghBanbridgeAndCraigavon, #[strum(serialize = "SH-AC")] AscensionIsland, #[strum(serialize = "BLA")] BallymenaBorough, #[strum(serialize = "BLY")] Ballymoney, #[strum(serialize = "BNB")] Banbridge, #[strum(serialize = "BNS")] Barnsley, #[strum(serialize = "BAS")] BathAndNorthEastSomerset, #[strum(serialize = "BDF")] Bedford, #[strum(serialize = "BFS")] BelfastDistrict, #[strum(serialize = "BIR")] Birmingham, #[strum(serialize = "BBD")] BlackburnWithDarwen, #[strum(serialize = "BPL")] Blackpool, #[strum(serialize = "BGW")] BlaenauGwentCountyBorough, #[strum(serialize = "BOL")] Bolton, #[strum(serialize = "BMH")] Bournemouth, #[strum(serialize = "BRC")] BracknellForest, #[strum(serialize = "BRD")] Bradford, #[strum(serialize = "BGE")] BridgendCountyBorough, #[strum(serialize = "BNH")] BrightonAndHove, #[strum(serialize = "BKM")] Buckinghamshire, #[strum(serialize = "BUR")] Bury, #[strum(serialize = "CAY")] CaerphillyCountyBorough, #[strum(serialize = "CLD")] Calderdale, #[strum(serialize = "CAM")] Cambridgeshire, #[strum(serialize = "CMN")] Carmarthenshire, #[strum(serialize = "CKF")] CarrickfergusBoroughCouncil, #[strum(serialize = "CSR")] Castlereagh, #[strum(serialize = "CCG")] CausewayCoastAndGlens, #[strum(serialize = "CBF")] CentralBedfordshire, #[strum(serialize = "CGN")] Ceredigion, #[strum(serialize = "CHE")] CheshireEast, #[strum(serialize = "CHW")] CheshireWestAndChester, #[strum(serialize = "CRF")] CityAndCountyOfCardiff, #[strum(serialize = "SWA")] CityAndCountyOfSwansea, #[strum(serialize = "BST")] CityOfBristol, #[strum(serialize = "DER")] CityOfDerby, #[strum(serialize = "KHL")] CityOfKingstonUponHull, #[strum(serialize = "LCE")] CityOfLeicester, #[strum(serialize = "LND")] CityOfLondon, #[strum(serialize = "NGM")] CityOfNottingham, #[strum(serialize = "PTE")] CityOfPeterborough, #[strum(serialize = "PLY")] CityOfPlymouth, #[strum(serialize = "POR")] CityOfPortsmouth, #[strum(serialize = "STH")] CityOfSouthampton, #[strum(serialize = "STE")] CityOfStokeOnTrent, #[strum(serialize = "SND")] CityOfSunderland, #[strum(serialize = "WSM")] CityOfWestminster, #[strum(serialize = "WLV")] CityOfWolverhampton, #[strum(serialize = "YOR")] CityOfYork, #[strum(serialize = "CLK")] Clackmannanshire, #[strum(serialize = "CLR")] ColeraineBoroughCouncil, #[strum(serialize = "CWY")] ConwyCountyBorough, #[strum(serialize = "CKT")] CookstownDistrictCouncil, #[strum(serialize = "CON")] Cornwall, #[strum(serialize = "DUR")] CountyDurham, #[strum(serialize = "COV")] Coventry, #[strum(serialize = "CGV")] CraigavonBoroughCouncil, #[strum(serialize = "CMA")] Cumbria, #[strum(serialize = "DAL")] Darlington, #[strum(serialize = "DEN")] Denbighshire, #[strum(serialize = "DBY")] Derbyshire, #[strum(serialize = "DRS")] DerryCityAndStrabane, #[strum(serialize = "DRY")] DerryCityCouncil, #[strum(serialize = "DEV")] Devon, #[strum(serialize = "DNC")] Doncaster, #[strum(serialize = "DOR")] Dorset, #[strum(serialize = "DOW")] DownDistrictCouncil, #[strum(serialize = "DUD")] Dudley, #[strum(serialize = "DGY")] DumfriesAndGalloway, #[strum(serialize = "DND")] Dundee, #[strum(serialize = "DGN")] DungannonAndSouthTyroneBoroughCouncil, #[strum(serialize = "EAY")] EastAyrshire, #[strum(serialize = "EDU")] EastDunbartonshire, #[strum(serialize = "ELN")] EastLothian, #[strum(serialize = "ERW")] EastRenfrewshire, #[strum(serialize = "ERY")] EastRidingOfYorkshire, #[strum(serialize = "ESX")] EastSussex, #[strum(serialize = "EDH")] Edinburgh, #[strum(serialize = "ENG")] England, #[strum(serialize = "ESS")] Essex, #[strum(serialize = "FAL")] Falkirk, #[strum(serialize = "FMO")] FermanaghAndOmagh, #[strum(serialize = "FER")] FermanaghDistrictCouncil, #[strum(serialize = "FIF")] Fife, #[strum(serialize = "FLN")] Flintshire, #[strum(serialize = "GAT")] Gateshead, #[strum(serialize = "GLG")] Glasgow, #[strum(serialize = "GLS")] Gloucestershire, #[strum(serialize = "GWN")] Gwynedd, #[strum(serialize = "HAL")] Halton, #[strum(serialize = "HAM")] Hampshire, #[strum(serialize = "HPL")] Hartlepool, #[strum(serialize = "HEF")] Herefordshire, #[strum(serialize = "HRT")] Hertfordshire, #[strum(serialize = "HLD")] Highland, #[strum(serialize = "IVC")] Inverclyde, #[strum(serialize = "IOW")] IsleOfWight, #[strum(serialize = "IOS")] IslesOfScilly, #[strum(serialize = "KEN")] Kent, #[strum(serialize = "KIR")] Kirklees, #[strum(serialize = "KWL")] Knowsley, #[strum(serialize = "LAN")] Lancashire, #[strum(serialize = "LRN")] LarneBoroughCouncil, #[strum(serialize = "LDS")] Leeds, #[strum(serialize = "LEC")] Leicestershire, #[strum(serialize = "LMV")] LimavadyBoroughCouncil, #[strum(serialize = "LIN")] Lincolnshire, #[strum(serialize = "LBC")] LisburnAndCastlereagh, #[strum(serialize = "LSB")] LisburnCityCouncil, #[strum(serialize = "LIV")] Liverpool, #[strum(serialize = "BDG")] LondonBoroughOfBarkingAndDagenham, #[strum(serialize = "BNE")] LondonBoroughOfBarnet, #[strum(serialize = "BEX")] LondonBoroughOfBexley, #[strum(serialize = "BEN")] LondonBoroughOfBrent, #[strum(serialize = "BRY")] LondonBoroughOfBromley, #[strum(serialize = "CMD")] LondonBoroughOfCamden, #[strum(serialize = "CRY")] LondonBoroughOfCroydon, #[strum(serialize = "EAL")] LondonBoroughOfEaling, #[strum(serialize = "ENF")] LondonBoroughOfEnfield, #[strum(serialize = "HCK")] LondonBoroughOfHackney, #[strum(serialize = "HMF")] LondonBoroughOfHammersmithAndFulham, #[strum(serialize = "HRY")] LondonBoroughOfHaringey, #[strum(serialize = "HRW")] LondonBoroughOfHarrow, #[strum(serialize = "HAV")] LondonBoroughOfHavering, #[strum(serialize = "HIL")] LondonBoroughOfHillingdon, #[strum(serialize = "HNS")] LondonBoroughOfHounslow, #[strum(serialize = "ISL")] LondonBoroughOfIslington, #[strum(serialize = "LBH")] LondonBoroughOfLambeth, #[strum(serialize = "LEW")] LondonBoroughOfLewisham, #[strum(serialize = "MRT")] LondonBoroughOfMerton, #[strum(serialize = "NWM")] LondonBoroughOfNewham, #[strum(serialize = "RDB")] LondonBoroughOfRedbridge, #[strum(serialize = "RIC")] LondonBoroughOfRichmondUponThames, #[strum(serialize = "SWK")] LondonBoroughOfSouthwark, #[strum(serialize = "STN")] LondonBoroughOfSutton, #[strum(serialize = "TWH")] LondonBoroughOfTowerHamlets, #[strum(serialize = "WFT")] LondonBoroughOfWalthamForest, #[strum(serialize = "WND")] LondonBoroughOfWandsworth, #[strum(serialize = "MFT")] MagherafeltDistrictCouncil, #[strum(serialize = "MAN")] Manchester, #[strum(serialize = "MDW")] Medway, #[strum(serialize = "MTY")] MerthyrTydfilCountyBorough, #[strum(serialize = "WGN")] MetropolitanBoroughOfWigan, #[strum(serialize = "MEA")] MidAndEastAntrim, #[strum(serialize = "MUL")] MidUlster, #[strum(serialize = "MDB")] Middlesbrough, #[strum(serialize = "MLN")] Midlothian, #[strum(serialize = "MIK")] MiltonKeynes, #[strum(serialize = "MON")] Monmouthshire, #[strum(serialize = "MRY")] Moray, #[strum(serialize = "MYL")] MoyleDistrictCouncil, #[strum(serialize = "NTL")] NeathPortTalbotCountyBorough, #[strum(serialize = "NET")] NewcastleUponTyne, #[strum(serialize = "NWP")] Newport, #[strum(serialize = "NYM")] NewryAndMourneDistrictCouncil, #[strum(serialize = "NMD")] NewryMourneAndDown, #[strum(serialize = "NTA")] NewtownabbeyBoroughCouncil, #[strum(serialize = "NFK")] Norfolk, #[strum(serialize = "NAY")] NorthAyrshire, #[strum(serialize = "NDN")] NorthDownBoroughCouncil, #[strum(serialize = "NEL")] NorthEastLincolnshire, #[strum(serialize = "NLK")] NorthLanarkshire, #[strum(serialize = "NLN")] NorthLincolnshire, #[strum(serialize = "NSM")] NorthSomerset, #[strum(serialize = "NTY")] NorthTyneside, #[strum(serialize = "NYK")] NorthYorkshire, #[strum(serialize = "NTH")] Northamptonshire, #[strum(serialize = "NIR")] NorthernIreland, #[strum(serialize = "NBL")] Northumberland, #[strum(serialize = "NTT")] Nottinghamshire, #[strum(serialize = "OLD")] Oldham, #[strum(serialize = "OMH")] OmaghDistrictCouncil, #[strum(serialize = "ORK")] OrkneyIslands, #[strum(serialize = "ELS")] OuterHebrides, #[strum(serialize = "OXF")] Oxfordshire, #[strum(serialize = "PEM")] Pembrokeshire, #[strum(serialize = "PKN")] PerthAndKinross, #[strum(serialize = "POL")] Poole, #[strum(serialize = "POW")] Powys, #[strum(serialize = "RDG")] Reading, #[strum(serialize = "RCC")] RedcarAndCleveland, #[strum(serialize = "RFW")] Renfrewshire, #[strum(serialize = "RCT")] RhonddaCynonTaf, #[strum(serialize = "RCH")] Rochdale, #[strum(serialize = "ROT")] Rotherham, #[strum(serialize = "GRE")] RoyalBoroughOfGreenwich, #[strum(serialize = "KEC")] RoyalBoroughOfKensingtonAndChelsea, #[strum(serialize = "KTT")] RoyalBoroughOfKingstonUponThames, #[strum(serialize = "RUT")] Rutland, #[strum(serialize = "SH-HL")] SaintHelena, #[strum(serialize = "SLF")] Salford, #[strum(serialize = "SAW")] Sandwell, #[strum(serialize = "SCT")] Scotland, #[strum(serialize = "SCB")] ScottishBorders, #[strum(serialize = "SFT")] Sefton, #[strum(serialize = "SHF")] Sheffield, #[strum(serialize = "ZET")] ShetlandIslands, #[strum(serialize = "SHR")] Shropshire, #[strum(serialize = "SLG")] Slough, #[strum(serialize = "SOL")] Solihull, #[strum(serialize = "SOM")] Somerset, #[strum(serialize = "SAY")] SouthAyrshire, #[strum(serialize = "SGC")] SouthGloucestershire, #[strum(serialize = "SLK")] SouthLanarkshire, #[strum(serialize = "STY")] SouthTyneside, #[strum(serialize = "SOS")] SouthendOnSea, #[strum(serialize = "SHN")] StHelens, #[strum(serialize = "STS")] Staffordshire, #[strum(serialize = "STG")] Stirling, #[strum(serialize = "SKP")] Stockport, #[strum(serialize = "STT")] StocktonOnTees, #[strum(serialize = "STB")] StrabaneDistrictCouncil, #[strum(serialize = "SFK")] Suffolk, #[strum(serialize = "SRY")] Surrey, #[strum(serialize = "SWD")] Swindon, #[strum(serialize = "TAM")] Tameside, #[strum(serialize = "TFW")] TelfordAndWrekin, #[strum(serialize = "THR")] Thurrock, #[strum(serialize = "TOB")] Torbay, #[strum(serialize = "TOF")] Torfaen, #[strum(serialize = "TRF")] Trafford, #[strum(serialize = "UKM")] UnitedKingdom, #[strum(serialize = "VGL")] ValeOfGlamorgan, #[strum(serialize = "WKF")] Wakefield, #[strum(serialize = "WLS")] Wales, #[strum(serialize = "WLL")] Walsall, #[strum(serialize = "WRT")] Warrington, #[strum(serialize = "WAR")] Warwickshire, #[strum(serialize = "WBK")] WestBerkshire, #[strum(serialize = "WDU")] WestDunbartonshire, #[strum(serialize = "WLN")] WestLothian, #[strum(serialize = "WSX")] WestSussex, #[strum(serialize = "WIL")] Wiltshire, #[strum(serialize = "WNM")] WindsorAndMaidenhead, #[strum(serialize = "WRL")] Wirral, #[strum(serialize = "WOK")] Wokingham, #[strum(serialize = "WOR")] Worcestershire, #[strum(serialize = "WRX")] WrexhamCountyBorough, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BelgiumStatesAbbreviation { #[strum(serialize = "VAN")] Antwerp, #[strum(serialize = "BRU")] BrusselsCapitalRegion, #[strum(serialize = "VOV")] EastFlanders, #[strum(serialize = "VLG")] Flanders, #[strum(serialize = "VBR")] FlemishBrabant, #[strum(serialize = "WHT")] Hainaut, #[strum(serialize = "VLI")] Limburg, #[strum(serialize = "WLG")] Liege, #[strum(serialize = "WLX")] Luxembourg, #[strum(serialize = "WNA")] Namur, #[strum(serialize = "WAL")] Wallonia, #[strum(serialize = "WBR")] WalloonBrabant, #[strum(serialize = "VWV")] WestFlanders, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum LuxembourgStatesAbbreviation { #[strum(serialize = "CA")] CantonOfCapellen, #[strum(serialize = "CL")] CantonOfClervaux, #[strum(serialize = "DI")] CantonOfDiekirch, #[strum(serialize = "EC")] CantonOfEchternach, #[strum(serialize = "ES")] CantonOfEschSurAlzette, #[strum(serialize = "GR")] CantonOfGrevenmacher, #[strum(serialize = "LU")] CantonOfLuxembourg, #[strum(serialize = "ME")] CantonOfMersch, #[strum(serialize = "RD")] CantonOfRedange, #[strum(serialize = "RM")] CantonOfRemich, #[strum(serialize = "VD")] CantonOfVianden, #[strum(serialize = "WI")] CantonOfWiltz, #[strum(serialize = "D")] DiekirchDistrict, #[strum(serialize = "G")] GrevenmacherDistrict, #[strum(serialize = "L")] LuxembourgDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RussiaStatesAbbreviation { #[strum(serialize = "ALT")] AltaiKrai, #[strum(serialize = "AL")] AltaiRepublic, #[strum(serialize = "AMU")] AmurOblast, #[strum(serialize = "ARK")] Arkhangelsk, #[strum(serialize = "AST")] AstrakhanOblast, #[strum(serialize = "BEL")] BelgorodOblast, #[strum(serialize = "BRY")] BryanskOblast, #[strum(serialize = "CE")] ChechenRepublic, #[strum(serialize = "CHE")] ChelyabinskOblast, #[strum(serialize = "CHU")] ChukotkaAutonomousOkrug, #[strum(serialize = "CU")] ChuvashRepublic, #[strum(serialize = "IRK")] Irkutsk, #[strum(serialize = "IVA")] IvanovoOblast, #[strum(serialize = "YEV")] JewishAutonomousOblast, #[strum(serialize = "KB")] KabardinoBalkarRepublic, #[strum(serialize = "KGD")] Kaliningrad, #[strum(serialize = "KLU")] KalugaOblast, #[strum(serialize = "KAM")] KamchatkaKrai, #[strum(serialize = "KC")] KarachayCherkessRepublic, #[strum(serialize = "KEM")] KemerovoOblast, #[strum(serialize = "KHA")] KhabarovskKrai, #[strum(serialize = "KHM")] KhantyMansiAutonomousOkrug, #[strum(serialize = "KIR")] KirovOblast, #[strum(serialize = "KO")] KomiRepublic, #[strum(serialize = "KOS")] KostromaOblast, #[strum(serialize = "KDA")] KrasnodarKrai, #[strum(serialize = "KYA")] KrasnoyarskKrai, #[strum(serialize = "KGN")] KurganOblast, #[strum(serialize = "KRS")] KurskOblast, #[strum(serialize = "LEN")] LeningradOblast, #[strum(serialize = "LIP")] LipetskOblast, #[strum(serialize = "MAG")] MagadanOblast, #[strum(serialize = "ME")] MariElRepublic, #[strum(serialize = "MOW")] Moscow, #[strum(serialize = "MOS")] MoscowOblast, #[strum(serialize = "MUR")] MurmanskOblast, #[strum(serialize = "NEN")] NenetsAutonomousOkrug, #[strum(serialize = "NIZ")] NizhnyNovgorodOblast, #[strum(serialize = "NGR")] NovgorodOblast, #[strum(serialize = "NVS")] Novosibirsk, #[strum(serialize = "OMS")] OmskOblast, #[strum(serialize = "ORE")] OrenburgOblast, #[strum(serialize = "ORL")] OryolOblast, #[strum(serialize = "PNZ")] PenzaOblast, #[strum(serialize = "PER")] PermKrai, #[strum(serialize = "PRI")] PrimorskyKrai, #[strum(serialize = "PSK")] PskovOblast, #[strum(serialize = "AD")] RepublicOfAdygea, #[strum(serialize = "BA")] RepublicOfBashkortostan, #[strum(serialize = "BU")] RepublicOfBuryatia, #[strum(serialize = "DA")] RepublicOfDagestan, #[strum(serialize = "IN")] RepublicOfIngushetia, #[strum(serialize = "KL")] RepublicOfKalmykia, #[strum(serialize = "KR")] RepublicOfKarelia, #[strum(serialize = "KK")] RepublicOfKhakassia, #[strum(serialize = "MO")] RepublicOfMordovia, #[strum(serialize = "SE")] RepublicOfNorthOssetiaAlania, #[strum(serialize = "TA")] RepublicOfTatarstan, #[strum(serialize = "ROS")] RostovOblast, #[strum(serialize = "RYA")] RyazanOblast, #[strum(serialize = "SPE")] SaintPetersburg, #[strum(serialize = "SA")] SakhaRepublic, #[strum(serialize = "SAK")] Sakhalin, #[strum(serialize = "SAM")] SamaraOblast, #[strum(serialize = "SAR")] SaratovOblast, #[strum(serialize = "UA-40")] Sevastopol, #[strum(serialize = "SMO")] SmolenskOblast, #[strum(serialize = "STA")] StavropolKrai, #[strum(serialize = "SVE")] Sverdlovsk, #[strum(serialize = "TAM")] TambovOblast, #[strum(serialize = "TOM")] TomskOblast, #[strum(serialize = "TUL")] TulaOblast, #[strum(serialize = "TY")] TuvaRepublic, #[strum(serialize = "TVE")] TverOblast, #[strum(serialize = "TYU")] TyumenOblast, #[strum(serialize = "UD")] UdmurtRepublic, #[strum(serialize = "ULY")] UlyanovskOblast, #[strum(serialize = "VLA")] VladimirOblast, #[strum(serialize = "VLG")] VologdaOblast, #[strum(serialize = "VOR")] VoronezhOblast, #[strum(serialize = "YAN")] YamaloNenetsAutonomousOkrug, #[strum(serialize = "YAR")] YaroslavlOblast, #[strum(serialize = "ZAB")] ZabaykalskyKrai, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SanMarinoStatesAbbreviation { #[strum(serialize = "01")] Acquaviva, #[strum(serialize = "06")] BorgoMaggiore, #[strum(serialize = "02")] Chiesanuova, #[strum(serialize = "03")] Domagnano, #[strum(serialize = "04")] Faetano, #[strum(serialize = "05")] Fiorentino, #[strum(serialize = "08")] Montegiardino, #[strum(serialize = "07")] SanMarino, #[strum(serialize = "09")] Serravalle, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SerbiaStatesAbbreviation { #[strum(serialize = "00")] Belgrade, #[strum(serialize = "01")] BorDistrict, #[strum(serialize = "02")] BraničevoDistrict, #[strum(serialize = "03")] CentralBanatDistrict, #[strum(serialize = "04")] JablanicaDistrict, #[strum(serialize = "05")] KolubaraDistrict, #[strum(serialize = "06")] MačvaDistrict, #[strum(serialize = "07")] MoravicaDistrict, #[strum(serialize = "08")] NišavaDistrict, #[strum(serialize = "09")] NorthBanatDistrict, #[strum(serialize = "10")] NorthBačkaDistrict, #[strum(serialize = "11")] PirotDistrict, #[strum(serialize = "12")] PodunavljeDistrict, #[strum(serialize = "13")] PomoravljeDistrict, #[strum(serialize = "14")] PčinjaDistrict, #[strum(serialize = "15")] RasinaDistrict, #[strum(serialize = "16")] RaškaDistrict, #[strum(serialize = "17")] SouthBanatDistrict, #[strum(serialize = "18")] SouthBačkaDistrict, #[strum(serialize = "19")] SremDistrict, #[strum(serialize = "20")] ToplicaDistrict, #[strum(serialize = "21")] Vojvodina, #[strum(serialize = "22")] WestBačkaDistrict, #[strum(serialize = "23")] ZaječarDistrict, #[strum(serialize = "24")] ZlatiborDistrict, #[strum(serialize = "25")] ŠumadijaDistrict, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SlovakiaStatesAbbreviation { #[strum(serialize = "BC")] BanskaBystricaRegion, #[strum(serialize = "BL")] BratislavaRegion, #[strum(serialize = "KI")] KosiceRegion, #[strum(serialize = "NI")] NitraRegion, #[strum(serialize = "PV")] PresovRegion, #[strum(serialize = "TC")] TrencinRegion, #[strum(serialize = "TA")] TrnavaRegion, #[strum(serialize = "ZI")] ZilinaRegion, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SloveniaStatesAbbreviation { #[strum(serialize = "001")] Ajdovščina, #[strum(serialize = "213")] Ankaran, #[strum(serialize = "002")] Beltinci, #[strum(serialize = "148")] Benedikt, #[strum(serialize = "149")] BistricaObSotli, #[strum(serialize = "003")] Bled, #[strum(serialize = "150")] Bloke, #[strum(serialize = "004")] Bohinj, #[strum(serialize = "005")] Borovnica, #[strum(serialize = "006")] Bovec, #[strum(serialize = "151")] Braslovče, #[strum(serialize = "007")] Brda, #[strum(serialize = "008")] Brezovica, #[strum(serialize = "009")] Brežice, #[strum(serialize = "152")] Cankova, #[strum(serialize = "012")] CerkljeNaGorenjskem, #[strum(serialize = "013")] Cerknica, #[strum(serialize = "014")] Cerkno, #[strum(serialize = "153")] Cerkvenjak, #[strum(serialize = "011")] CityMunicipalityOfCelje, #[strum(serialize = "085")] CityMunicipalityOfNovoMesto, #[strum(serialize = "018")] Destrnik, #[strum(serialize = "019")] Divača, #[strum(serialize = "154")] Dobje, #[strum(serialize = "020")] Dobrepolje, #[strum(serialize = "155")] Dobrna, #[strum(serialize = "021")] DobrovaPolhovGradec, #[strum(serialize = "156")] Dobrovnik, #[strum(serialize = "022")] DolPriLjubljani, #[strum(serialize = "157")] DolenjskeToplice, #[strum(serialize = "023")] Domžale, #[strum(serialize = "024")] Dornava, #[strum(serialize = "025")] Dravograd, #[strum(serialize = "026")] Duplek, #[strum(serialize = "027")] GorenjaVasPoljane, #[strum(serialize = "028")] Gorišnica, #[strum(serialize = "207")] Gorje, #[strum(serialize = "029")] GornjaRadgona, #[strum(serialize = "030")] GornjiGrad, #[strum(serialize = "031")] GornjiPetrovci, #[strum(serialize = "158")] Grad, #[strum(serialize = "032")] Grosuplje, #[strum(serialize = "159")] Hajdina, #[strum(serialize = "161")] Hodoš, #[strum(serialize = "162")] Horjul, #[strum(serialize = "160")] HočeSlivnica, #[strum(serialize = "034")] Hrastnik, #[strum(serialize = "035")] HrpeljeKozina, #[strum(serialize = "036")] Idrija, #[strum(serialize = "037")] Ig, #[strum(serialize = "039")] IvančnaGorica, #[strum(serialize = "040")] Izola, #[strum(serialize = "041")] Jesenice, #[strum(serialize = "163")] Jezersko, #[strum(serialize = "042")] Jursinci, #[strum(serialize = "043")] Kamnik, #[strum(serialize = "044")] KanalObSoci, #[strum(serialize = "045")] Kidricevo, #[strum(serialize = "046")] Kobarid, #[strum(serialize = "047")] Kobilje, #[strum(serialize = "049")] Komen, #[strum(serialize = "164")] Komenda, #[strum(serialize = "050")] Koper, #[strum(serialize = "197")] KostanjevicaNaKrki, #[strum(serialize = "165")] Kostel, #[strum(serialize = "051")] Kozje, #[strum(serialize = "048")] Kocevje, #[strum(serialize = "052")] Kranj, #[strum(serialize = "053")] KranjskaGora, #[strum(serialize = "166")] Krizevci, #[strum(serialize = "055")] Kungota, #[strum(serialize = "056")] Kuzma, #[strum(serialize = "057")] Lasko, #[strum(serialize = "058")] Lenart, #[strum(serialize = "059")] Lendava, #[strum(serialize = "060")] Litija, #[strum(serialize = "061")] Ljubljana, #[strum(serialize = "062")] Ljubno, #[strum(serialize = "063")] Ljutomer, #[strum(serialize = "064")] Logatec, #[strum(serialize = "208")] LogDragomer, #[strum(serialize = "167")] LovrencNaPohorju, #[strum(serialize = "065")] LoskaDolina, #[strum(serialize = "066")] LoskiPotok, #[strum(serialize = "068")] Lukovica, #[strum(serialize = "067")] Luče, #[strum(serialize = "069")] Majsperk, #[strum(serialize = "198")] Makole, #[strum(serialize = "070")] Maribor, #[strum(serialize = "168")] Markovci, #[strum(serialize = "071")] Medvode, #[strum(serialize = "072")] Menges, #[strum(serialize = "073")] Metlika, #[strum(serialize = "074")] Mezica, #[strum(serialize = "169")] MiklavzNaDravskemPolju, #[strum(serialize = "075")] MirenKostanjevica, #[strum(serialize = "212")] Mirna, #[strum(serialize = "170")] MirnaPec, #[strum(serialize = "076")] Mislinja, #[strum(serialize = "199")] MokronogTrebelno, #[strum(serialize = "078")] MoravskeToplice, #[strum(serialize = "077")] Moravce, #[strum(serialize = "079")] Mozirje, #[strum(serialize = "195")] Apače, #[strum(serialize = "196")] Cirkulane, #[strum(serialize = "038")] IlirskaBistrica, #[strum(serialize = "054")] Krsko, #[strum(serialize = "123")] Skofljica, #[strum(serialize = "080")] MurskaSobota, #[strum(serialize = "081")] Muta, #[strum(serialize = "082")] Naklo, #[strum(serialize = "083")] Nazarje, #[strum(serialize = "084")] NovaGorica, #[strum(serialize = "086")] Odranci, #[strum(serialize = "171")] Oplotnica, #[strum(serialize = "087")] Ormoz, #[strum(serialize = "088")] Osilnica, #[strum(serialize = "089")] Pesnica, #[strum(serialize = "090")] Piran, #[strum(serialize = "091")] Pivka, #[strum(serialize = "172")] Podlehnik, #[strum(serialize = "093")] Podvelka, #[strum(serialize = "092")] Podcetrtek, #[strum(serialize = "200")] Poljcane, #[strum(serialize = "173")] Polzela, #[strum(serialize = "094")] Postojna, #[strum(serialize = "174")] Prebold, #[strum(serialize = "095")] Preddvor, #[strum(serialize = "175")] Prevalje, #[strum(serialize = "096")] Ptuj, #[strum(serialize = "097")] Puconci, #[strum(serialize = "100")] Radenci, #[strum(serialize = "099")] Radece, #[strum(serialize = "101")] RadljeObDravi, #[strum(serialize = "102")] Radovljica, #[strum(serialize = "103")] RavneNaKoroskem, #[strum(serialize = "176")] Razkrizje, #[strum(serialize = "098")] RaceFram, #[strum(serialize = "201")] RenčeVogrsko, #[strum(serialize = "209")] RecicaObSavinji, #[strum(serialize = "104")] Ribnica, #[strum(serialize = "177")] RibnicaNaPohorju, #[strum(serialize = "107")] Rogatec, #[strum(serialize = "106")] RogaskaSlatina, #[strum(serialize = "105")] Rogasovci, #[strum(serialize = "108")] Ruse, #[strum(serialize = "178")] SelnicaObDravi, #[strum(serialize = "109")] Semic, #[strum(serialize = "110")] Sevnica, #[strum(serialize = "111")] Sezana, #[strum(serialize = "112")] SlovenjGradec, #[strum(serialize = "113")] SlovenskaBistrica, #[strum(serialize = "114")] SlovenskeKonjice, #[strum(serialize = "179")] Sodrazica, #[strum(serialize = "180")] Solcava, #[strum(serialize = "202")] SredisceObDravi, #[strum(serialize = "115")] Starse, #[strum(serialize = "203")] Straza, #[strum(serialize = "181")] SvetaAna, #[strum(serialize = "204")] SvetaTrojica, #[strum(serialize = "182")] SvetiAndraz, #[strum(serialize = "116")] SvetiJurijObScavnici, #[strum(serialize = "210")] SvetiJurijVSlovenskihGoricah, #[strum(serialize = "205")] SvetiTomaz, #[strum(serialize = "184")] Tabor, #[strum(serialize = "010")] Tišina, #[strum(serialize = "128")] Tolmin, #[strum(serialize = "129")] Trbovlje, #[strum(serialize = "130")] Trebnje, #[strum(serialize = "185")] TrnovskaVas, #[strum(serialize = "186")] Trzin, #[strum(serialize = "131")] Tržič, #[strum(serialize = "132")] Turnišče, #[strum(serialize = "187")] VelikaPolana, #[strum(serialize = "134")] VelikeLašče, #[strum(serialize = "188")] Veržej, #[strum(serialize = "135")] Videm, #[strum(serialize = "136")] Vipava, #[strum(serialize = "137")] Vitanje, #[strum(serialize = "138")] Vodice, #[strum(serialize = "139")] Vojnik, #[strum(serialize = "189")] Vransko, #[strum(serialize = "140")] Vrhnika, #[strum(serialize = "141")] Vuzenica, #[strum(serialize = "142")] ZagorjeObSavi, #[strum(serialize = "143")] Zavrč, #[strum(serialize = "144")] Zreče, #[strum(serialize = "015")] Črenšovci, #[strum(serialize = "016")] ČrnaNaKoroškem, #[strum(serialize = "017")] Črnomelj, #[strum(serialize = "033")] Šalovci, #[strum(serialize = "183")] ŠempeterVrtojba, #[strum(serialize = "118")] Šentilj, #[strum(serialize = "119")] Šentjernej, #[strum(serialize = "120")] Šentjur, #[strum(serialize = "211")] Šentrupert, #[strum(serialize = "117")] Šenčur, #[strum(serialize = "121")] Škocjan, #[strum(serialize = "122")] ŠkofjaLoka, #[strum(serialize = "124")] ŠmarjePriJelšah, #[strum(serialize = "206")] ŠmarješkeToplice, #[strum(serialize = "125")] ŠmartnoObPaki, #[strum(serialize = "194")] ŠmartnoPriLitiji, #[strum(serialize = "126")] Šoštanj, #[strum(serialize = "127")] Štore, #[strum(serialize = "190")] Žalec, #[strum(serialize = "146")] Železniki, #[strum(serialize = "191")] Žetale, #[strum(serialize = "147")] Žiri, #[strum(serialize = "192")] Žirovnica, #[strum(serialize = "193")] Žužemberk, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum SwedenStatesAbbreviation { #[strum(serialize = "K")] Blekinge, #[strum(serialize = "W")] DalarnaCounty, #[strum(serialize = "I")] GotlandCounty, #[strum(serialize = "X")] GävleborgCounty, #[strum(serialize = "N")] HallandCounty, #[strum(serialize = "F")] JönköpingCounty, #[strum(serialize = "H")] KalmarCounty, #[strum(serialize = "G")] KronobergCounty, #[strum(serialize = "BD")] NorrbottenCounty, #[strum(serialize = "M")] SkåneCounty, #[strum(serialize = "AB")] StockholmCounty, #[strum(serialize = "D")] SödermanlandCounty, #[strum(serialize = "C")] UppsalaCounty, #[strum(serialize = "S")] VärmlandCounty, #[strum(serialize = "AC")] VästerbottenCounty, #[strum(serialize = "Y")] VästernorrlandCounty, #[strum(serialize = "U")] VästmanlandCounty, #[strum(serialize = "O")] VästraGötalandCounty, #[strum(serialize = "T")] ÖrebroCounty, #[strum(serialize = "E")] ÖstergötlandCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum UkraineStatesAbbreviation { #[strum(serialize = "43")] AutonomousRepublicOfCrimea, #[strum(serialize = "71")] CherkasyOblast, #[strum(serialize = "74")] ChernihivOblast, #[strum(serialize = "77")] ChernivtsiOblast, #[strum(serialize = "12")] DnipropetrovskOblast, #[strum(serialize = "14")] DonetskOblast, #[strum(serialize = "26")] IvanoFrankivskOblast, #[strum(serialize = "63")] KharkivOblast, #[strum(serialize = "65")] KhersonOblast, #[strum(serialize = "68")] KhmelnytskyOblast, #[strum(serialize = "30")] Kiev, #[strum(serialize = "35")] KirovohradOblast, #[strum(serialize = "32")] KyivOblast, #[strum(serialize = "09")] LuhanskOblast, #[strum(serialize = "46")] LvivOblast, #[strum(serialize = "48")] MykolaivOblast, #[strum(serialize = "51")] OdessaOblast, #[strum(serialize = "56")] RivneOblast, #[strum(serialize = "59")] SumyOblast, #[strum(serialize = "61")] TernopilOblast, #[strum(serialize = "05")] VinnytsiaOblast, #[strum(serialize = "07")] VolynOblast, #[strum(serialize = "21")] ZakarpattiaOblast, #[strum(serialize = "23")] ZaporizhzhyaOblast, #[strum(serialize = "18")] ZhytomyrOblast, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum RomaniaStatesAbbreviation { #[strum(serialize = "AB")] Alba, #[strum(serialize = "AR")] AradCounty, #[strum(serialize = "AG")] Arges, #[strum(serialize = "BC")] BacauCounty, #[strum(serialize = "BH")] BihorCounty, #[strum(serialize = "BN")] BistritaNasaudCounty, #[strum(serialize = "BT")] BotosaniCounty, #[strum(serialize = "BR")] Braila, #[strum(serialize = "BV")] BrasovCounty, #[strum(serialize = "B")] Bucharest, #[strum(serialize = "BZ")] BuzauCounty, #[strum(serialize = "CS")] CarasSeverinCounty, #[strum(serialize = "CJ")] ClujCounty, #[strum(serialize = "CT")] ConstantaCounty, #[strum(serialize = "CV")] CovasnaCounty, #[strum(serialize = "CL")] CalarasiCounty, #[strum(serialize = "DJ")] DoljCounty, #[strum(serialize = "DB")] DambovitaCounty, #[strum(serialize = "GL")] GalatiCounty, #[strum(serialize = "GR")] GiurgiuCounty, #[strum(serialize = "GJ")] GorjCounty, #[strum(serialize = "HR")] HarghitaCounty, #[strum(serialize = "HD")] HunedoaraCounty, #[strum(serialize = "IL")] IalomitaCounty, #[strum(serialize = "IS")] IasiCounty, #[strum(serialize = "IF")] IlfovCounty, #[strum(serialize = "MH")] MehedintiCounty, #[strum(serialize = "MM")] MuresCounty, #[strum(serialize = "NT")] NeamtCounty, #[strum(serialize = "OT")] OltCounty, #[strum(serialize = "PH")] PrahovaCounty, #[strum(serialize = "SM")] SatuMareCounty, #[strum(serialize = "SB")] SibiuCounty, #[strum(serialize = "SV")] SuceavaCounty, #[strum(serialize = "SJ")] SalajCounty, #[strum(serialize = "TR")] TeleormanCounty, #[strum(serialize = "TM")] TimisCounty, #[strum(serialize = "TL")] TulceaCounty, #[strum(serialize = "VS")] VasluiCounty, #[strum(serialize = "VN")] VranceaCounty, #[strum(serialize = "VL")] ValceaCounty, } #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, )] pub enum BrazilStatesAbbreviation { #[strum(serialize = "AC")] Acre, #[strum(serialize = "AL")] Alagoas, #[strum(serialize = "AP")] Amapá, #[strum(serialize = "AM")] Amazonas, #[strum(serialize = "BA")] Bahia, #[strum(serialize = "CE")] Ceará, #[strum(serialize = "DF")] DistritoFederal, #[strum(serialize = "ES")] EspíritoSanto, #[strum(serialize = "GO")] Goiás, #[strum(serialize = "MA")] Maranhão, #[strum(serialize = "MT")] MatoGrosso, #[strum(serialize = "MS")] MatoGrossoDoSul, #[strum(serialize = "MG")] MinasGerais, #[strum(serialize = "PA")] Pará, #[strum(serialize = "PB")] Paraíba, #[strum(serialize = "PR")] Paraná, #[strum(serialize = "PE")] Pernambuco, #[strum(serialize = "PI")] Piauí, #[strum(serialize = "RJ")] RioDeJaneiro, #[strum(serialize = "RN")] RioGrandeDoNorte, #[strum(serialize = "RS")] RioGrandeDoSul, #[strum(serialize = "RO")] Rondônia, #[strum(serialize = "RR")] Roraima, #[strum(serialize = "SC")] SantaCatarina, #[strum(serialize = "SP")] SãoPaulo, #[strum(serialize = "SE")] Sergipe, #[strum(serialize = "TO")] Tocantins, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutStatus { Success, Failed, Cancelled, Initiated, Expired, Reversed, Pending, Ineligible, #[default] RequiresCreation, RequiresConfirmation, RequiresPayoutMethodData, RequiresFulfillment, RequiresVendorAccountCreation, } /// The payout_type of the payout request is a mandatory field for confirming the payouts. It should be specified in the Create request. If not provided, it must be updated in the Payout Update request before it can be confirmed. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutType { #[default] Card, Bank, Wallet, BankRedirect, } /// Type of entity to whom the payout is being carried out to, select from the given list of options #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "PascalCase")] #[strum(serialize_all = "PascalCase")] pub enum PayoutEntityType { /// Adyen #[default] Individual, Company, NonProfit, PublicSector, NaturalPerson, /// Wise #[strum(serialize = "lowercase")] #[serde(rename = "lowercase")] Business, Personal, } /// The send method which will be required for processing payouts, check options for better understanding. #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutSendPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentSource { #[default] MerchantServer, Postman, Dashboard, Sdk, Webhook, ExternalAuthenticator, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] pub enum BrowserName { #[default] Safari, #[serde(other)] Unknown, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, strum::EnumString)] #[strum(serialize_all = "snake_case")] pub enum ClientPlatform { #[default] Web, Ios, Android, #[serde(other)] Unknown, } impl PaymentSource { pub fn is_for_internal_use_only(self) -> bool { match self { Self::Dashboard | Self::Sdk | Self::MerchantServer | Self::Postman => false, Self::Webhook | Self::ExternalAuthenticator => true, } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum MerchantDecision { Approved, Rejected, AutoRefunded, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum TaxStatus { Taxable, Exempt, } #[derive( Clone, Copy, Default, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmSuggestion { #[default] FrmCancelTransaction, FrmManualReview, FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized. } #[derive( Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ReconStatus { NotRequested, Requested, Active, Disabled, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationConnectors { Threedsecureio, Netcetera, Gpayments, CtpMastercard, UnifiedAuthenticationService, Juspaythreedsserver, CtpVisa, Cardinal, } impl AuthenticationConnectors { pub fn is_separate_version_call_required(self) -> bool { match self { Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::UnifiedAuthenticationService | Self::Juspaythreedsserver | Self::CtpVisa | Self::Cardinal => false, Self::Gpayments => true, } } pub fn is_jwt_flow(&self) -> bool { match self { Self::Threedsecureio | Self::Netcetera | Self::CtpMastercard | Self::UnifiedAuthenticationService | Self::Juspaythreedsserver | Self::CtpVisa | Self::Gpayments => false, Self::Cardinal => true, } } } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum VaultSdk { VgsSdk, HyperswitchSdk, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationStatus { #[default] Started, Pending, Success, Failed, } impl AuthenticationStatus { pub fn is_terminal_status(self) -> bool { match self { Self::Started | Self::Pending => false, Self::Success | Self::Failed => true, } } pub fn is_failed(self) -> bool { self == Self::Failed } pub fn is_success(self) -> bool { self == Self::Success } } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DecoupledAuthenticationType { #[default] Challenge, Frictionless, } #[derive( Clone, Debug, Eq, Default, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, utoipa::ToSchema, Copy, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationLifecycleStatus { Used, #[default] Unused, Expired, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorStatus { #[default] Inactive, Active, } #[derive( Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, serde::Deserialize, serde::Serialize, ToSchema, Default, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TransactionType { #[default] Payment, #[cfg(feature = "payouts")] Payout, ThreeDsAuthentication, } impl TransactionType { pub fn is_three_ds_authentication(self) -> bool { matches!(self, Self::ThreeDsAuthentication) } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoleScope { Organization, Merchant, Profile, } impl From<RoleScope> for EntityType { fn from(role_scope: RoleScope) -> Self { match role_scope { RoleScope::Organization => Self::Organization, RoleScope::Merchant => Self::Merchant, RoleScope::Profile => Self::Profile, } } } /// Indicates the transaction status #[derive( Clone, Default, Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq, ToSchema, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] pub enum TransactionStatus { /// Authentication/ Account Verification Successful #[serde(rename = "Y")] Success, /// Not Authenticated /Account Not Verified; Transaction denied #[default] #[serde(rename = "N")] Failure, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in Authentication Response(ARes) or Result Request (RReq) #[serde(rename = "U")] VerificationNotPerformed, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided #[serde(rename = "A")] NotVerified, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. #[serde(rename = "R")] Rejected, /// Challenge Required; Additional authentication is required using the Challenge Request (CReq) / Challenge Response (CRes) #[serde(rename = "C")] ChallengeRequired, /// Challenge Required; Decoupled Authentication confirmed. #[serde(rename = "D")] ChallengeRequiredDecoupledAuthentication, /// Informational Only; 3DS Requestor challenge preference acknowledged. #[serde(rename = "I")] InformationOnly, } impl TransactionStatus { pub fn is_pending(self) -> bool { matches!( self, Self::ChallengeRequired | Self::ChallengeRequiredDecoupledAuthentication ) } pub fn is_terminal_state(self) -> bool { matches!(self, Self::Success | Self::Failure) } } #[derive( Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, strum::EnumIter, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PermissionGroup { OperationsView, OperationsManage, ConnectorsView, ConnectorsManage, WorkflowsView, WorkflowsManage, AnalyticsView, UsersView, UsersManage, AccountView, AccountManage, ReconReportsView, ReconReportsManage, ReconOpsView, ReconOpsManage, InternalManage, ThemeView, ThemeManage, } #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, strum::EnumIter, )] pub enum ParentGroup { Operations, Connectors, Workflows, Analytics, Users, ReconOps, ReconReports, Account, Internal, Theme, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum Resource { Payment, Refund, ApiKey, Account, Connector, Routing, Dispute, Mandate, Customer, Analytics, ThreeDsDecisionManager, SurchargeDecisionManager, User, WebhookEvent, Payout, Report, ReconToken, ReconFiles, ReconAndSettlementAnalytics, ReconUpload, ReconReports, RunRecon, ReconConfig, RevenueRecovery, Subscription, InternalConnector, Theme, } #[derive( Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, serde::Deserialize, Hash, )] #[serde(rename_all = "snake_case")] pub enum PermissionScope { Read = 0, Write = 1, } /// Name of banks supported by Hyperswitch #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankNames { AmericanExpress, AffinBank, AgroBank, AllianceBank, AmBank, BankOfAmerica, BankOfChina, BankIslam, BankMuamalat, BankRakyat, BankSimpananNasional, Barclays, BlikPSP, CapitalOne, Chase, Citi, CimbBank, Discover, NavyFederalCreditUnion, PentagonFederalCreditUnion, SynchronyBank, WellsFargo, AbnAmro, AsnBank, Bunq, Handelsbanken, HongLeongBank, HsbcBank, Ing, Knab, KuwaitFinanceHouse, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, ArzteUndApothekerBank, AustrianAnadiBankAg, BankAustria, Bank99Ag, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BankMillennium, BankPEKAOSA, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, CapitalBankGraweGruppeAg, CeskaSporitelna, Dolomitenbank, EasybankAg, EPlatbyVUB, ErsteBankUndSparkassen, FrieslandBank, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, KomercniBanka, MBank, MarchfelderBank, Maybank, OberbankAg, OsterreichischeArzteUndApothekerbank, OcbcBank, PayWithING, PlaceZIPKO, PlatnoscOnlineKartaPlatnicza, PosojilnicaBankEGen, PostovaBanka, PublicBank, RaiffeisenBankengruppeOsterreich, RhbBank, SchelhammerCapitalBankAg, StandardCharteredBank, SchoellerbankAg, SpardaBankWien, SporoPay, SantanderPrzelew24, TatraPay, Viamo, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, UobBank, PayWithAliorBank, BankiSpoldzielcze, PayWithInteligo, BNPParibasPoland, BankNowySA, CreditAgricole, PayWithBOS, PayWithCitiHandlowy, PayWithPlusBank, ToyotaBank, VeloBank, ETransferPocztowy24, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, IdeaBank, EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, BangkokBank, KrungsriBank, KrungThaiBank, TheSiamCommercialBank, KasikornBank, OpenBankSuccess, OpenBankFailure, OpenBankCancelled, Aib, BankOfScotland, DanskeBank, FirstDirect, FirstTrust, Halifax, Lloyds, Monzo, NatWest, NationwideBank, RoyalBankOfScotland, Starling, TsbBank, TescoBank, UlsterBank, Yoursafe, N26, NationaleNederlanden, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankType { Checking, Savings, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum BankHolderType { Personal, Business, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, strum::Display, serde::Serialize, strum::EnumIter, strum::EnumString, strum::VariantNames, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GenericLinkType { #[default] PaymentMethodCollect, PayoutLink, } #[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { AuthSelect, #[serde(rename = "sso")] #[strum(serialize = "sso")] SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, ResetPassword, AcceptInvite, UserInfo, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum UserAuthType { OpenIdConnect, MagicLink, #[default] Password, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum Owner { Organization, Tenant, Internal, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ApiVersion { V1, V2, } #[derive( Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, strum::EnumIter, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { Tenant = 3, Organization = 2, Merchant = 1, Profile = 0, } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum PayoutRetryType { SingleConnector, MultiConnector, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OrderFulfillmentTimeOrigin { Create, Confirm, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UIWidgetFormLayout { Tabs, Journey, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DeleteStatus { #[default] Active, Redacted, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector // status: payment status // // status = success && pc == sc TruePositive, // status = failed && pc == sc FalsePositive, // status = failed && pc != sc TrueNegative, // status = success && pc != sc FalseNegative, // status = processing NonDeterministic, } /// Whether 3ds authentication is requested or not #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] pub enum External3dsAuthenticationRequest { /// Request for 3ds authentication Enable, /// Skip 3ds authentication #[default] Skip, } /// Whether payment link is requested to be enabled or not for this transaction #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] pub enum EnablePaymentLinkRequest { /// Request for enabling payment link Enable, /// Skip enabling payment link #[default] Skip, } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] pub enum MitExemptionRequest { /// Request for applying MIT exemption Apply, /// Skip applying MIT exemption #[default] Skip, } /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value #[default] Present, /// Customer is absent during the payment Absent, } impl From<ConnectorType> for TransactionType { fn from(connector_type: ConnectorType) -> Self { match connector_type { #[cfg(feature = "payouts")] ConnectorType::PayoutProcessor => Self::Payout, _ => Self::Payment, } } } impl From<RefundStatus> for RelayStatus { fn from(refund_status: RefundStatus) -> Self { match refund_status { RefundStatus::Failure | RefundStatus::TransactionFailure => Self::Failure, RefundStatus::ManualReview | RefundStatus::Pending => Self::Pending, RefundStatus::Success => Self::Success, } } } impl From<RelayStatus> for RefundStatus { fn from(relay_status: RelayStatus) -> Self { match relay_status { RelayStatus::Failure => Self::Failure, RelayStatus::Pending | RelayStatus::Created => Self::Pending, RelayStatus::Success => Self::Success, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum TaxCalculationOverride { /// Skip calling the external tax provider #[default] Skip, /// Calculate tax by calling the external tax provider Calculate, } impl From<Option<bool>> for TaxCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl TaxCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } #[derive( Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum SurchargeCalculationOverride { /// Skip calculating surcharge #[default] Skip, /// Calculate surcharge Calculate, } impl From<Option<bool>> for SurchargeCalculationOverride { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Calculate, _ => Self::Skip, } } } impl SurchargeCalculationOverride { pub fn as_bool(self) -> bool { match self { Self::Skip => false, Self::Calculate => true, } } } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorMandateStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorTokenStatus { /// Indicates that the connector mandate is active and can be used for payments. Active, /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } #[derive( Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, PartialOrd, Ord, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ErrorCategory { FrmDecline, ProcessorDowntime, ProcessorDeclineUnauthorized, IssueWithPaymentMethod, ProcessorDeclineIncorrectData, HardDecline, SoftDecline, } impl ErrorCategory { pub fn should_perform_elimination_routing(self) -> bool { match self { Self::ProcessorDowntime | Self::ProcessorDeclineUnauthorized => true, Self::IssueWithPaymentMethod | Self::ProcessorDeclineIncorrectData | Self::FrmDecline | Self::HardDecline | Self::SoftDecline => false, } } } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] pub enum PaymentChargeType { #[serde(untagged)] Stripe(StripeChargeType), } #[derive( Clone, Debug, Default, Hash, Eq, PartialEq, ToSchema, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum StripeChargeType { #[default] Direct, Destination, } /// Authentication Products #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationProduct { ClickToPay, } /// Connector Access Method #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum HyperswitchConnectorCategory { PaymentGateway, AlternativePaymentMethod, BankAcquirer, PayoutProcessor, AuthenticationProvider, FraudAndRiskManagementProvider, TaxCalculationProvider, RevenueGrowthManagementPlatform, } /// Connector Integration Status #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorIntegrationStatus { /// Connector is integrated and live on production Live, /// Connector is integrated and fully tested on sandbox Sandbox, /// Connector is integrated and partially tested on sandbox Beta, /// Connector is integrated using the online documentation but not tested yet Alpha, } /// The status of the feature #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FeatureStatus { NotSupported, Supported, } /// The type of tokenization to use for the payment method #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenizationType { /// Create a single use token for the given payment method /// The user might have to go through additional factor authentication when using the single use token if required by the payment method SingleUse, /// Create a multi use token for the given payment method /// User will have to complete the additional factor authentication only once when creating the multi use token /// This will create a mandate at the connector which can be used for recurring payments MultiUse, } /// The network tokenization toggle, whether to enable or skip the network tokenization #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub enum NetworkTokenizationToggle { /// Enable network tokenization for the payment method Enable, /// Skip network tokenization for the payment method Skip, } #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayAuthMethod { /// Contain pan data only PanOnly, /// Contain cryptogram data along with pan data #[serde(rename = "CRYPTOGRAM_3DS")] Cryptogram, } #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "PascalCase")] #[serde(rename_all = "PascalCase")] pub enum AdyenSplitType { /// Books split amount to the specified account. BalanceAccount, /// The aggregated amount of the interchange and scheme fees. AcquiringFees, /// The aggregated amount of all transaction fees. PaymentFee, /// The aggregated amount of Adyen's commission and markup fees. AdyenFees, /// The transaction fees due to Adyen under blended rates. AdyenCommission, /// The transaction fees due to Adyen under Interchange ++ pricing. AdyenMarkup, /// The fees paid to the issuer for each payment made with the card network. Interchange, /// The fees paid to the card scheme for using their network. SchemeFee, /// Your platform's commission on the payment (specified in amount), booked to your liable balance account. Commission, /// Allows you and your users to top up balance accounts using direct debit, card payments, or other payment methods. TopUp, /// The value-added tax charged on the payment, booked to your platforms liable balance account. Vat, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, Default, )] #[serde(rename = "snake_case")] pub enum PaymentConnectorTransmission { /// Failed to call the payment connector #[default] ConnectorCallUnsuccessful, /// Payment Connector call succeeded ConnectorCallSucceeded, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TriggeredBy { /// Denotes payment attempt is been created by internal system. #[default] Internal, /// Denotes payment attempt is been created by external system. External, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MitCategory { /// A fixed purchase amount split into multiple scheduled payments until the total is paid. Installment, /// Merchant-initiated transaction using stored credentials, but not tied to a fixed schedule Unscheduled, /// Merchant-initiated payments that happen at regular intervals (usually the same amount each time). Recurring, /// A retried MIT after a previous transaction failed or was declined. Resubmission, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ProcessTrackerStatus { // Picked by the producer Processing, // State when the task is added New, // Send to retry Pending, // Picked by consumer ProcessStarted, // Finished by consumer Finish, // Review the task Review, } #[derive( serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, strum::EnumString, strum::Display, )] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum ProcessTrackerRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, PaymentMethodStatusUpdateWorkflow, PassiveRecoveryWorkflow, ProcessDisputeWorkflow, DisputeListWorkflow, InvoiceSyncflow, } #[derive(Debug)] pub enum CryptoPadding { PKCS7, ZeroPadding, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum TokenizationFlag { /// Token is active and can be used for payments Enabled, /// Token is inactive and cannot be used for payments Disabled, } /// The type of token data to fetch for get-token endpoint #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum TokenDataType { /// Fetch single use token for the given payment method SingleUseToken, /// Fetch multi use token for the given payment method MultiUseToken, /// Fetch network token for the given payment method NetworkToken, } #[derive( Clone, Debug, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingApproach { SuccessRateExploitation, SuccessRateExploration, ContractBasedRouting, DebitRouting, RuleBasedRouting, VolumeBasedRouting, StraightThroughRouting, #[default] DefaultFallback, #[serde(untagged)] #[strum(default)] Other(String), } impl RoutingApproach { pub fn from_decision_engine_approach(approach: &str) -> Self { match approach { "SR_SELECTION_V3_ROUTING" => Self::SuccessRateExploitation, "SR_V3_HEDGING" | "DEFAULT" => Self::SuccessRateExploration, "NTW_BASED_ROUTING" => Self::DebitRouting, _ => Self::DefaultFallback, } } } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, strum::Display, strum::EnumString, Hash, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] #[router_derive::diesel_enum(storage_type = "text")] pub enum CallbackMapperIdType { NetworkTokenRequestorReferenceID, } /// Payment Method Status #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum VaultType { /// Indicates that the payment method is stored in internal vault. Internal, /// Indicates that the payment method is stored in external vault. External, } #[derive( Clone, Debug, Copy, Default, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ExternalVaultEnabled { Enable, #[default] Skip, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "UPPERCASE")] pub enum GooglePayCardFundingSource { Credit, Debit, Prepaid, #[serde(other)] Unknown, } impl From<IntentStatus> for InvoiceStatus { fn from(value: IntentStatus) -> Self { match value { IntentStatus::Succeeded => Self::InvoicePaid, IntentStatus::RequiresCapture | IntentStatus::PartiallyCaptured | IntentStatus::PartiallyCapturedAndCapturable | IntentStatus::PartiallyAuthorizedAndRequiresCapture | IntentStatus::Processing | IntentStatus::RequiresCustomerAction | IntentStatus::RequiresConfirmation | IntentStatus::RequiresPaymentMethod => Self::PaymentPending, IntentStatus::RequiresMerchantAction => Self::ManualReview, IntentStatus::Cancelled | IntentStatus::CancelledPostCapture => Self::PaymentCanceled, IntentStatus::Expired => Self::PaymentPendingTimeout, IntentStatus::Failed | IntentStatus::Conflicted => Self::PaymentFailed, } } }
crates/common_enums/src/enums.rs
common_enums::src::enums
70,029
true
// File: crates/common_enums/src/enums/ui.rs // Module: common_enums::src::enums::ui use std::fmt; use serde::{de::Visitor, Deserialize, Deserializer, Serialize}; use utoipa::ToSchema; #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "lowercase")] pub enum ElementPosition { Left, #[default] #[serde(rename = "top left")] TopLeft, Top, #[serde(rename = "top right")] TopRight, Right, #[serde(rename = "bottom right")] BottomRight, Bottom, #[serde(rename = "bottom left")] BottomLeft, Center, } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, ToSchema)] #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum ElementSize { Variants(SizeVariants), Percentage(u32), Pixels(u32), } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum SizeVariants { #[default] Cover, Contain, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum PaymentLinkDetailsLayout { #[default] Layout1, Layout2, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum PaymentLinkSdkLabelType { #[default] Above, Floating, Never, } #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum PaymentLinkShowSdkTerms { Always, #[default] Auto, Never, } impl<'de> Deserialize<'de> for ElementSize { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct ElementSizeVisitor; impl Visitor<'_> for ElementSizeVisitor { type Value = ElementSize; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("a string with possible values - contain, cover or values in percentage or pixels. For eg: 48px or 50%") } fn visit_str<E>(self, value: &str) -> Result<ElementSize, E> where E: serde::de::Error, { if let Some(percent) = value.strip_suffix('%') { percent .parse::<u32>() .map(ElementSize::Percentage) .map_err(E::custom) } else if let Some(px) = value.strip_suffix("px") { px.parse::<u32>() .map(ElementSize::Pixels) .map_err(E::custom) } else { match value { "cover" => Ok(ElementSize::Variants(SizeVariants::Cover)), "contain" => Ok(ElementSize::Variants(SizeVariants::Contain)), _ => Err(E::custom("invalid size variant")), } } } } deserializer.deserialize_str(ElementSizeVisitor) } } impl Serialize for ElementSize { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::ser::Serializer, { match self { Self::Variants(variant) => serializer.serialize_str(variant.to_string().as_str()), Self::Pixels(pixel_count) => { serializer.serialize_str(format!("{pixel_count}px").as_str()) } Self::Percentage(pixel_count) => { serializer.serialize_str(format!("{pixel_count}%").as_str()) } } } }
crates/common_enums/src/enums/ui.rs
common_enums::src::enums::ui
1,113
true
// File: crates/common_enums/src/enums/payments.rs // Module: common_enums::src::enums::payments use serde; use utoipa::ToSchema; #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ProductType { #[default] Physical, Digital, Travel, Ride, Event, Accommodation, }
crates/common_enums/src/enums/payments.rs
common_enums::src::enums::payments
99
true
// File: crates/common_enums/src/enums/accounts.rs // Module: common_enums::src::enums::accounts use serde; use utoipa::ToSchema; #[derive( Copy, Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, Hash, )] #[router_derive::diesel_enum(storage_type = "text")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantProductType { #[default] Orchestration, Vault, Recon, Recovery, CostObservability, DynamicRouting, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum MerchantAccountType { #[default] Standard, Platform, Connected, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum OrganizationType { #[default] Standard, Platform, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum MerchantAccountRequestType { #[default] Standard, Connected, }
crates/common_enums/src/enums/accounts.rs
common_enums::src::enums::accounts
460
true
// File: crates/hyperswitch_constraint_graph/src/types.rs // Module: hyperswitch_constraint_graph::src::types use std::{ any::Any, fmt, hash, ops::{Deref, DerefMut}, sync::Arc, }; use rustc_hash::{FxHashMap, FxHashSet}; use crate::{dense_map::impl_entity, error::AnalysisTrace}; pub trait KeyNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + PartialEq + Eq {} pub trait ValueNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + PartialEq + Eq { type Key: KeyNode; fn get_key(&self) -> Self::Key; } #[cfg(feature = "viz")] pub trait NodeViz { fn viz(&self) -> String; } #[derive(Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash)] #[serde(transparent)] pub struct NodeId(usize); impl_entity!(NodeId); #[derive(Debug)] pub struct Node<V: ValueNode> { pub node_type: NodeType<V>, pub preds: Vec<EdgeId>, pub succs: Vec<EdgeId>, } impl<V: ValueNode> Node<V> { pub(crate) fn new(node_type: NodeType<V>) -> Self { Self { node_type, preds: Vec::new(), succs: Vec::new(), } } } #[derive(Debug, PartialEq, Eq)] pub enum NodeType<V: ValueNode> { AllAggregator, AnyAggregator, InAggregator(FxHashSet<V>), Value(NodeValue<V>), } #[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)] #[serde(tag = "type", content = "value", rename_all = "snake_case")] pub enum NodeValue<V: ValueNode> { Key(<V as ValueNode>::Key), Value(V), } impl<V: ValueNode> From<V> for NodeValue<V> { fn from(value: V) -> Self { Self::Value(value) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct EdgeId(usize); impl_entity!(EdgeId); #[derive( Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash, strum::Display, PartialOrd, Ord, )] pub enum Strength { Weak, Normal, Strong, } impl Strength { pub fn get_resolved_strength(prev_strength: Self, curr_strength: Self) -> Self { std::cmp::max(prev_strength, curr_strength) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Relation { Positive, Negative, } impl From<Relation> for bool { fn from(value: Relation) -> Self { matches!(value, Relation::Positive) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize)] pub enum RelationResolution { Positive, Negative, Contradiction, } impl From<Relation> for RelationResolution { fn from(value: Relation) -> Self { match value { Relation::Positive => Self::Positive, Relation::Negative => Self::Negative, } } } impl RelationResolution { pub fn get_resolved_relation(prev_relation: Self, curr_relation: Self) -> Self { if prev_relation != curr_relation { Self::Contradiction } else { curr_relation } } } #[derive(Debug, Clone)] pub struct Edge { pub strength: Strength, pub relation: Relation, pub pred: NodeId, pub succ: NodeId, pub domain: Option<DomainId>, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct DomainId(usize); impl_entity!(DomainId); #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct DomainIdentifier(String); impl DomainIdentifier { pub fn new(identifier: String) -> Self { Self(identifier) } pub fn into_inner(&self) -> String { self.0.clone() } } impl From<String> for DomainIdentifier { fn from(value: String) -> Self { Self(value) } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct DomainInfo { pub domain_identifier: DomainIdentifier, pub domain_description: String, } pub trait CheckingContext { type Value: ValueNode; fn from_node_values<L>(vals: impl IntoIterator<Item = L>) -> Self where L: Into<Self::Value>; fn check_presence(&self, value: &NodeValue<Self::Value>, strength: Strength) -> bool; fn get_values_by_key( &self, expected: &<Self::Value as ValueNode>::Key, ) -> Option<Vec<Self::Value>>; } #[derive(Debug, Clone, serde::Serialize)] pub struct Memoization<V: ValueNode>( #[allow(clippy::type_complexity)] FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace<V>>>>, ); impl<V: ValueNode> Memoization<V> { pub fn new() -> Self { Self(FxHashMap::default()) } } impl<V: ValueNode> Default for Memoization<V> { #[inline] fn default() -> Self { Self::new() } } impl<V: ValueNode> Deref for Memoization<V> { type Target = FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace<V>>>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<V: ValueNode> DerefMut for Memoization<V> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[derive(Debug, Clone)] pub struct CycleCheck(FxHashMap<NodeId, (Strength, RelationResolution)>); impl CycleCheck { pub fn new() -> Self { Self(FxHashMap::default()) } } impl Default for CycleCheck { #[inline] fn default() -> Self { Self::new() } } impl Deref for CycleCheck { type Target = FxHashMap<NodeId, (Strength, RelationResolution)>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for CycleCheck { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } pub trait Metadata: erased_serde::Serialize + Any + Send + Sync + fmt::Debug {} erased_serde::serialize_trait_object!(Metadata); impl<M> Metadata for M where M: erased_serde::Serialize + Any + Send + Sync + fmt::Debug {}
crates/hyperswitch_constraint_graph/src/types.rs
hyperswitch_constraint_graph::src::types
1,465
true
// File: crates/hyperswitch_constraint_graph/src/graph.rs // Module: hyperswitch_constraint_graph::src::graph use std::sync::{Arc, Weak}; use rustc_hash::{FxHashMap, FxHashSet}; use crate::{ builder, dense_map::DenseMap, error::{self, AnalysisTrace, GraphError}, types::{ CheckingContext, CycleCheck, DomainId, DomainIdentifier, DomainInfo, Edge, EdgeId, Memoization, Metadata, Node, NodeId, NodeType, NodeValue, Relation, RelationResolution, Strength, ValueNode, }, }; #[derive(Debug)] struct CheckNodeContext<'a, V: ValueNode, C: CheckingContext<Value = V>> { ctx: &'a C, node: &'a Node<V>, node_id: NodeId, relation: Relation, strength: Strength, memo: &'a mut Memoization<V>, cycle_map: &'a mut CycleCheck, domains: Option<&'a [DomainId]>, } #[derive(Debug)] pub struct ConstraintGraph<V: ValueNode> { pub domain: DenseMap<DomainId, DomainInfo>, pub domain_identifier_map: FxHashMap<DomainIdentifier, DomainId>, pub nodes: DenseMap<NodeId, Node<V>>, pub edges: DenseMap<EdgeId, Edge>, pub value_map: FxHashMap<NodeValue<V>, NodeId>, pub node_info: DenseMap<NodeId, Option<&'static str>>, pub node_metadata: DenseMap<NodeId, Option<Arc<dyn Metadata>>>, } impl<V> ConstraintGraph<V> where V: ValueNode, { fn get_predecessor_edges_by_domain( &self, node_id: NodeId, domains: Option<&[DomainId]>, ) -> Result<Vec<&Edge>, GraphError<V>> { let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?; let mut final_list = Vec::new(); for &pred in &node.preds { let edge = self.edges.get(pred).ok_or(GraphError::EdgeNotFound)?; if let Some((domain_id, domains)) = edge.domain.zip(domains) { if domains.contains(&domain_id) { final_list.push(edge); } } else if edge.domain.is_none() { final_list.push(edge); } } Ok(final_list) } #[allow(clippy::too_many_arguments)] pub fn check_node<C>( &self, ctx: &C, node_id: NodeId, relation: Relation, strength: Strength, memo: &mut Memoization<V>, cycle_map: &mut CycleCheck, domains: Option<&[String]>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let domains = domains .map(|domain_idents| { domain_idents .iter() .map(|domain_ident| { self.domain_identifier_map .get(&DomainIdentifier::new(domain_ident.to_string())) .copied() .ok_or(GraphError::DomainNotFound) }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; self.check_node_inner( ctx, node_id, relation, strength, memo, cycle_map, domains.as_deref(), ) } #[allow(clippy::too_many_arguments)] pub fn check_node_inner<C>( &self, ctx: &C, node_id: NodeId, relation: Relation, strength: Strength, memo: &mut Memoization<V>, cycle_map: &mut CycleCheck, domains: Option<&[DomainId]>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?; if let Some(already_memo) = memo.get(&(node_id, relation, strength)) { already_memo .clone() .map_err(|err| GraphError::AnalysisError(Arc::downgrade(&err))) } else if let Some((initial_strength, initial_relation)) = cycle_map.get(&node_id).copied() { let strength_relation = Strength::get_resolved_strength(initial_strength, strength); let relation_resolve = RelationResolution::get_resolved_relation(initial_relation, relation.into()); cycle_map.entry(node_id).and_modify(|value| { value.0 = strength_relation; value.1 = relation_resolve }); Ok(()) } else { let check_node_context = CheckNodeContext { node, node_id, relation, strength, memo, cycle_map, ctx, domains, }; match &node.node_type { NodeType::AllAggregator => self.validate_all_aggregator(check_node_context), NodeType::AnyAggregator => self.validate_any_aggregator(check_node_context), NodeType::InAggregator(expected) => { self.validate_in_aggregator(check_node_context, expected) } NodeType::Value(val) => self.validate_value_node(check_node_context, val), } } } fn validate_all_aggregator<C>( &self, vald: CheckNodeContext<'_, V, C>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let mut unsatisfied = Vec::<Weak<AnalysisTrace<V>>>::new(); for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? { vald.cycle_map .insert(vald.node_id, (vald.strength, vald.relation.into())); if let Err(e) = self.check_node_inner( vald.ctx, edge.pred, edge.relation, edge.strength, vald.memo, vald.cycle_map, vald.domains, ) { unsatisfied.push(e.get_analysis_trace()?); } if let Some((_resolved_strength, resolved_relation)) = vald.cycle_map.remove(&vald.node_id) { if resolved_relation == RelationResolution::Contradiction { let err = Arc::new(AnalysisTrace::Contradiction { relation: resolved_relation, }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); return Err(GraphError::AnalysisError(Arc::downgrade(&err))); } } } if !unsatisfied.is_empty() { let err = Arc::new(AnalysisTrace::AllAggregation { unsatisfied, info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); Err(GraphError::AnalysisError(Arc::downgrade(&err))) } else { vald.memo .insert((vald.node_id, vald.relation, vald.strength), Ok(())); Ok(()) } } fn validate_any_aggregator<C>( &self, vald: CheckNodeContext<'_, V, C>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let mut unsatisfied = Vec::<Weak<AnalysisTrace<V>>>::new(); let mut matched_one = false; for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? { vald.cycle_map .insert(vald.node_id, (vald.strength, vald.relation.into())); if let Err(e) = self.check_node_inner( vald.ctx, edge.pred, edge.relation, edge.strength, vald.memo, vald.cycle_map, vald.domains, ) { unsatisfied.push(e.get_analysis_trace()?); } else { matched_one = true; } if let Some((_resolved_strength, resolved_relation)) = vald.cycle_map.remove(&vald.node_id) { if resolved_relation == RelationResolution::Contradiction { let err = Arc::new(AnalysisTrace::Contradiction { relation: resolved_relation, }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); return Err(GraphError::AnalysisError(Arc::downgrade(&err))); } } } if matched_one || vald.node.preds.is_empty() { vald.memo .insert((vald.node_id, vald.relation, vald.strength), Ok(())); Ok(()) } else { let err = Arc::new(AnalysisTrace::AnyAggregation { unsatisfied: unsatisfied.clone(), info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); Err(GraphError::AnalysisError(Arc::downgrade(&err))) } } fn validate_in_aggregator<C>( &self, vald: CheckNodeContext<'_, V, C>, expected: &FxHashSet<V>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let the_key = expected .iter() .next() .ok_or_else(|| GraphError::MalformedGraph { reason: "An OnlyIn aggregator node must have at least one expected value" .to_string(), })? .get_key(); let ctx_vals = if let Some(vals) = vald.ctx.get_values_by_key(&the_key) { vals } else { return if let Strength::Weak = vald.strength { vald.memo .insert((vald.node_id, vald.relation, vald.strength), Ok(())); Ok(()) } else { let err = Arc::new(AnalysisTrace::InAggregation { expected: expected.iter().cloned().collect(), found: None, relation: vald.relation, info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); Err(GraphError::AnalysisError(Arc::downgrade(&err))) }; }; let relation_bool: bool = vald.relation.into(); for ctx_value in ctx_vals { if expected.contains(&ctx_value) != relation_bool { let err = Arc::new(AnalysisTrace::InAggregation { expected: expected.iter().cloned().collect(), found: Some(ctx_value.clone()), relation: vald.relation, info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; } } vald.memo .insert((vald.node_id, vald.relation, vald.strength), Ok(())); Ok(()) } fn validate_value_node<C>( &self, vald: CheckNodeContext<'_, V, C>, val: &NodeValue<V>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let mut errors = Vec::<Weak<AnalysisTrace<V>>>::new(); let mut matched_one = false; self.context_analysis( vald.node_id, vald.relation, vald.strength, vald.ctx, val, vald.memo, )?; for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? { vald.cycle_map .insert(vald.node_id, (vald.strength, vald.relation.into())); let result = self.check_node_inner( vald.ctx, edge.pred, edge.relation, edge.strength, vald.memo, vald.cycle_map, vald.domains, ); if let Some((resolved_strength, resolved_relation)) = vald.cycle_map.remove(&vald.node_id) { if resolved_relation == RelationResolution::Contradiction { let err = Arc::new(AnalysisTrace::Contradiction { relation: resolved_relation, }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); return Err(GraphError::AnalysisError(Arc::downgrade(&err))); } else if resolved_strength != vald.strength { self.context_analysis( vald.node_id, vald.relation, resolved_strength, vald.ctx, val, vald.memo, )? } } match (edge.strength, result) { (Strength::Strong, Err(trace)) => { let err = Arc::new(AnalysisTrace::Value { value: val.clone(), relation: vald.relation, info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), predecessors: Some(error::ValueTracePredecessor::Mandatory(Box::new( trace.get_analysis_trace()?, ))), }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; } (Strength::Strong, Ok(_)) => { matched_one = true; } (Strength::Normal | Strength::Weak, Err(trace)) => { errors.push(trace.get_analysis_trace()?); } (Strength::Normal | Strength::Weak, Ok(_)) => { matched_one = true; } } } if matched_one || vald.node.preds.is_empty() { vald.memo .insert((vald.node_id, vald.relation, vald.strength), Ok(())); Ok(()) } else { let err = Arc::new(AnalysisTrace::Value { value: val.clone(), relation: vald.relation, info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), predecessors: Some(error::ValueTracePredecessor::OneOf(errors.clone())), }); vald.memo.insert( (vald.node_id, vald.relation, vald.strength), Err(Arc::clone(&err)), ); Err(GraphError::AnalysisError(Arc::downgrade(&err))) } } fn context_analysis<C>( &self, node_id: NodeId, relation: Relation, strength: Strength, ctx: &C, val: &NodeValue<V>, memo: &mut Memoization<V>, ) -> Result<(), GraphError<V>> where C: CheckingContext<Value = V>, { let in_context = ctx.check_presence(val, strength); let relation_bool: bool = relation.into(); if in_context != relation_bool { let err = Arc::new(AnalysisTrace::Value { value: val.clone(), relation, predecessors: None, info: self.node_info.get(node_id).copied().flatten(), metadata: self.node_metadata.get(node_id).cloned().flatten(), }); memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; } if !relation_bool { memo.insert((node_id, relation, strength), Ok(())); return Ok(()); } Ok(()) } pub fn combine(g1: &Self, g2: &Self) -> Result<Self, GraphError<V>> { let mut node_builder = builder::ConstraintGraphBuilder::new(); let mut g1_old2new_id = DenseMap::<NodeId, NodeId>::new(); let mut g2_old2new_id = DenseMap::<NodeId, NodeId>::new(); let mut g1_old2new_domain_id = DenseMap::<DomainId, DomainId>::new(); let mut g2_old2new_domain_id = DenseMap::<DomainId, DomainId>::new(); let add_domain = |node_builder: &mut builder::ConstraintGraphBuilder<V>, domain: DomainInfo| -> Result<DomainId, GraphError<V>> { node_builder.make_domain( domain.domain_identifier.into_inner(), &domain.domain_description, ) }; let add_node = |node_builder: &mut builder::ConstraintGraphBuilder<V>, node: &Node<V>| -> Result<NodeId, GraphError<V>> { match &node.node_type { NodeType::Value(node_value) => { Ok(node_builder.make_value_node(node_value.clone(), None, None::<()>)) } NodeType::AllAggregator => { Ok(node_builder.make_all_aggregator(&[], None, None::<()>, None)?) } NodeType::AnyAggregator => { Ok(node_builder.make_any_aggregator(&[], None, None::<()>, None)?) } NodeType::InAggregator(expected) => Ok(node_builder.make_in_aggregator( expected.iter().cloned().collect(), None, None::<()>, )?), } }; for (_old_domain_id, domain) in g1.domain.iter() { let new_domain_id = add_domain(&mut node_builder, domain.clone())?; g1_old2new_domain_id.push(new_domain_id); } for (_old_domain_id, domain) in g2.domain.iter() { let new_domain_id = add_domain(&mut node_builder, domain.clone())?; g2_old2new_domain_id.push(new_domain_id); } for (_old_node_id, node) in g1.nodes.iter() { let new_node_id = add_node(&mut node_builder, node)?; g1_old2new_id.push(new_node_id); } for (_old_node_id, node) in g2.nodes.iter() { let new_node_id = add_node(&mut node_builder, node)?; g2_old2new_id.push(new_node_id); } for edge in g1.edges.values() { let new_pred_id = g1_old2new_id .get(edge.pred) .ok_or(GraphError::NodeNotFound)?; let new_succ_id = g1_old2new_id .get(edge.succ) .ok_or(GraphError::NodeNotFound)?; let domain_ident = edge .domain .map(|domain_id| g1.domain.get(domain_id).ok_or(GraphError::DomainNotFound)) .transpose()? .map(|domain| domain.domain_identifier.clone()); node_builder.make_edge( *new_pred_id, *new_succ_id, edge.strength, edge.relation, domain_ident, )?; } for edge in g2.edges.values() { let new_pred_id = g2_old2new_id .get(edge.pred) .ok_or(GraphError::NodeNotFound)?; let new_succ_id = g2_old2new_id .get(edge.succ) .ok_or(GraphError::NodeNotFound)?; let domain_ident = edge .domain .map(|domain_id| g2.domain.get(domain_id).ok_or(GraphError::DomainNotFound)) .transpose()? .map(|domain| domain.domain_identifier.clone()); node_builder.make_edge( *new_pred_id, *new_succ_id, edge.strength, edge.relation, domain_ident, )?; } Ok(node_builder.build()) } } #[cfg(feature = "viz")] mod viz { use graphviz_rust::{ dot_generator::*, dot_structures::*, printer::{DotPrinter, PrinterContext}, }; use crate::{dense_map::EntityId, types, ConstraintGraph, NodeViz, ValueNode}; fn get_node_id(node_id: types::NodeId) -> String { format!("N{}", node_id.get_id()) } impl<V> ConstraintGraph<V> where V: ValueNode + NodeViz, <V as ValueNode>::Key: NodeViz, { fn get_node_label(node: &types::Node<V>) -> String { let label = match &node.node_type { types::NodeType::Value(types::NodeValue::Key(key)) => format!("any {}", key.viz()), types::NodeType::Value(types::NodeValue::Value(val)) => { format!("{} = {}", val.get_key().viz(), val.viz()) } types::NodeType::AllAggregator => "&&".to_string(), types::NodeType::AnyAggregator => "| |".to_string(), types::NodeType::InAggregator(agg) => { let key = if let Some(val) = agg.iter().next() { val.get_key().viz() } else { return "empty in".to_string(); }; let nodes = agg.iter().map(NodeViz::viz).collect::<Vec<_>>(); format!("{key} in [{}]", nodes.join(", ")) } }; format!("\"{label}\"") } fn build_node(cg_node_id: types::NodeId, cg_node: &types::Node<V>) -> Node { let viz_node_id = get_node_id(cg_node_id); let viz_node_label = Self::get_node_label(cg_node); node!(viz_node_id; attr!("label", viz_node_label)) } fn build_edge(cg_edge: &types::Edge) -> Edge { let pred_vertex = get_node_id(cg_edge.pred); let succ_vertex = get_node_id(cg_edge.succ); let arrowhead = match cg_edge.strength { types::Strength::Weak => "onormal", types::Strength::Normal => "normal", types::Strength::Strong => "normalnormal", }; let color = match cg_edge.relation { types::Relation::Positive => "blue", types::Relation::Negative => "red", }; edge!( node_id!(pred_vertex) => node_id!(succ_vertex); attr!("arrowhead", arrowhead), attr!("color", color) ) } pub fn get_viz_digraph(&self) -> Graph { graph!( strict di id!("constraint_graph"), self.nodes .iter() .map(|(node_id, node)| Self::build_node(node_id, node)) .map(Stmt::Node) .chain(self.edges.values().map(Self::build_edge).map(Stmt::Edge)) .collect::<Vec<_>>() ) } pub fn get_viz_digraph_string(&self) -> String { let mut ctx = PrinterContext::default(); let digraph = self.get_viz_digraph(); digraph.print(&mut ctx) } } }
crates/hyperswitch_constraint_graph/src/graph.rs
hyperswitch_constraint_graph::src::graph
5,132
true
// File: crates/hyperswitch_constraint_graph/src/error.rs // Module: hyperswitch_constraint_graph::src::error use std::sync::{Arc, Weak}; use crate::types::{Metadata, NodeValue, Relation, RelationResolution, ValueNode}; #[derive(Debug, Clone, serde::Serialize)] #[serde(tag = "type", content = "predecessor", rename_all = "snake_case")] pub enum ValueTracePredecessor<V: ValueNode> { Mandatory(Box<Weak<AnalysisTrace<V>>>), OneOf(Vec<Weak<AnalysisTrace<V>>>), } #[derive(Debug, Clone, serde::Serialize)] #[serde(tag = "type", content = "trace", rename_all = "snake_case")] pub enum AnalysisTrace<V: ValueNode> { Value { value: NodeValue<V>, relation: Relation, predecessors: Option<ValueTracePredecessor<V>>, info: Option<&'static str>, metadata: Option<Arc<dyn Metadata>>, }, AllAggregation { unsatisfied: Vec<Weak<AnalysisTrace<V>>>, info: Option<&'static str>, metadata: Option<Arc<dyn Metadata>>, }, AnyAggregation { unsatisfied: Vec<Weak<AnalysisTrace<V>>>, info: Option<&'static str>, metadata: Option<Arc<dyn Metadata>>, }, InAggregation { expected: Vec<V>, found: Option<V>, relation: Relation, info: Option<&'static str>, metadata: Option<Arc<dyn Metadata>>, }, Contradiction { relation: RelationResolution, }, } #[derive(Debug, Clone, serde::Serialize, thiserror::Error)] #[serde(tag = "type", content = "info", rename_all = "snake_case")] pub enum GraphError<V: ValueNode> { #[error("An edge was not found in the graph")] EdgeNotFound, #[error("Attempted to create a conflicting edge between two nodes")] ConflictingEdgeCreated, #[error("Cycle detected in graph")] CycleDetected, #[error("Domain wasn't found in the Graph")] DomainNotFound, #[error("Malformed Graph: {reason}")] MalformedGraph { reason: String }, #[error("A node was not found in the graph")] NodeNotFound, #[error("A value node was not found: {0:#?}")] ValueNodeNotFound(V), #[error("No values provided for an 'in' aggregator node")] NoInAggregatorValues, #[error("Error during analysis: {0:#?}")] AnalysisError(Weak<AnalysisTrace<V>>), } impl<V: ValueNode> GraphError<V> { pub fn get_analysis_trace(self) -> Result<Weak<AnalysisTrace<V>>, Self> { match self { Self::AnalysisError(trace) => Ok(trace), _ => Err(self), } } }
crates/hyperswitch_constraint_graph/src/error.rs
hyperswitch_constraint_graph::src::error
613
true
// File: crates/hyperswitch_constraint_graph/src/lib.rs // Module: hyperswitch_constraint_graph::src::lib pub mod builder; mod dense_map; pub mod error; pub mod graph; pub mod types; pub use builder::ConstraintGraphBuilder; pub use error::{AnalysisTrace, GraphError}; pub use graph::ConstraintGraph; #[cfg(feature = "viz")] pub use types::NodeViz; pub use types::{ CheckingContext, CycleCheck, DomainId, DomainIdentifier, Edge, EdgeId, KeyNode, Memoization, Node, NodeId, NodeValue, Relation, Strength, ValueNode, };
crates/hyperswitch_constraint_graph/src/lib.rs
hyperswitch_constraint_graph::src::lib
131
true
// File: crates/hyperswitch_constraint_graph/src/dense_map.rs // Module: hyperswitch_constraint_graph::src::dense_map use std::{fmt, iter, marker::PhantomData, ops, slice, vec}; pub trait EntityId { fn get_id(&self) -> usize; fn with_id(id: usize) -> Self; } macro_rules! impl_entity { ($name:ident) => { impl $crate::dense_map::EntityId for $name { #[inline] fn get_id(&self) -> usize { self.0 } #[inline] fn with_id(id: usize) -> Self { Self(id) } } }; } pub(crate) use impl_entity; pub struct DenseMap<K, V> { data: Vec<V>, _marker: PhantomData<K>, } impl<K, V> DenseMap<K, V> { pub fn new() -> Self { Self { data: Vec::new(), _marker: PhantomData, } } } impl<K, V> Default for DenseMap<K, V> { fn default() -> Self { Self::new() } } impl<K, V> DenseMap<K, V> where K: EntityId, { pub fn push(&mut self, elem: V) -> K { let curr_len = self.data.len(); self.data.push(elem); K::with_id(curr_len) } #[inline] pub fn get(&self, idx: K) -> Option<&V> { self.data.get(idx.get_id()) } #[inline] pub fn get_mut(&mut self, idx: K) -> Option<&mut V> { self.data.get_mut(idx.get_id()) } #[inline] pub fn contains_key(&self, key: K) -> bool { key.get_id() < self.data.len() } #[inline] pub fn keys(&self) -> Keys<K> { Keys::new(0..self.data.len()) } #[inline] pub fn into_keys(self) -> Keys<K> { Keys::new(0..self.data.len()) } #[inline] pub fn values(&self) -> slice::Iter<'_, V> { self.data.iter() } #[inline] pub fn values_mut(&mut self) -> slice::IterMut<'_, V> { self.data.iter_mut() } #[inline] pub fn into_values(self) -> vec::IntoIter<V> { self.data.into_iter() } #[inline] pub fn iter(&self) -> Iter<'_, K, V> { Iter::new(self.data.iter()) } #[inline] pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { IterMut::new(self.data.iter_mut()) } } impl<K, V> fmt::Debug for DenseMap<K, V> where K: EntityId + fmt::Debug, V: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_map().entries(self.iter()).finish() } } pub struct Keys<K> { inner: ops::Range<usize>, _marker: PhantomData<K>, } impl<K> Keys<K> { fn new(range: ops::Range<usize>) -> Self { Self { inner: range, _marker: PhantomData, } } } impl<K> Iterator for Keys<K> where K: EntityId, { type Item = K; fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(K::with_id) } } pub struct Iter<'a, K, V> { inner: iter::Enumerate<slice::Iter<'a, V>>, _marker: PhantomData<K>, } impl<'a, K, V> Iter<'a, K, V> { fn new(iter: slice::Iter<'a, V>) -> Self { Self { inner: iter.enumerate(), _marker: PhantomData, } } } impl<'a, K, V> Iterator for Iter<'a, K, V> where K: EntityId, { type Item = (K, &'a V); fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(|(id, val)| (K::with_id(id), val)) } } pub struct IterMut<'a, K, V> { inner: iter::Enumerate<slice::IterMut<'a, V>>, _marker: PhantomData<K>, } impl<'a, K, V> IterMut<'a, K, V> { fn new(iter: slice::IterMut<'a, V>) -> Self { Self { inner: iter.enumerate(), _marker: PhantomData, } } } impl<'a, K, V> Iterator for IterMut<'a, K, V> where K: EntityId, { type Item = (K, &'a mut V); fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(|(id, val)| (K::with_id(id), val)) } } pub struct IntoIter<K, V> { inner: iter::Enumerate<vec::IntoIter<V>>, _marker: PhantomData<K>, } impl<K, V> IntoIter<K, V> { fn new(iter: vec::IntoIter<V>) -> Self { Self { inner: iter.enumerate(), _marker: PhantomData, } } } impl<K, V> Iterator for IntoIter<K, V> where K: EntityId, { type Item = (K, V); fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(|(id, val)| (K::with_id(id), val)) } } impl<K, V> IntoIterator for DenseMap<K, V> where K: EntityId, { type Item = (K, V); type IntoIter = IntoIter<K, V>; fn into_iter(self) -> Self::IntoIter { IntoIter::new(self.data.into_iter()) } } impl<K, V> FromIterator<V> for DenseMap<K, V> where K: EntityId, { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = V>, { Self { data: Vec::from_iter(iter), _marker: PhantomData, } } }
crates/hyperswitch_constraint_graph/src/dense_map.rs
hyperswitch_constraint_graph::src::dense_map
1,435
true
// File: crates/hyperswitch_constraint_graph/src/builder.rs // Module: hyperswitch_constraint_graph::src::builder use std::sync::Arc; use rustc_hash::{FxHashMap, FxHashSet}; use crate::{ dense_map::DenseMap, error::GraphError, graph::ConstraintGraph, types::{ DomainId, DomainIdentifier, DomainInfo, Edge, EdgeId, Metadata, Node, NodeId, NodeType, NodeValue, Relation, Strength, ValueNode, }, }; pub enum DomainIdOrIdentifier { DomainId(DomainId), DomainIdentifier(DomainIdentifier), } impl From<String> for DomainIdOrIdentifier { fn from(value: String) -> Self { Self::DomainIdentifier(DomainIdentifier::new(value)) } } impl From<DomainIdentifier> for DomainIdOrIdentifier { fn from(value: DomainIdentifier) -> Self { Self::DomainIdentifier(value) } } impl From<DomainId> for DomainIdOrIdentifier { fn from(value: DomainId) -> Self { Self::DomainId(value) } } #[derive(Debug)] pub struct ConstraintGraphBuilder<V: ValueNode> { domain: DenseMap<DomainId, DomainInfo>, nodes: DenseMap<NodeId, Node<V>>, edges: DenseMap<EdgeId, Edge>, domain_identifier_map: FxHashMap<DomainIdentifier, DomainId>, value_map: FxHashMap<NodeValue<V>, NodeId>, edges_map: FxHashMap<(NodeId, NodeId, Option<DomainId>), EdgeId>, node_info: DenseMap<NodeId, Option<&'static str>>, node_metadata: DenseMap<NodeId, Option<Arc<dyn Metadata>>>, } #[allow(clippy::new_without_default)] impl<V> ConstraintGraphBuilder<V> where V: ValueNode, { pub fn new() -> Self { Self { domain: DenseMap::new(), nodes: DenseMap::new(), edges: DenseMap::new(), domain_identifier_map: FxHashMap::default(), value_map: FxHashMap::default(), edges_map: FxHashMap::default(), node_info: DenseMap::new(), node_metadata: DenseMap::new(), } } pub fn build(self) -> ConstraintGraph<V> { ConstraintGraph { domain: self.domain, domain_identifier_map: self.domain_identifier_map, nodes: self.nodes, edges: self.edges, value_map: self.value_map, node_info: self.node_info, node_metadata: self.node_metadata, } } fn retrieve_domain_from_identifier( &self, domain_ident: DomainIdentifier, ) -> Result<DomainId, GraphError<V>> { self.domain_identifier_map .get(&domain_ident) .copied() .ok_or(GraphError::DomainNotFound) } pub fn make_domain( &mut self, domain_identifier: String, domain_description: &str, ) -> Result<DomainId, GraphError<V>> { let domain_identifier = DomainIdentifier::new(domain_identifier); Ok(self .domain_identifier_map .clone() .get(&domain_identifier) .map_or_else( || { let domain_id = self.domain.push(DomainInfo { domain_identifier: domain_identifier.clone(), domain_description: domain_description.to_string(), }); self.domain_identifier_map .insert(domain_identifier, domain_id); domain_id }, |domain_id| *domain_id, )) } pub fn make_value_node<M: Metadata>( &mut self, value: NodeValue<V>, info: Option<&'static str>, metadata: Option<M>, ) -> NodeId { self.value_map.get(&value).copied().unwrap_or_else(|| { let node_id = self.nodes.push(Node::new(NodeType::Value(value.clone()))); let _node_info_id = self.node_info.push(info); let _node_metadata_id = self .node_metadata .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); self.value_map.insert(value, node_id); node_id }) } pub fn make_edge<T: Into<DomainIdOrIdentifier>>( &mut self, pred_id: NodeId, succ_id: NodeId, strength: Strength, relation: Relation, domain: Option<T>, ) -> Result<EdgeId, GraphError<V>> { self.ensure_node_exists(pred_id)?; self.ensure_node_exists(succ_id)?; let domain_id = domain .map(|d| match d.into() { DomainIdOrIdentifier::DomainIdentifier(ident) => { self.retrieve_domain_from_identifier(ident) } DomainIdOrIdentifier::DomainId(domain_id) => { self.ensure_domain_exists(domain_id).map(|_| domain_id) } }) .transpose()?; self.edges_map .get(&(pred_id, succ_id, domain_id)) .copied() .and_then(|edge_id| self.edges.get(edge_id).cloned().map(|edge| (edge_id, edge))) .map_or_else( || { let edge_id = self.edges.push(Edge { strength, relation, pred: pred_id, succ: succ_id, domain: domain_id, }); self.edges_map .insert((pred_id, succ_id, domain_id), edge_id); let pred = self .nodes .get_mut(pred_id) .ok_or(GraphError::NodeNotFound)?; pred.succs.push(edge_id); let succ = self .nodes .get_mut(succ_id) .ok_or(GraphError::NodeNotFound)?; succ.preds.push(edge_id); Ok(edge_id) }, |(edge_id, edge)| { if edge.strength == strength && edge.relation == relation { Ok(edge_id) } else { Err(GraphError::ConflictingEdgeCreated) } }, ) } pub fn make_all_aggregator<M: Metadata>( &mut self, nodes: &[(NodeId, Relation, Strength)], info: Option<&'static str>, metadata: Option<M>, domain_id: Option<DomainId>, ) -> Result<NodeId, GraphError<V>> { nodes .iter() .try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?; let aggregator_id = self.nodes.push(Node::new(NodeType::AllAggregator)); let _aggregator_info_id = self.node_info.push(info); let _node_metadata_id = self .node_metadata .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); for (node_id, relation, strength) in nodes { self.make_edge(*node_id, aggregator_id, *strength, *relation, domain_id)?; } Ok(aggregator_id) } pub fn make_any_aggregator<M: Metadata>( &mut self, nodes: &[(NodeId, Relation, Strength)], info: Option<&'static str>, metadata: Option<M>, domain_id: Option<DomainId>, ) -> Result<NodeId, GraphError<V>> { nodes .iter() .try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?; let aggregator_id = self.nodes.push(Node::new(NodeType::AnyAggregator)); let _aggregator_info_id = self.node_info.push(info); let _node_metadata_id = self .node_metadata .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); for (node_id, relation, strength) in nodes { self.make_edge(*node_id, aggregator_id, *strength, *relation, domain_id)?; } Ok(aggregator_id) } pub fn make_in_aggregator<M: Metadata>( &mut self, values: Vec<V>, info: Option<&'static str>, metadata: Option<M>, ) -> Result<NodeId, GraphError<V>> { let key = values .first() .ok_or(GraphError::NoInAggregatorValues)? .get_key(); for val in &values { if val.get_key() != key { Err(GraphError::MalformedGraph { reason: "Values for 'In' aggregator not of same key".to_string(), })?; } } let node_id = self .nodes .push(Node::new(NodeType::InAggregator(FxHashSet::from_iter( values, )))); let _aggregator_info_id = self.node_info.push(info); let _node_metadata_id = self .node_metadata .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); Ok(node_id) } fn ensure_node_exists(&self, id: NodeId) -> Result<(), GraphError<V>> { if self.nodes.contains_key(id) { Ok(()) } else { Err(GraphError::NodeNotFound) } } fn ensure_domain_exists(&self, id: DomainId) -> Result<(), GraphError<V>> { if self.domain.contains_key(id) { Ok(()) } else { Err(GraphError::DomainNotFound) } } }
crates/hyperswitch_constraint_graph/src/builder.rs
hyperswitch_constraint_graph::src::builder
2,015
true
// File: crates/connector_configs/src/lib.rs // Module: connector_configs::src::lib pub mod common_config; pub mod connector; pub mod response_modifier; pub mod transformer;
crates/connector_configs/src/lib.rs
connector_configs::src::lib
39
true
// File: crates/connector_configs/src/response_modifier.rs // Module: connector_configs::src::response_modifier use crate::common_config::{ CardProvider, ConnectorApiIntegrationPayload, DashboardPaymentMethodPayload, DashboardRequestPayload, Provider, }; impl ConnectorApiIntegrationPayload { pub fn get_transformed_response_payload(response: Self) -> DashboardRequestPayload { let mut wallet_details: Vec<Provider> = Vec::new(); let mut bank_redirect_details: Vec<Provider> = Vec::new(); let mut pay_later_details: Vec<Provider> = Vec::new(); let mut debit_details: Vec<CardProvider> = Vec::new(); let mut credit_details: Vec<CardProvider> = Vec::new(); let mut bank_transfer_details: Vec<Provider> = Vec::new(); let mut crypto_details: Vec<Provider> = Vec::new(); let mut bank_debit_details: Vec<Provider> = Vec::new(); let mut reward_details: Vec<Provider> = Vec::new(); let mut real_time_payment_details: Vec<Provider> = Vec::new(); let mut upi_details: Vec<Provider> = Vec::new(); let mut voucher_details: Vec<Provider> = Vec::new(); let mut gift_card_details: Vec<Provider> = Vec::new(); let mut card_redirect_details: Vec<Provider> = Vec::new(); let mut open_banking_details: Vec<Provider> = Vec::new(); let mut mobile_payment_details: Vec<Provider> = Vec::new(); if let Some(payment_methods_enabled) = response.payment_methods_enabled.clone() { for methods in payment_methods_enabled { match methods.payment_method { api_models::enums::PaymentMethod::Card => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { match method_type.payment_method_type { api_models::enums::PaymentMethodType::Credit => { if let Some(card_networks) = method_type.card_networks { for card in card_networks { credit_details.push(CardProvider { payment_method_type: card, accepted_currencies: method_type .accepted_currencies .clone(), accepted_countries: method_type .accepted_countries .clone(), }) } } } api_models::enums::PaymentMethodType::Debit => { if let Some(card_networks) = method_type.card_networks { for card in card_networks { // debit_details.push(card) debit_details.push(CardProvider { payment_method_type: card, accepted_currencies: method_type .accepted_currencies .clone(), accepted_countries: method_type .accepted_countries .clone(), }) } } } _ => (), } } } } api_models::enums::PaymentMethod::Wallet => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { // wallet_details.push(method_type.payment_method_type) wallet_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::BankRedirect => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { bank_redirect_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::PayLater => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { pay_later_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::BankTransfer => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { bank_transfer_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::Crypto => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { crypto_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::BankDebit => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { bank_debit_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::Reward => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { reward_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::RealTimePayment => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { real_time_payment_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::OpenBanking => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { open_banking_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::Upi => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { upi_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::Voucher => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { voucher_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::GiftCard => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { gift_card_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::CardRedirect => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { card_redirect_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } api_models::enums::PaymentMethod::MobilePayment => { if let Some(payment_method_types) = methods.payment_method_types { for method_type in payment_method_types { mobile_payment_details.push(Provider { payment_method_type: method_type.payment_method_type, accepted_currencies: method_type.accepted_currencies.clone(), accepted_countries: method_type.accepted_countries.clone(), payment_experience: method_type.payment_experience, }) } } } } } } let open_banking = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::OpenBanking, payment_method_type: api_models::enums::PaymentMethod::OpenBanking.to_string(), provider: Some(open_banking_details), card_provider: None, }; let upi = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::Upi, payment_method_type: api_models::enums::PaymentMethod::Upi.to_string(), provider: Some(upi_details), card_provider: None, }; let voucher: DashboardPaymentMethodPayload = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::Voucher, payment_method_type: api_models::enums::PaymentMethod::Voucher.to_string(), provider: Some(voucher_details), card_provider: None, }; let gift_card: DashboardPaymentMethodPayload = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::GiftCard, payment_method_type: api_models::enums::PaymentMethod::GiftCard.to_string(), provider: Some(gift_card_details), card_provider: None, }; let reward = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::Reward, payment_method_type: api_models::enums::PaymentMethod::Reward.to_string(), provider: Some(reward_details), card_provider: None, }; let real_time_payment = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::RealTimePayment, payment_method_type: api_models::enums::PaymentMethod::RealTimePayment.to_string(), provider: Some(real_time_payment_details), card_provider: None, }; let wallet = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::Wallet, payment_method_type: api_models::enums::PaymentMethod::Wallet.to_string(), provider: Some(wallet_details), card_provider: None, }; let bank_redirect = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::BankRedirect, payment_method_type: api_models::enums::PaymentMethod::BankRedirect.to_string(), provider: Some(bank_redirect_details), card_provider: None, }; let bank_debit = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::BankDebit, payment_method_type: api_models::enums::PaymentMethod::BankDebit.to_string(), provider: Some(bank_debit_details), card_provider: None, }; let bank_transfer = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::BankTransfer, payment_method_type: api_models::enums::PaymentMethod::BankTransfer.to_string(), provider: Some(bank_transfer_details), card_provider: None, }; let crypto = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::Crypto, payment_method_type: api_models::enums::PaymentMethod::Crypto.to_string(), provider: Some(crypto_details), card_provider: None, }; let card_redirect = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::CardRedirect, payment_method_type: api_models::enums::PaymentMethod::CardRedirect.to_string(), provider: Some(card_redirect_details), card_provider: None, }; let pay_later = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::PayLater, payment_method_type: api_models::enums::PaymentMethod::PayLater.to_string(), provider: Some(pay_later_details), card_provider: None, }; let debit_details = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::Card, payment_method_type: api_models::enums::PaymentMethodType::Debit.to_string(), provider: None, card_provider: Some(debit_details), }; let credit_details = DashboardPaymentMethodPayload { payment_method: api_models::enums::PaymentMethod::Card, payment_method_type: api_models::enums::PaymentMethodType::Credit.to_string(), provider: None, card_provider: Some(credit_details), }; DashboardRequestPayload { connector: response.connector_name, payment_methods_enabled: Some(vec![ open_banking, upi, voucher, reward, real_time_payment, wallet, bank_redirect, bank_debit, bank_transfer, crypto, card_redirect, pay_later, debit_details, credit_details, gift_card, ]), metadata: response.metadata, } } }
crates/connector_configs/src/response_modifier.rs
connector_configs::src::response_modifier
2,961
true
// File: crates/connector_configs/src/common_config.rs // Module: connector_configs::src::common_config use api_models::{payment_methods, payments}; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, serde::Serialize, Clone)] #[serde(rename_all = "snake_case")] pub struct ZenApplePay { pub terminal_uuid: Option<String>, pub pay_wall_secret: Option<String>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, serde::Serialize, Clone)] #[serde(untagged)] pub enum ApplePayData { ApplePay(payments::ApplePayMetadata), ApplePayCombined(payments::ApplePayCombinedMetadata), Zen(ZenApplePay), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayDashboardPayLoad { #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename( serialize = "stripe_publishable_key", deserialize = "stripe:publishable_key" ))] #[serde(alias = "stripe:publishable_key")] #[serde(alias = "stripe_publishable_key")] pub stripe_publishable_key: Option<String>, pub merchant_name: String, #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, serde::Serialize, Clone)] #[serde(rename_all = "snake_case")] pub struct ZenGooglePay { pub terminal_uuid: Option<String>, pub pay_wall_secret: Option<String>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, serde::Serialize, Clone)] #[serde(untagged)] pub enum GooglePayData { Standard(GpayDashboardPayLoad), Zen(ZenGooglePay), } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkData { pub client_id: Option<String>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, serde::Serialize, Clone)] #[serde(untagged)] pub enum GoogleApiModelData { Standard(payments::GpayMetaData), Zen(ZenGooglePay), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PaymentMethodsEnabled { pub payment_method: api_models::enums::PaymentMethod, pub payment_method_types: Option<Vec<payment_methods::RequestPaymentMethodTypes>>, } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct ApiModelMetaData { pub merchant_config_currency: Option<api_models::enums::Currency>, pub merchant_account_id: Option<String>, pub account_name: Option<String>, pub terminal_id: Option<String>, pub merchant_id: Option<String>, pub google_pay: Option<GoogleApiModelData>, pub paypal_sdk: Option<PaypalSdkData>, pub apple_pay: Option<ApplePayData>, pub apple_pay_combined: Option<ApplePayData>, pub endpoint_prefix: Option<String>, pub mcc: Option<String>, pub merchant_country_code: Option<String>, pub merchant_name: Option<String>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, pub acquirer_country_code: Option<String>, pub three_ds_requestor_name: Option<String>, pub three_ds_requestor_id: Option<String>, pub pull_mechanism_for_external_3ds_enabled: Option<bool>, pub klarna_region: Option<KlarnaEndpoint>, pub source_balance_account: Option<String>, pub brand_id: Option<String>, pub destination_account_number: Option<String>, pub dpa_id: Option<String>, pub dpa_name: Option<String>, pub locale: Option<String>, pub card_brands: Option<Vec<String>>, pub merchant_category_code: Option<String>, pub merchant_configuration_id: Option<String>, pub tenant_id: Option<String>, pub platform_url: Option<String>, pub account_id: Option<serde_json::Value>, pub site: Option<String>, } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub enum KlarnaEndpoint { Europe, NorthAmerica, Oceania, } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, ToSchema, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CardProvider { pub payment_method_type: api_models::enums::CardNetwork, /// List of currencies accepted or has the processing capabilities of the processor #[schema(example = json!( { "type": "specific_accepted", "list": ["USD", "INR"] } ), value_type = Option<AcceptedCurrencies>)] pub accepted_currencies: Option<api_models::admin::AcceptedCurrencies>, #[schema(example = json!( { "type": "specific_accepted", "list": ["UK", "AU"] } ), value_type = Option<AcceptedCountries>)] pub accepted_countries: Option<api_models::admin::AcceptedCountries>, } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, ToSchema, Deserialize)] #[serde(rename_all = "snake_case")] pub struct Provider { pub payment_method_type: api_models::enums::PaymentMethodType, /// List of currencies accepted or has the processing capabilities of the processor #[schema(example = json!( { "type": "specific_accepted", "list": ["USD", "INR"] } ), value_type = Option<AcceptedCurrencies>)] pub accepted_currencies: Option<api_models::admin::AcceptedCurrencies>, #[schema(example = json!( { "type": "specific_accepted", "list": ["UK", "AU"] } ), value_type = Option<AcceptedCountries>)] pub accepted_countries: Option<api_models::admin::AcceptedCountries>, pub payment_experience: Option<api_models::enums::PaymentExperience>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct ConnectorApiIntegrationPayload { pub connector_type: String, pub profile_id: common_utils::id_type::ProfileId, pub connector_name: api_models::enums::Connector, #[serde(skip_deserializing)] #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, pub merchant_connector_id: Option<String>, pub disabled: bool, pub test_mode: bool, pub payment_methods_enabled: Option<Vec<PaymentMethodsEnabled>>, pub metadata: Option<ApiModelMetaData>, pub connector_webhook_details: Option<api_models::admin::MerchantConnectorWebhookDetails>, } #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct DashboardPaymentMethodPayload { pub payment_method: api_models::enums::PaymentMethod, pub payment_method_type: String, pub provider: Option<Vec<Provider>>, pub card_provider: Option<Vec<CardProvider>>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde_with::skip_serializing_none] #[serde(rename_all = "snake_case")] pub struct DashboardRequestPayload { pub connector: api_models::enums::Connector, pub payment_methods_enabled: Option<Vec<DashboardPaymentMethodPayload>>, pub metadata: Option<ApiModelMetaData>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, serde::Serialize, Clone)] #[serde(tag = "type", content = "options")] pub enum InputType { Text, Number, Toggle, Radio(Vec<String>), Select(Vec<String>), MultiSelect(Vec<String>), } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, serde::Serialize, Clone)] #[serde(rename_all = "snake_case")] pub struct InputData { pub name: String, pub label: String, pub placeholder: String, pub required: bool, #[serde(flatten)] pub input_type: InputType, }
crates/connector_configs/src/common_config.rs
connector_configs::src::common_config
1,830
true
// File: crates/connector_configs/src/transformer.rs // Module: connector_configs::src::transformer use std::str::FromStr; use api_models::{ enums::{ Connector, PaymentMethod, PaymentMethodType::{self, AliPay, ApplePay, GooglePay, Klarna, Paypal, WeChatPay}, }, payment_methods, refunds::MinorUnit, }; use crate::common_config::{ ConnectorApiIntegrationPayload, DashboardRequestPayload, PaymentMethodsEnabled, Provider, }; impl DashboardRequestPayload { pub fn transform_card( payment_method_type: PaymentMethodType, card_provider: Vec<api_models::enums::CardNetwork>, ) -> payment_methods::RequestPaymentMethodTypes { payment_methods::RequestPaymentMethodTypes { payment_method_type, card_networks: Some(card_provider), minimum_amount: Some(MinorUnit::zero()), maximum_amount: Some(MinorUnit::new(68607706)), recurring_enabled: Some(true), installment_payment_enabled: Some(false), accepted_currencies: None, accepted_countries: None, payment_experience: None, } } pub fn get_payment_experience( connector: Connector, payment_method_type: PaymentMethodType, payment_method: PaymentMethod, payment_experience: Option<api_models::enums::PaymentExperience>, ) -> Option<api_models::enums::PaymentExperience> { match payment_method { PaymentMethod::BankRedirect => None, _ => match (connector, payment_method_type) { #[cfg(feature = "dummy_connector")] (Connector::DummyConnector4, _) | (Connector::DummyConnector7, _) => { Some(api_models::enums::PaymentExperience::RedirectToUrl) } (Connector::Paypal, Paypal) => payment_experience, (Connector::Klarna, Klarna) => payment_experience, (Connector::Zen, GooglePay) | (Connector::Zen, ApplePay) => { Some(api_models::enums::PaymentExperience::RedirectToUrl) } (Connector::Braintree, Paypal) => { Some(api_models::enums::PaymentExperience::InvokeSdkClient) } (Connector::Globepay, AliPay) | (Connector::Globepay, WeChatPay) | (Connector::Stripe, WeChatPay) => { Some(api_models::enums::PaymentExperience::DisplayQrCode) } (_, GooglePay) | (_, ApplePay) | (_, PaymentMethodType::SamsungPay) | (_, PaymentMethodType::Paze) | (_, PaymentMethodType::AmazonPay) => { Some(api_models::enums::PaymentExperience::InvokeSdkClient) } (_, PaymentMethodType::DirectCarrierBilling) => { Some(api_models::enums::PaymentExperience::CollectOtp) } (_, PaymentMethodType::Cashapp) | (_, PaymentMethodType::Swish) => { Some(api_models::enums::PaymentExperience::DisplayQrCode) } _ => Some(api_models::enums::PaymentExperience::RedirectToUrl), }, } } pub fn transform_payment_method( connector: Connector, provider: Vec<Provider>, payment_method: PaymentMethod, ) -> Vec<payment_methods::RequestPaymentMethodTypes> { let mut payment_method_types = Vec::new(); for method_type in provider { let data = payment_methods::RequestPaymentMethodTypes { payment_method_type: method_type.payment_method_type, card_networks: None, minimum_amount: Some(MinorUnit::zero()), maximum_amount: Some(MinorUnit::new(68607706)), recurring_enabled: Some(true), installment_payment_enabled: Some(false), accepted_currencies: method_type.accepted_currencies, accepted_countries: method_type.accepted_countries, payment_experience: Self::get_payment_experience( connector, method_type.payment_method_type, payment_method, method_type.payment_experience, ), }; payment_method_types.push(data) } payment_method_types } pub fn create_connector_request( request: Self, api_response: ConnectorApiIntegrationPayload, ) -> ConnectorApiIntegrationPayload { let mut card_payment_method_types = Vec::new(); let mut payment_method_enabled = Vec::new(); if let Some(payment_methods_enabled) = request.payment_methods_enabled.clone() { for payload in payment_methods_enabled { match payload.payment_method { PaymentMethod::Card => { if let Some(card_provider) = payload.card_provider { let payment_type = PaymentMethodType::from_str(&payload.payment_method_type) .map_err(|_| "Invalid key received".to_string()); if let Ok(payment_type) = payment_type { for method in card_provider { let data = payment_methods::RequestPaymentMethodTypes { payment_method_type: payment_type, card_networks: Some(vec![method.payment_method_type]), minimum_amount: Some(MinorUnit::zero()), maximum_amount: Some(MinorUnit::new(68607706)), recurring_enabled: Some(true), installment_payment_enabled: Some(false), accepted_currencies: method.accepted_currencies, accepted_countries: method.accepted_countries, payment_experience: None, }; card_payment_method_types.push(data) } } } } PaymentMethod::BankRedirect | PaymentMethod::Wallet | PaymentMethod::PayLater | PaymentMethod::BankTransfer | PaymentMethod::Crypto | PaymentMethod::BankDebit | PaymentMethod::Reward | PaymentMethod::RealTimePayment | PaymentMethod::Upi | PaymentMethod::Voucher | PaymentMethod::GiftCard | PaymentMethod::OpenBanking | PaymentMethod::CardRedirect | PaymentMethod::MobilePayment => { if let Some(provider) = payload.provider { let val = Self::transform_payment_method( request.connector, provider, payload.payment_method, ); if !val.is_empty() { let methods = PaymentMethodsEnabled { payment_method: payload.payment_method, payment_method_types: Some(val), }; payment_method_enabled.push(methods); } } } }; } if !card_payment_method_types.is_empty() { let card = PaymentMethodsEnabled { payment_method: PaymentMethod::Card, payment_method_types: Some(card_payment_method_types), }; payment_method_enabled.push(card); } } ConnectorApiIntegrationPayload { connector_type: api_response.connector_type, profile_id: api_response.profile_id, connector_name: api_response.connector_name, connector_label: api_response.connector_label, merchant_connector_id: api_response.merchant_connector_id, disabled: api_response.disabled, test_mode: api_response.test_mode, payment_methods_enabled: Some(payment_method_enabled), connector_webhook_details: api_response.connector_webhook_details, metadata: request.metadata, } } }
crates/connector_configs/src/transformer.rs
connector_configs::src::transformer
1,504
true
// File: crates/connector_configs/src/connector.rs // Module: connector_configs::src::connector use std::collections::HashMap; #[cfg(feature = "payouts")] use api_models::enums::PayoutConnectors; use api_models::{ enums::{AuthenticationConnectors, Connector, PmAuthConnectors, TaxConnectors}, payments, }; use serde::{Deserialize, Serialize}; use toml; use crate::common_config::{CardProvider, InputData, Provider, ZenApplePay}; #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct PayloadCurrencyAuthKeyType { pub api_key: String, pub processing_account_id: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct Classic { pub password_classic: String, pub username_classic: String, pub merchant_id_classic: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct Evoucher { pub password_evoucher: String, pub username_evoucher: String, pub merchant_id_evoucher: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct CashtoCodeCurrencyAuthKeyType { pub classic: Classic, pub evoucher: Evoucher, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CurrencyAuthValue { CashtoCode(CashtoCodeCurrencyAuthKeyType), Payload(PayloadCurrencyAuthKeyType), } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub enum ConnectorAuthType { HeaderKey { api_key: String, }, BodyKey { api_key: String, key1: String, }, SignatureKey { api_key: String, key1: String, api_secret: String, }, MultiAuthKey { api_key: String, key1: String, api_secret: String, key2: String, }, CurrencyAuthKey { auth_key_map: HashMap<String, CurrencyAuthValue>, }, CertificateAuth { certificate: String, private_key: String, }, #[default] NoKey, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(untagged)] pub enum ApplePayTomlConfig { Standard(Box<payments::ApplePayMetadata>), Zen(ZenApplePay), } #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum KlarnaEndpoint { Europe, NorthAmerica, Oceania, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ConfigMerchantAdditionalDetails { pub open_banking_recipient_data: Option<InputData>, pub account_data: Option<InputData>, pub iban: Option<Vec<InputData>>, pub bacs: Option<Vec<InputData>>, pub connector_recipient_id: Option<InputData>, pub wallet_id: Option<InputData>, pub faster_payments: Option<Vec<InputData>>, pub sepa: Option<Vec<InputData>>, pub sepa_instant: Option<Vec<InputData>>, pub elixir: Option<Vec<InputData>>, pub bankgiro: Option<Vec<InputData>>, pub plusgiro: Option<Vec<InputData>>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct AccountIdConfigForCard { pub three_ds: Option<Vec<InputData>>, pub no_three_ds: Option<Vec<InputData>>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct AccountIdConfigForRedirect { pub three_ds: Option<Vec<InputData>>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct AccountIdConfigForApplePay { pub encrypt: Option<Vec<InputData>>, pub decrypt: Option<Vec<InputData>>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct AccountIDSupportedMethods { apple_pay: HashMap<String, AccountIdConfigForApplePay>, card: HashMap<String, AccountIdConfigForCard>, interac: HashMap<String, AccountIdConfigForRedirect>, pay_safe_card: HashMap<String, AccountIdConfigForRedirect>, skrill: HashMap<String, AccountIdConfigForRedirect>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ConfigMetadata { pub merchant_config_currency: Option<InputData>, pub merchant_account_id: Option<InputData>, pub account_name: Option<InputData>, pub account_type: Option<InputData>, pub terminal_id: Option<InputData>, pub google_pay: Option<Vec<InputData>>, pub apple_pay: Option<Vec<InputData>>, pub merchant_id: Option<InputData>, pub endpoint_prefix: Option<InputData>, pub mcc: Option<InputData>, pub merchant_country_code: Option<InputData>, pub merchant_name: Option<InputData>, pub acquirer_bin: Option<InputData>, pub acquirer_merchant_id: Option<InputData>, pub acquirer_country_code: Option<InputData>, pub three_ds_requestor_name: Option<InputData>, pub three_ds_requestor_id: Option<InputData>, pub pull_mechanism_for_external_3ds_enabled: Option<InputData>, pub klarna_region: Option<InputData>, pub pricing_type: Option<InputData>, pub source_balance_account: Option<InputData>, pub brand_id: Option<InputData>, pub destination_account_number: Option<InputData>, pub dpa_id: Option<InputData>, pub dpa_name: Option<InputData>, pub locale: Option<InputData>, pub card_brands: Option<InputData>, pub merchant_category_code: Option<InputData>, pub merchant_configuration_id: Option<InputData>, pub currency_id: Option<InputData>, pub platform_id: Option<InputData>, pub ledger_account_id: Option<InputData>, pub tenant_id: Option<InputData>, pub platform_url: Option<InputData>, pub report_group: Option<InputData>, pub proxy_url: Option<InputData>, pub shop_name: Option<InputData>, pub merchant_funding_source: Option<InputData>, pub account_id: Option<AccountIDSupportedMethods>, pub name: Option<InputData>, pub client_merchant_reference_id: Option<InputData>, pub route: Option<InputData>, pub mid: Option<InputData>, pub tid: Option<InputData>, pub site: Option<InputData>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ConnectorWalletDetailsConfig { pub samsung_pay: Option<Vec<InputData>>, pub paze: Option<Vec<InputData>>, pub google_pay: Option<Vec<InputData>>, pub amazon_pay: Option<Vec<InputData>>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ConnectorTomlConfig { pub connector_auth: Option<ConnectorAuthType>, pub connector_webhook_details: Option<api_models::admin::MerchantConnectorWebhookDetails>, pub metadata: Option<Box<ConfigMetadata>>, pub connector_wallets_details: Option<Box<ConnectorWalletDetailsConfig>>, pub additional_merchant_data: Option<Box<ConfigMerchantAdditionalDetails>>, pub credit: Option<Vec<CardProvider>>, pub debit: Option<Vec<CardProvider>>, pub bank_transfer: Option<Vec<Provider>>, pub bank_redirect: Option<Vec<Provider>>, pub bank_debit: Option<Vec<Provider>>, pub open_banking: Option<Vec<Provider>>, pub pay_later: Option<Vec<Provider>>, pub wallet: Option<Vec<Provider>>, pub crypto: Option<Vec<Provider>>, pub reward: Option<Vec<Provider>>, pub upi: Option<Vec<Provider>>, pub voucher: Option<Vec<Provider>>, pub gift_card: Option<Vec<Provider>>, pub card_redirect: Option<Vec<Provider>>, pub is_verifiable: Option<bool>, pub real_time_payment: Option<Vec<Provider>>, } #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ConnectorConfig { pub authipay: Option<ConnectorTomlConfig>, pub juspaythreedsserver: Option<ConnectorTomlConfig>, pub katapult: Option<ConnectorTomlConfig>, pub aci: Option<ConnectorTomlConfig>, pub adyen: Option<ConnectorTomlConfig>, pub affirm: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub adyen_payout: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub adyenplatform_payout: Option<ConnectorTomlConfig>, pub airwallex: Option<ConnectorTomlConfig>, pub amazonpay: Option<ConnectorTomlConfig>, pub archipel: Option<ConnectorTomlConfig>, pub authorizedotnet: Option<ConnectorTomlConfig>, pub bamboraapac: Option<ConnectorTomlConfig>, pub bankofamerica: Option<ConnectorTomlConfig>, pub barclaycard: Option<ConnectorTomlConfig>, pub billwerk: Option<ConnectorTomlConfig>, pub bitpay: Option<ConnectorTomlConfig>, pub blackhawknetwork: Option<ConnectorTomlConfig>, pub calida: Option<ConnectorTomlConfig>, pub bluesnap: Option<ConnectorTomlConfig>, pub boku: Option<ConnectorTomlConfig>, pub braintree: Option<ConnectorTomlConfig>, pub breadpay: Option<ConnectorTomlConfig>, pub cardinal: Option<ConnectorTomlConfig>, pub cashtocode: Option<ConnectorTomlConfig>, pub celero: Option<ConnectorTomlConfig>, pub chargebee: Option<ConnectorTomlConfig>, pub custombilling: Option<ConnectorTomlConfig>, pub checkbook: Option<ConnectorTomlConfig>, pub checkout: Option<ConnectorTomlConfig>, pub coinbase: Option<ConnectorTomlConfig>, pub coingate: Option<ConnectorTomlConfig>, pub cryptopay: Option<ConnectorTomlConfig>, pub ctp_visa: Option<ConnectorTomlConfig>, pub cybersource: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub cybersource_payout: Option<ConnectorTomlConfig>, pub iatapay: Option<ConnectorTomlConfig>, pub itaubank: Option<ConnectorTomlConfig>, pub opennode: Option<ConnectorTomlConfig>, pub bambora: Option<ConnectorTomlConfig>, pub datatrans: Option<ConnectorTomlConfig>, pub deutschebank: Option<ConnectorTomlConfig>, pub digitalvirgo: Option<ConnectorTomlConfig>, pub dlocal: Option<ConnectorTomlConfig>, pub dwolla: Option<ConnectorTomlConfig>, pub ebanx_payout: Option<ConnectorTomlConfig>, pub elavon: Option<ConnectorTomlConfig>, pub facilitapay: Option<ConnectorTomlConfig>, pub finix: Option<ConnectorTomlConfig>, pub fiserv: Option<ConnectorTomlConfig>, pub fiservemea: Option<ConnectorTomlConfig>, pub fiuu: Option<ConnectorTomlConfig>, pub flexiti: Option<ConnectorTomlConfig>, pub forte: Option<ConnectorTomlConfig>, pub getnet: Option<ConnectorTomlConfig>, pub gigadat: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub gigadat_payout: Option<ConnectorTomlConfig>, pub globalpay: Option<ConnectorTomlConfig>, pub globepay: Option<ConnectorTomlConfig>, pub gocardless: Option<ConnectorTomlConfig>, pub gpayments: Option<ConnectorTomlConfig>, pub hipay: Option<ConnectorTomlConfig>, pub helcim: Option<ConnectorTomlConfig>, pub hyperswitch_vault: Option<ConnectorTomlConfig>, pub hyperwallet: Option<ConnectorTomlConfig>, pub inespay: Option<ConnectorTomlConfig>, pub jpmorgan: Option<ConnectorTomlConfig>, pub klarna: Option<ConnectorTomlConfig>, pub loonio: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub loonio_payout: Option<ConnectorTomlConfig>, pub mifinity: Option<ConnectorTomlConfig>, pub mollie: Option<ConnectorTomlConfig>, pub moneris: Option<ConnectorTomlConfig>, pub mpgs: Option<ConnectorTomlConfig>, pub multisafepay: Option<ConnectorTomlConfig>, pub nexinets: Option<ConnectorTomlConfig>, pub nexixpay: Option<ConnectorTomlConfig>, pub nmi: Option<ConnectorTomlConfig>, pub nomupay_payout: Option<ConnectorTomlConfig>, pub noon: Option<ConnectorTomlConfig>, pub nordea: Option<ConnectorTomlConfig>, pub novalnet: Option<ConnectorTomlConfig>, pub nuvei_payout: Option<ConnectorTomlConfig>, pub nuvei: Option<ConnectorTomlConfig>, pub paybox: Option<ConnectorTomlConfig>, pub payload: Option<ConnectorTomlConfig>, pub payme: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub payone_payout: Option<ConnectorTomlConfig>, pub paypal: Option<ConnectorTomlConfig>, pub paysafe: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub paypal_payout: Option<ConnectorTomlConfig>, pub paystack: Option<ConnectorTomlConfig>, pub paytm: Option<ConnectorTomlConfig>, pub payu: Option<ConnectorTomlConfig>, pub peachpayments: Option<ConnectorTomlConfig>, pub phonepe: Option<ConnectorTomlConfig>, pub placetopay: Option<ConnectorTomlConfig>, pub plaid: Option<ConnectorTomlConfig>, pub powertranz: Option<ConnectorTomlConfig>, pub prophetpay: Option<ConnectorTomlConfig>, pub razorpay: Option<ConnectorTomlConfig>, pub recurly: Option<ConnectorTomlConfig>, pub riskified: Option<ConnectorTomlConfig>, pub rapyd: Option<ConnectorTomlConfig>, pub redsys: Option<ConnectorTomlConfig>, pub santander: Option<ConnectorTomlConfig>, pub shift4: Option<ConnectorTomlConfig>, pub sift: Option<ConnectorTomlConfig>, pub silverflow: Option<ConnectorTomlConfig>, pub stripe: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub stripe_payout: Option<ConnectorTomlConfig>, pub stripebilling: Option<ConnectorTomlConfig>, pub signifyd: Option<ConnectorTomlConfig>, pub tersouro: Option<ConnectorTomlConfig>, pub tokenex: Option<ConnectorTomlConfig>, pub tokenio: Option<ConnectorTomlConfig>, pub trustpay: Option<ConnectorTomlConfig>, pub trustpayments: Option<ConnectorTomlConfig>, pub threedsecureio: Option<ConnectorTomlConfig>, pub netcetera: Option<ConnectorTomlConfig>, pub tsys: Option<ConnectorTomlConfig>, pub vgs: Option<ConnectorTomlConfig>, pub volt: Option<ConnectorTomlConfig>, pub wellsfargo: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub wise_payout: Option<ConnectorTomlConfig>, pub worldline: Option<ConnectorTomlConfig>, pub worldpay: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub worldpay_payout: Option<ConnectorTomlConfig>, pub worldpayvantiv: Option<ConnectorTomlConfig>, pub worldpayxml: Option<ConnectorTomlConfig>, pub xendit: Option<ConnectorTomlConfig>, pub square: Option<ConnectorTomlConfig>, pub stax: Option<ConnectorTomlConfig>, pub dummy_connector: Option<ConnectorTomlConfig>, pub stripe_test: Option<ConnectorTomlConfig>, pub paypal_test: Option<ConnectorTomlConfig>, pub zen: Option<ConnectorTomlConfig>, pub zsl: Option<ConnectorTomlConfig>, pub taxjar: Option<ConnectorTomlConfig>, pub tesouro: Option<ConnectorTomlConfig>, pub ctp_mastercard: Option<ConnectorTomlConfig>, pub unified_authentication_service: Option<ConnectorTomlConfig>, } impl ConnectorConfig { fn new() -> Result<Self, String> { let config_str = if cfg!(feature = "production") { include_str!("../toml/production.toml") } else if cfg!(feature = "sandbox") { include_str!("../toml/sandbox.toml") } else { include_str!("../toml/development.toml") }; let config = toml::from_str::<Self>(config_str); match config { Ok(data) => Ok(data), Err(err) => Err(err.to_string()), } } #[cfg(feature = "payouts")] pub fn get_payout_connector_config( connector: PayoutConnectors, ) -> Result<Option<ConnectorTomlConfig>, String> { let connector_data = Self::new()?; match connector { PayoutConnectors::Adyen => Ok(connector_data.adyen_payout), PayoutConnectors::Adyenplatform => Ok(connector_data.adyenplatform_payout), PayoutConnectors::Cybersource => Ok(connector_data.cybersource_payout), PayoutConnectors::Ebanx => Ok(connector_data.ebanx_payout), PayoutConnectors::Gigadat => Ok(connector_data.gigadat_payout), PayoutConnectors::Loonio => Ok(connector_data.loonio_payout), PayoutConnectors::Nomupay => Ok(connector_data.nomupay_payout), PayoutConnectors::Nuvei => Ok(connector_data.nuvei_payout), PayoutConnectors::Payone => Ok(connector_data.payone_payout), PayoutConnectors::Paypal => Ok(connector_data.paypal_payout), PayoutConnectors::Stripe => Ok(connector_data.stripe_payout), PayoutConnectors::Wise => Ok(connector_data.wise_payout), PayoutConnectors::Worldpay => Ok(connector_data.worldpay_payout), } } pub fn get_authentication_connector_config( connector: AuthenticationConnectors, ) -> Result<Option<ConnectorTomlConfig>, String> { let connector_data = Self::new()?; match connector { AuthenticationConnectors::Threedsecureio => Ok(connector_data.threedsecureio), AuthenticationConnectors::Netcetera => Ok(connector_data.netcetera), AuthenticationConnectors::Gpayments => Ok(connector_data.gpayments), AuthenticationConnectors::CtpMastercard => Ok(connector_data.ctp_mastercard), AuthenticationConnectors::CtpVisa => Ok(connector_data.ctp_visa), AuthenticationConnectors::UnifiedAuthenticationService => { Ok(connector_data.unified_authentication_service) } AuthenticationConnectors::Juspaythreedsserver => Ok(connector_data.juspaythreedsserver), AuthenticationConnectors::Cardinal => Ok(connector_data.cardinal), } } pub fn get_tax_processor_config( connector: TaxConnectors, ) -> Result<Option<ConnectorTomlConfig>, String> { let connector_data = Self::new()?; match connector { TaxConnectors::Taxjar => Ok(connector_data.taxjar), } } pub fn get_pm_authentication_processor_config( connector: PmAuthConnectors, ) -> Result<Option<ConnectorTomlConfig>, String> { let connector_data = Self::new()?; match connector { PmAuthConnectors::Plaid => Ok(connector_data.plaid), } } pub fn get_connector_config( connector: Connector, ) -> Result<Option<ConnectorTomlConfig>, String> { let connector_data = Self::new()?; match connector { Connector::Aci => Ok(connector_data.aci), Connector::Authipay => Ok(connector_data.authipay), Connector::Adyen => Ok(connector_data.adyen), Connector::Affirm => Ok(connector_data.affirm), Connector::Adyenplatform => Err("Use get_payout_connector_config".to_string()), Connector::Airwallex => Ok(connector_data.airwallex), Connector::Amazonpay => Ok(connector_data.amazonpay), Connector::Archipel => Ok(connector_data.archipel), Connector::Authorizedotnet => Ok(connector_data.authorizedotnet), Connector::Bamboraapac => Ok(connector_data.bamboraapac), Connector::Bankofamerica => Ok(connector_data.bankofamerica), Connector::Barclaycard => Ok(connector_data.barclaycard), Connector::Billwerk => Ok(connector_data.billwerk), Connector::Bitpay => Ok(connector_data.bitpay), Connector::Bluesnap => Ok(connector_data.bluesnap), Connector::Calida => Ok(connector_data.calida), Connector::Blackhawknetwork => Ok(connector_data.blackhawknetwork), Connector::Boku => Ok(connector_data.boku), Connector::Braintree => Ok(connector_data.braintree), Connector::Breadpay => Ok(connector_data.breadpay), Connector::Cashtocode => Ok(connector_data.cashtocode), Connector::Cardinal => Ok(connector_data.cardinal), Connector::Celero => Ok(connector_data.celero), Connector::Chargebee => Ok(connector_data.chargebee), Connector::Checkbook => Ok(connector_data.checkbook), Connector::Checkout => Ok(connector_data.checkout), Connector::Coinbase => Ok(connector_data.coinbase), Connector::Coingate => Ok(connector_data.coingate), Connector::Cryptopay => Ok(connector_data.cryptopay), Connector::CtpVisa => Ok(connector_data.ctp_visa), Connector::Custombilling => Ok(connector_data.custombilling), Connector::Cybersource => Ok(connector_data.cybersource), #[cfg(feature = "dummy_connector")] Connector::DummyBillingConnector => Ok(connector_data.dummy_connector), Connector::Iatapay => Ok(connector_data.iatapay), Connector::Itaubank => Ok(connector_data.itaubank), Connector::Opennode => Ok(connector_data.opennode), Connector::Bambora => Ok(connector_data.bambora), Connector::Datatrans => Ok(connector_data.datatrans), Connector::Deutschebank => Ok(connector_data.deutschebank), Connector::Digitalvirgo => Ok(connector_data.digitalvirgo), Connector::Dlocal => Ok(connector_data.dlocal), Connector::Dwolla => Ok(connector_data.dwolla), Connector::Ebanx => Ok(connector_data.ebanx_payout), Connector::Elavon => Ok(connector_data.elavon), Connector::Facilitapay => Ok(connector_data.facilitapay), Connector::Finix => Ok(connector_data.finix), Connector::Fiserv => Ok(connector_data.fiserv), Connector::Fiservemea => Ok(connector_data.fiservemea), Connector::Fiuu => Ok(connector_data.fiuu), Connector::Flexiti => Ok(connector_data.flexiti), Connector::Forte => Ok(connector_data.forte), Connector::Getnet => Ok(connector_data.getnet), Connector::Gigadat => Ok(connector_data.gigadat), Connector::Globalpay => Ok(connector_data.globalpay), Connector::Globepay => Ok(connector_data.globepay), Connector::Gocardless => Ok(connector_data.gocardless), Connector::Gpayments => Ok(connector_data.gpayments), Connector::Hipay => Ok(connector_data.hipay), Connector::HyperswitchVault => Ok(connector_data.hyperswitch_vault), Connector::Helcim => Ok(connector_data.helcim), Connector::Inespay => Ok(connector_data.inespay), Connector::Jpmorgan => Ok(connector_data.jpmorgan), Connector::Juspaythreedsserver => Ok(connector_data.juspaythreedsserver), Connector::Klarna => Ok(connector_data.klarna), Connector::Loonio => Ok(connector_data.loonio), Connector::Mifinity => Ok(connector_data.mifinity), Connector::Mollie => Ok(connector_data.mollie), Connector::Moneris => Ok(connector_data.moneris), Connector::Multisafepay => Ok(connector_data.multisafepay), Connector::Nexinets => Ok(connector_data.nexinets), Connector::Nexixpay => Ok(connector_data.nexixpay), Connector::Prophetpay => Ok(connector_data.prophetpay), Connector::Nmi => Ok(connector_data.nmi), Connector::Nordea => Ok(connector_data.nordea), Connector::Nomupay => Err("Use get_payout_connector_config".to_string()), Connector::Novalnet => Ok(connector_data.novalnet), Connector::Noon => Ok(connector_data.noon), Connector::Nuvei => Ok(connector_data.nuvei), Connector::Paybox => Ok(connector_data.paybox), Connector::Payload => Ok(connector_data.payload), Connector::Payme => Ok(connector_data.payme), Connector::Payone => Err("Use get_payout_connector_config".to_string()), Connector::Paypal => Ok(connector_data.paypal), Connector::Paysafe => Ok(connector_data.paysafe), Connector::Paystack => Ok(connector_data.paystack), Connector::Payu => Ok(connector_data.payu), Connector::Peachpayments => Ok(connector_data.peachpayments), Connector::Placetopay => Ok(connector_data.placetopay), Connector::Plaid => Ok(connector_data.plaid), Connector::Powertranz => Ok(connector_data.powertranz), Connector::Razorpay => Ok(connector_data.razorpay), Connector::Rapyd => Ok(connector_data.rapyd), Connector::Recurly => Ok(connector_data.recurly), Connector::Redsys => Ok(connector_data.redsys), Connector::Riskified => Ok(connector_data.riskified), Connector::Santander => Ok(connector_data.santander), Connector::Shift4 => Ok(connector_data.shift4), Connector::Signifyd => Ok(connector_data.signifyd), Connector::Silverflow => Ok(connector_data.silverflow), Connector::Square => Ok(connector_data.square), Connector::Stax => Ok(connector_data.stax), Connector::Stripe => Ok(connector_data.stripe), Connector::Stripebilling => Ok(connector_data.stripebilling), Connector::Tesouro => Ok(connector_data.tesouro), Connector::Tokenex => Ok(connector_data.tokenex), Connector::Tokenio => Ok(connector_data.tokenio), Connector::Trustpay => Ok(connector_data.trustpay), Connector::Trustpayments => Ok(connector_data.trustpayments), Connector::Threedsecureio => Ok(connector_data.threedsecureio), Connector::Taxjar => Ok(connector_data.taxjar), Connector::Tsys => Ok(connector_data.tsys), Connector::Vgs => Ok(connector_data.vgs), Connector::Volt => Ok(connector_data.volt), Connector::Wellsfargo => Ok(connector_data.wellsfargo), Connector::Wise => Err("Use get_payout_connector_config".to_string()), Connector::Worldline => Ok(connector_data.worldline), Connector::Worldpay => Ok(connector_data.worldpay), Connector::Worldpayvantiv => Ok(connector_data.worldpayvantiv), Connector::Worldpayxml => Ok(connector_data.worldpayxml), Connector::Zen => Ok(connector_data.zen), Connector::Zsl => Ok(connector_data.zsl), #[cfg(feature = "dummy_connector")] Connector::DummyConnector1 => Ok(connector_data.dummy_connector), #[cfg(feature = "dummy_connector")] Connector::DummyConnector2 => Ok(connector_data.dummy_connector), #[cfg(feature = "dummy_connector")] Connector::DummyConnector3 => Ok(connector_data.dummy_connector), #[cfg(feature = "dummy_connector")] Connector::DummyConnector4 => Ok(connector_data.stripe_test), #[cfg(feature = "dummy_connector")] Connector::DummyConnector5 => Ok(connector_data.dummy_connector), #[cfg(feature = "dummy_connector")] Connector::DummyConnector6 => Ok(connector_data.dummy_connector), #[cfg(feature = "dummy_connector")] Connector::DummyConnector7 => Ok(connector_data.paypal_test), Connector::Netcetera => Ok(connector_data.netcetera), Connector::CtpMastercard => Ok(connector_data.ctp_mastercard), Connector::Xendit => Ok(connector_data.xendit), Connector::Paytm => Ok(connector_data.paytm), Connector::Phonepe => Ok(connector_data.phonepe), } } }
crates/connector_configs/src/connector.rs
connector_configs::src::connector
6,448
true
// File: crates/test_utils/src/lib.rs // Module: test_utils::src::lib #![allow(clippy::print_stdout, clippy::print_stderr)] pub mod connector_auth; pub mod newman_runner;
crates/test_utils/src/lib.rs
test_utils::src::lib
45
true
// File: crates/test_utils/src/connector_auth.rs // Module: test_utils::src::connector_auth use std::{collections::HashMap, env}; use masking::Secret; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ConnectorAuthentication { pub aci: Option<BodyKey>, #[cfg(not(feature = "payouts"))] pub adyen: Option<BodyKey>, #[cfg(feature = "payouts")] pub adyenplatform: Option<HeaderKey>, pub affirm: Option<HeaderKey>, #[cfg(feature = "payouts")] pub adyen: Option<SignatureKey>, #[cfg(not(feature = "payouts"))] pub adyen_uk: Option<BodyKey>, #[cfg(feature = "payouts")] pub adyen_uk: Option<SignatureKey>, pub airwallex: Option<BodyKey>, pub amazonpay: Option<BodyKey>, pub archipel: Option<NoKey>, pub authipay: Option<SignatureKey>, pub authorizedotnet: Option<BodyKey>, pub bambora: Option<BodyKey>, pub bamboraapac: Option<HeaderKey>, pub bankofamerica: Option<SignatureKey>, pub barclaycard: Option<SignatureKey>, pub billwerk: Option<HeaderKey>, pub bitpay: Option<HeaderKey>, pub blackhawknetwork: Option<HeaderKey>, pub calida: Option<HeaderKey>, pub bluesnap: Option<BodyKey>, pub boku: Option<BodyKey>, pub breadpay: Option<BodyKey>, pub cardinal: Option<SignatureKey>, pub cashtocode: Option<BodyKey>, pub celero: Option<HeaderKey>, pub chargebee: Option<HeaderKey>, pub checkbook: Option<BodyKey>, pub checkout: Option<SignatureKey>, pub coinbase: Option<HeaderKey>, pub coingate: Option<HeaderKey>, pub cryptopay: Option<BodyKey>, pub cybersource: Option<SignatureKey>, pub datatrans: Option<HeaderKey>, pub deutschebank: Option<SignatureKey>, pub digitalvirgo: Option<HeaderKey>, pub dlocal: Option<SignatureKey>, #[cfg(feature = "dummy_connector")] pub dummyconnector: Option<HeaderKey>, pub dwolla: Option<HeaderKey>, pub ebanx: Option<HeaderKey>, pub elavon: Option<HeaderKey>, pub facilitapay: Option<BodyKey>, pub finix: Option<HeaderKey>, pub fiserv: Option<SignatureKey>, pub fiservemea: Option<HeaderKey>, pub fiuu: Option<HeaderKey>, pub flexiti: Option<HeaderKey>, pub forte: Option<MultiAuthKey>, pub getnet: Option<HeaderKey>, pub gigadat: Option<SignatureKey>, pub globalpay: Option<BodyKey>, pub globepay: Option<BodyKey>, pub gocardless: Option<HeaderKey>, pub gpayments: Option<HeaderKey>, pub helcim: Option<HeaderKey>, pub hipay: Option<HeaderKey>, pub hyperswitch_vault: Option<SignatureKey>, pub hyperwallet: Option<BodyKey>, pub iatapay: Option<SignatureKey>, pub inespay: Option<HeaderKey>, pub itaubank: Option<MultiAuthKey>, pub jpmorgan: Option<BodyKey>, pub juspaythreedsserver: Option<HeaderKey>, pub katapult: Option<HeaderKey>, pub loonio: Option<HeaderKey>, pub mifinity: Option<HeaderKey>, pub mollie: Option<BodyKey>, pub moneris: Option<SignatureKey>, pub mpgs: Option<HeaderKey>, pub multisafepay: Option<HeaderKey>, pub netcetera: Option<HeaderKey>, pub nexinets: Option<BodyKey>, pub nexixpay: Option<HeaderKey>, pub nomupay: Option<BodyKey>, pub noon: Option<SignatureKey>, pub nordea: Option<SignatureKey>, pub novalnet: Option<HeaderKey>, pub nmi: Option<HeaderKey>, pub nuvei: Option<SignatureKey>, pub opayo: Option<HeaderKey>, pub opennode: Option<HeaderKey>, pub paybox: Option<HeaderKey>, pub payeezy: Option<SignatureKey>, pub payload: Option<CurrencyAuthKey>, pub payme: Option<BodyKey>, pub payone: Option<HeaderKey>, pub paypal: Option<BodyKey>, pub paysafe: Option<BodyKey>, pub paystack: Option<HeaderKey>, pub paytm: Option<HeaderKey>, pub payu: Option<BodyKey>, pub peachpayments: Option<HeaderKey>, pub phonepe: Option<HeaderKey>, pub placetopay: Option<BodyKey>, pub plaid: Option<BodyKey>, pub powertranz: Option<BodyKey>, pub prophetpay: Option<HeaderKey>, pub rapyd: Option<BodyKey>, pub razorpay: Option<BodyKey>, pub recurly: Option<HeaderKey>, pub redsys: Option<HeaderKey>, pub santander: Option<BodyKey>, pub shift4: Option<HeaderKey>, pub sift: Option<HeaderKey>, pub silverflow: Option<SignatureKey>, pub square: Option<BodyKey>, pub stax: Option<HeaderKey>, pub stripe: Option<HeaderKey>, pub stripebilling: Option<HeaderKey>, pub taxjar: Option<HeaderKey>, pub tesouro: Option<HeaderKey>, pub threedsecureio: Option<HeaderKey>, pub thunes: Option<HeaderKey>, pub tokenex: Option<BodyKey>, pub tokenio: Option<HeaderKey>, pub stripe_au: Option<HeaderKey>, pub stripe_uk: Option<HeaderKey>, pub trustpay: Option<SignatureKey>, pub trustpayments: Option<HeaderKey>, pub tsys: Option<SignatureKey>, pub unified_authentication_service: Option<HeaderKey>, pub vgs: Option<SignatureKey>, pub volt: Option<HeaderKey>, pub wellsfargo: Option<HeaderKey>, // pub wellsfargopayout: Option<HeaderKey>, pub wise: Option<BodyKey>, pub worldpay: Option<BodyKey>, pub worldpayvantiv: Option<HeaderKey>, pub worldpayxml: Option<HeaderKey>, pub xendit: Option<HeaderKey>, pub worldline: Option<SignatureKey>, pub zen: Option<HeaderKey>, pub zsl: Option<BodyKey>, pub automation_configs: Option<AutomationConfigs>, pub users: Option<UsersConfigs>, } impl Default for ConnectorAuthentication { fn default() -> Self { Self::new() } } #[allow(dead_code)] impl ConnectorAuthentication { /// # Panics /// /// Will panic if `CONNECTOR_AUTH_FILE_PATH` env is not set #[allow(clippy::expect_used)] pub fn new() -> Self { // Do `export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml"` // before running tests in shell let path = env::var("CONNECTOR_AUTH_FILE_PATH") .expect("Connector authentication file path not set"); toml::from_str( &std::fs::read_to_string(path).expect("connector authentication config file not found"), ) .expect("Failed to read connector authentication config file") } } #[derive(Clone, Debug, Deserialize)] pub struct ConnectorAuthenticationMap(HashMap<String, ConnectorAuthType>); impl Default for ConnectorAuthenticationMap { fn default() -> Self { Self::new() } } // This is a temporary solution to avoid rust compiler from complaining about unused function #[allow(dead_code)] impl ConnectorAuthenticationMap { pub fn inner(&self) -> &HashMap<String, ConnectorAuthType> { &self.0 } /// # Panics /// /// Will panic if `CONNECTOR_AUTH_FILE_PATH` env is not set #[allow(clippy::expect_used)] pub fn new() -> Self { // Do `export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml"` // before running tests in shell let path = env::var("CONNECTOR_AUTH_FILE_PATH") .expect("connector authentication file path not set"); // Read the file contents to a JsonString let contents = &std::fs::read_to_string(path).expect("Failed to read connector authentication file"); // Deserialize the JsonString to a HashMap let auth_config: HashMap<String, toml::Value> = toml::from_str(contents).expect("Failed to deserialize TOML file"); // auth_config contains the data in below given format: // { // "connector_name": Table( // { // "api_key": String( // "API_Key", // ), // "api_secret": String( // "Secret key", // ), // "key1": String( // "key1", // ), // "key2": String( // "key2", // ), // }, // ), // "connector_name": Table( // ... // } // auth_map refines and extracts required information let auth_map = auth_config .into_iter() .map(|(connector_name, config)| { let auth_type = match config { toml::Value::Table(mut table) => { if let Some(auth_key_map_value) = table.remove("auth_key_map") { // This is a CurrencyAuthKey if let toml::Value::Table(auth_key_map_table) = auth_key_map_value { let mut parsed_auth_map = HashMap::new(); for (currency, val) in auth_key_map_table { if let Ok(currency_enum) = currency.parse::<common_enums::Currency>() { parsed_auth_map .insert(currency_enum, Secret::new(val.to_string())); } } ConnectorAuthType::CurrencyAuthKey { auth_key_map: parsed_auth_map, } } else { ConnectorAuthType::NoKey } } else { match ( table.get("api_key"), table.get("key1"), table.get("api_secret"), table.get("key2"), ) { (Some(api_key), None, None, None) => ConnectorAuthType::HeaderKey { api_key: Secret::new( api_key.as_str().unwrap_or_default().to_string(), ), }, (Some(api_key), Some(key1), None, None) => { ConnectorAuthType::BodyKey { api_key: Secret::new( api_key.as_str().unwrap_or_default().to_string(), ), key1: Secret::new( key1.as_str().unwrap_or_default().to_string(), ), } } (Some(api_key), Some(key1), Some(api_secret), None) => { ConnectorAuthType::SignatureKey { api_key: Secret::new( api_key.as_str().unwrap_or_default().to_string(), ), key1: Secret::new( key1.as_str().unwrap_or_default().to_string(), ), api_secret: Secret::new( api_secret.as_str().unwrap_or_default().to_string(), ), } } (Some(api_key), Some(key1), Some(api_secret), Some(key2)) => { ConnectorAuthType::MultiAuthKey { api_key: Secret::new( api_key.as_str().unwrap_or_default().to_string(), ), key1: Secret::new( key1.as_str().unwrap_or_default().to_string(), ), api_secret: Secret::new( api_secret.as_str().unwrap_or_default().to_string(), ), key2: Secret::new( key2.as_str().unwrap_or_default().to_string(), ), } } _ => ConnectorAuthType::NoKey, } } } _ => ConnectorAuthType::NoKey, }; (connector_name, auth_type) }) .collect(); Self(auth_map) } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct HeaderKey { pub api_key: Secret<String>, } impl From<HeaderKey> for ConnectorAuthType { fn from(key: HeaderKey) -> Self { Self::HeaderKey { api_key: key.api_key, } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct BodyKey { pub api_key: Secret<String>, pub key1: Secret<String>, } impl From<BodyKey> for ConnectorAuthType { fn from(key: BodyKey) -> Self { Self::BodyKey { api_key: key.api_key, key1: key.key1, } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct SignatureKey { pub api_key: Secret<String>, pub key1: Secret<String>, pub api_secret: Secret<String>, } impl From<SignatureKey> for ConnectorAuthType { fn from(key: SignatureKey) -> Self { Self::SignatureKey { api_key: key.api_key, key1: key.key1, api_secret: key.api_secret, } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct MultiAuthKey { pub api_key: Secret<String>, pub key1: Secret<String>, pub api_secret: Secret<String>, pub key2: Secret<String>, } impl From<MultiAuthKey> for ConnectorAuthType { fn from(key: MultiAuthKey) -> Self { Self::MultiAuthKey { api_key: key.api_key, key1: key.key1, api_secret: key.api_secret, key2: key.key2, } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct CurrencyAuthKey { pub auth_key_map: HashMap<String, toml::Value>, } impl From<CurrencyAuthKey> for ConnectorAuthType { fn from(key: CurrencyAuthKey) -> Self { let mut auth_map = HashMap::new(); for (currency, auth_data) in key.auth_key_map { if let Ok(currency_enum) = currency.parse::<common_enums::Currency>() { auth_map.insert(currency_enum, Secret::new(auth_data.to_string())); } } Self::CurrencyAuthKey { auth_key_map: auth_map, } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct NoKey {} #[derive(Debug, Serialize, Deserialize, Clone)] pub struct AutomationConfigs { pub hs_base_url: Option<String>, pub hs_api_key: Option<String>, pub hs_api_keys: Option<String>, pub hs_webhook_url: Option<String>, pub hs_test_env: Option<String>, pub hs_test_browser: Option<String>, pub chrome_profile_path: Option<String>, pub firefox_profile_path: Option<String>, pub pypl_email: Option<String>, pub pypl_pass: Option<String>, pub gmail_email: Option<String>, pub gmail_pass: Option<String>, pub clearpay_email: Option<String>, pub clearpay_pass: Option<String>, pub configs_url: Option<String>, pub stripe_pub_key: Option<String>, pub testcases_path: Option<String>, pub bluesnap_gateway_merchant_id: Option<String>, pub globalpay_gateway_merchant_id: Option<String>, pub authorizedotnet_gateway_merchant_id: Option<String>, pub run_minimum_steps: Option<bool>, pub airwallex_merchant_name: Option<String>, pub adyen_bancontact_username: Option<String>, pub adyen_bancontact_pass: Option<String>, } #[derive(Default, Debug, Clone, serde::Deserialize)] #[serde(tag = "auth_type")] pub enum ConnectorAuthType { 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::Currency, Secret<String>>, }, #[default] NoKey, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct UsersConfigs { pub user_email: String, pub user_password: String, pub wrong_password: String, pub user_base_email_for_signup: String, pub user_domain_for_signup: String, }
crates/test_utils/src/connector_auth.rs
test_utils::src::connector_auth
3,710
true
// File: crates/test_utils/src/newman_runner.rs // Module: test_utils::src::newman_runner use std::{ env, fs::{self, OpenOptions}, io::{self, Write}, path::Path, process::{exit, Command}, }; use anyhow::{Context, Result}; use clap::{arg, command, Parser, ValueEnum}; use masking::PeekInterface; use regex::Regex; use crate::connector_auth::{ ConnectorAuthType, ConnectorAuthentication, ConnectorAuthenticationMap, }; #[derive(ValueEnum, Clone, Copy)] pub enum Module { Connector, Users, } #[derive(Parser)] #[command(version, about = "Postman collection runner using newman!", long_about = None)] pub struct Args { /// Admin API Key of the environment #[arg(short, long)] admin_api_key: String, /// Base URL of the Hyperswitch environment #[arg(short, long)] base_url: String, /// Name of the connector #[arg(short, long)] connector_name: Option<String>, /// Name of the module #[arg(short, long)] module_name: Option<Module>, /// Custom headers #[arg(short = 'H', long = "header")] custom_headers: Option<Vec<String>>, /// Minimum delay in milliseconds to be added before sending a request /// By default, 7 milliseconds will be the delay #[arg(short, long, default_value_t = 7)] delay_request: u32, /// Folder name of specific tests #[arg(short, long = "folder")] folders: Option<String>, /// Optional Verbose logs #[arg(short, long)] verbose: bool, } impl Args { /// Getter for the `module_name` field pub fn get_module_name(&self) -> Option<Module> { self.module_name } } pub struct ReturnArgs { pub newman_command: Command, pub modified_file_paths: Vec<Option<String>>, pub collection_path: String, } // Generates the name of the collection JSON file for the specified connector. // Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-json/stripe.postman_collection.json #[inline] fn get_collection_path(name: impl AsRef<str>) -> String { format!( "postman/collection-json/{}.postman_collection.json", name.as_ref() ) } // Generates the name of the collection directory for the specified connector. // Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-dir/stripe #[inline] fn get_dir_path(name: impl AsRef<str>) -> String { format!("postman/collection-dir/{}", name.as_ref()) } // This function currently allows you to add only custom headers. // In future, as we scale, this can be modified based on the need fn insert_content<T, U>(dir: T, content_to_insert: U) -> io::Result<()> where T: AsRef<Path>, U: AsRef<str>, { let file_name = "event.prerequest.js"; let file_path = dir.as_ref().join(file_name); // Open the file in write mode or create it if it doesn't exist let mut file = OpenOptions::new() .append(true) .create(true) .open(file_path)?; write!(file, "{}", content_to_insert.as_ref())?; Ok(()) } // This function gives runner for connector or a module pub fn generate_runner() -> Result<ReturnArgs> { let args = Args::parse(); match args.get_module_name() { Some(Module::Users) => generate_newman_command_for_users(), Some(Module::Connector) => generate_newman_command_for_connector(), // Running connector tests when no module is passed to keep the previous test behavior same None => generate_newman_command_for_connector(), } } pub fn generate_newman_command_for_users() -> Result<ReturnArgs> { let args = Args::parse(); let base_url = args.base_url; let admin_api_key = args.admin_api_key; let path = env::var("CONNECTOR_AUTH_FILE_PATH") .with_context(|| "connector authentication file path not set")?; let authentication: ConnectorAuthentication = toml::from_str( &fs::read_to_string(path) .with_context(|| "connector authentication config file not found")?, ) .with_context(|| "connector authentication file path not set")?; let users_configs = authentication .users .with_context(|| "user configs not found in authentication file")?; let collection_path = get_collection_path("users"); let mut newman_command = Command::new("newman"); newman_command.args(["run", &collection_path]); newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]); newman_command.args(["--env-var", &format!("baseUrl={base_url}")]); newman_command.args([ "--env-var", &format!("user_email={}", users_configs.user_email), ]); newman_command.args([ "--env-var", &format!( "user_base_email_for_signup={}", users_configs.user_base_email_for_signup ), ]); newman_command.args([ "--env-var", &format!( "user_domain_for_signup={}", users_configs.user_domain_for_signup ), ]); newman_command.args([ "--env-var", &format!("user_password={}", users_configs.user_password), ]); newman_command.args([ "--env-var", &format!("wrong_password={}", users_configs.wrong_password), ]); newman_command.args([ "--delay-request", format!("{}", &args.delay_request).as_str(), ]); newman_command.arg("--color").arg("on"); if args.verbose { newman_command.arg("--verbose"); } Ok(ReturnArgs { newman_command, modified_file_paths: vec![], collection_path, }) } pub fn generate_newman_command_for_connector() -> Result<ReturnArgs> { let args = Args::parse(); let connector_name = args .connector_name .with_context(|| "invalid parameters: connector/module name not found in arguments")?; let base_url = args.base_url; let admin_api_key = args.admin_api_key; let collection_path = get_collection_path(&connector_name); let collection_dir_path = get_dir_path(&connector_name); let auth_map = ConnectorAuthenticationMap::new(); let inner_map = auth_map.inner(); /* Newman runner Certificate keys are added through secrets in CI, so there's no need to explicitly pass it as arguments. It can be overridden by explicitly passing certificates as arguments. If the collection requires certificates (Stripe collection for example) during the merchant connector account create step, then Stripe's certificates will be passed implicitly (for now). If any other connector requires certificates to be passed, that has to be passed explicitly for now. */ let mut newman_command = Command::new("newman"); newman_command.args(["run", &collection_path]); newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]); newman_command.args(["--env-var", &format!("baseUrl={base_url}")]); let custom_header_exist = check_for_custom_headers(args.custom_headers, &collection_dir_path); // validation of connector is needed here as a work around to the limitation of the fork of newman that Hyperswitch uses let (connector_name, modified_collection_file_paths) = check_connector_for_dynamic_amount(&connector_name); if let Some(auth_type) = inner_map.get(connector_name) { match auth_type { ConnectorAuthType::HeaderKey { api_key } => { newman_command.args([ "--env-var", &format!("connector_api_key={}", api_key.peek()), ]); } ConnectorAuthType::BodyKey { api_key, key1 } => { newman_command.args([ "--env-var", &format!("connector_api_key={}", api_key.peek()), "--env-var", &format!("connector_key1={}", key1.peek()), ]); } ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => { newman_command.args([ "--env-var", &format!("connector_api_key={}", api_key.peek()), "--env-var", &format!("connector_key1={}", key1.peek()), "--env-var", &format!("connector_api_secret={}", api_secret.peek()), ]); } ConnectorAuthType::MultiAuthKey { api_key, key1, key2, api_secret, } => { newman_command.args([ "--env-var", &format!("connector_api_key={}", api_key.peek()), "--env-var", &format!("connector_key1={}", key1.peek()), "--env-var", &format!("connector_key2={}", key2.peek()), "--env-var", &format!("connector_api_secret={}", api_secret.peek()), ]); } // Handle other ConnectorAuthType variants _ => { eprintln!("Invalid authentication type."); } } } else { eprintln!("Connector not found."); } // Add additional environment variables if present if let Ok(gateway_merchant_id) = env::var("GATEWAY_MERCHANT_ID") { newman_command.args([ "--env-var", &format!("gateway_merchant_id={gateway_merchant_id}"), ]); } if let Ok(gpay_certificate) = env::var("GPAY_CERTIFICATE") { newman_command.args(["--env-var", &format!("certificate={gpay_certificate}")]); } if let Ok(gpay_certificate_keys) = env::var("GPAY_CERTIFICATE_KEYS") { newman_command.args([ "--env-var", &format!("certificate_keys={gpay_certificate_keys}"), ]); } if let Ok(merchant_api_key) = env::var("MERCHANT_API_KEY") { newman_command.args(["--env-var", &format!("merchant_api_key={merchant_api_key}")]); } newman_command.args([ "--delay-request", format!("{}", &args.delay_request).as_str(), ]); newman_command.arg("--color").arg("on"); // Add flags for running specific folders if let Some(folders) = &args.folders { let folder_names: Vec<String> = folders.split(',').map(|s| s.trim().to_string()).collect(); for folder_name in folder_names { if !folder_name.contains("QuickStart") { // This is a quick fix, "QuickStart" is intentional to have merchant account and API keys set up // This will be replaced by a more robust and efficient account creation or reuse existing old account newman_command.args(["--folder", "QuickStart"]); } newman_command.args(["--folder", &folder_name]); } } if args.verbose { newman_command.arg("--verbose"); } Ok(ReturnArgs { newman_command, modified_file_paths: vec![modified_collection_file_paths, custom_header_exist], collection_path, }) } pub fn check_for_custom_headers(headers: Option<Vec<String>>, path: &str) -> Option<String> { if let Some(headers) = &headers { for header in headers { if let Some((key, value)) = header.split_once(':') { let content_to_insert = format!(r#"pm.request.headers.add({{key: "{key}", value: "{value}"}});"#); if let Err(err) = insert_content(path, &content_to_insert) { eprintln!("An error occurred while inserting the custom header: {err}"); } } else { eprintln!("Invalid header format: {header}"); } } return Some(format!("{path}/event.prerequest.js")); } None } // If the connector name exists in dynamic_amount_connectors, // the corresponding collection is modified at runtime to remove double quotes pub fn check_connector_for_dynamic_amount(connector_name: &str) -> (&str, Option<String>) { let collection_dir_path = get_dir_path(connector_name); let dynamic_amount_connectors = ["nmi", "powertranz"]; if dynamic_amount_connectors.contains(&connector_name) { return remove_quotes_for_integer_values(connector_name).unwrap_or((connector_name, None)); } /* If connector name does not exist in dynamic_amount_connectors but we want to run it with custom headers, since we're running from collections directly, we'll have to export the collection again and it is much simpler. We could directly inject the custom-headers using regex, but it is not encouraged as it is hard to determine the place of edit. */ export_collection(connector_name, collection_dir_path); (connector_name, None) } /* Existing issue with the fork of newman is that, it requires you to pass variables like `{{value}}` within double quotes without which it fails to execute. For integer values like `amount`, this is a bummer as it flags the value stating it is of type string and not integer. Refactoring is done in 2 steps: - Export the collection to json (although the json will be up-to-date, we export it again for safety) - Use regex to replace the values which removes double quotes from integer values Ex: \"{{amount}}\" -> {{amount}} */ pub fn remove_quotes_for_integer_values( connector_name: &str, ) -> Result<(&str, Option<String>), io::Error> { let collection_path = get_collection_path(connector_name); let collection_dir_path = get_dir_path(connector_name); let values_to_replace = [ "amount", "another_random_number", "capture_amount", "random_number", "refund_amount", ]; export_collection(connector_name, collection_dir_path); let mut contents = fs::read_to_string(&collection_path)?; for value_to_replace in values_to_replace { if let Ok(re) = Regex::new(&format!( r#"\\"(?P<field>\{{\{{{value_to_replace}\}}\}})\\""#, )) { contents = re.replace_all(&contents, "$field").to_string(); } else { eprintln!("Regex validation failed."); } let mut file = OpenOptions::new() .write(true) .truncate(true) .open(&collection_path)?; file.write_all(contents.as_bytes())?; } Ok((connector_name, Some(collection_path))) } pub fn export_collection(connector_name: &str, collection_dir_path: String) { let collection_path = get_collection_path(connector_name); let mut newman_command = Command::new("newman"); newman_command.args([ "dir-import".to_owned(), collection_dir_path, "-o".to_owned(), collection_path.clone(), ]); match newman_command.spawn().and_then(|mut child| child.wait()) { Ok(exit_status) => { if exit_status.success() { println!("Conversion of collection from directory structure to json successful!"); } else { eprintln!("Conversion of collection from directory structure to json failed!"); exit(exit_status.code().unwrap_or(1)); } } Err(err) => { eprintln!("Failed to execute dir-import: {err:?}"); exit(1); } } }
crates/test_utils/src/newman_runner.rs
test_utils::src::newman_runner
3,337
true
// File: crates/test_utils/src/main.rs // Module: test_utils::src::main #![allow(clippy::print_stdout, clippy::print_stderr)] use std::process::{exit, Command}; use anyhow::Result; use test_utils::newman_runner; fn main() -> Result<()> { let mut runner = newman_runner::generate_runner()?; // Execute the newman command let output = runner.newman_command.spawn(); let mut child = match output { Ok(child) => child, Err(err) => { eprintln!("Failed to execute command: {err}"); exit(1); } }; let status = child.wait(); // Filter out None values leaving behind Some(Path) let paths: Vec<String> = runner.modified_file_paths.into_iter().flatten().collect(); if !paths.is_empty() { let git_status = Command::new("git").arg("restore").args(&paths).output(); match git_status { Ok(output) if !output.status.success() => { let stderr_str = String::from_utf8_lossy(&output.stderr); eprintln!("Git command failed with error: {stderr_str}"); } Ok(_) => { println!("Git restore successful!"); } Err(e) => { eprintln!("Error running Git: {e}"); } } } let exit_code = match status { Ok(exit_status) => { if exit_status.success() { println!("Command executed successfully!"); exit_status.code().unwrap_or(0) } else { eprintln!("Command failed with exit code: {:?}", exit_status.code()); exit_status.code().unwrap_or(1) } } Err(err) => { eprintln!("Failed to wait for command execution: {err}"); exit(1); } }; exit(exit_code); }
crates/test_utils/src/main.rs
test_utils::src::main
395
true
// File: crates/euclid_wasm/src/types.rs // Module: euclid_wasm::src::types use euclid::frontend::dir::DirKeyKind; #[cfg(feature = "payouts")] use euclid::frontend::dir::PayoutDirKeyKind; use serde::Serialize; #[derive(Serialize, Clone)] pub struct Details<'a> { pub description: Option<&'a str>, pub kind: DirKeyKind, } #[cfg(feature = "payouts")] #[derive(Serialize, Clone)] pub struct PayoutDetails<'a> { pub description: Option<&'a str>, pub kind: PayoutDirKeyKind, }
crates/euclid_wasm/src/types.rs
euclid_wasm::src::types
144
true
// File: crates/euclid_wasm/src/lib.rs // Module: euclid_wasm::src::lib #![allow(non_upper_case_globals)] mod types; mod utils; use std::{ collections::{HashMap, HashSet}, str::FromStr, sync::OnceLock, }; use api_models::{ enums as api_model_enums, routing::ConnectorSelection, surcharge_decision_configs::SurchargeDecisionConfigs, }; use common_enums::RoutableConnectors; use common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule; use connector_configs::{ common_config::{ConnectorApiIntegrationPayload, DashboardRequestPayload}, connector, }; use currency_conversion::{ conversion::convert as convert_currency, types as currency_conversion_types, }; use euclid::{ backend::{inputs, interpreter::InterpreterBackend, EuclidBackend}, dssa::{self, analyzer, graph::CgraphExt, state_machine}, frontend::{ ast, dir::{self, enums as dir_enums, EuclidDirFilter}, }, }; use strum::{EnumMessage, EnumProperty, VariantNames}; use wasm_bindgen::prelude::*; use crate::utils::JsResultExt; type JsResult = Result<JsValue, JsValue>; use api_models::payment_methods::CountryCodeWithName; #[cfg(feature = "payouts")] use common_enums::PayoutStatus; use common_enums::{ CountryAlpha2, DisputeStatus, EventClass, EventType, IntentStatus, MandateStatus, MerchantCategoryCode, MerchantCategoryCodeWithName, RefundStatus, }; use strum::IntoEnumIterator; struct SeedData { cgraph: hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>, connectors: Vec<ast::ConnectorChoice>, } static SEED_DATA: OnceLock<SeedData> = OnceLock::new(); static SEED_FOREX: OnceLock<currency_conversion_types::ExchangeRates> = OnceLock::new(); /// This function can be used by the frontend to educate wasm about the forex rates data. /// The input argument is a struct fields base_currency and conversion where later is all the conversions associated with the base_currency /// to all different currencies present. #[wasm_bindgen(js_name = setForexData)] pub fn seed_forex(forex: JsValue) -> JsResult { let forex: currency_conversion_types::ExchangeRates = serde_wasm_bindgen::from_value(forex)?; SEED_FOREX .set(forex) .map_err(|_| "Forex has already been seeded".to_string()) .err_to_js()?; Ok(JsValue::NULL) } /// This function can be used to perform currency_conversion on the input amount, from_currency, /// to_currency which are all expected to be one of currencies we already have in our Currency /// enum. #[wasm_bindgen(js_name = convertCurrency)] pub fn convert_forex_value(amount: i64, from_currency: JsValue, to_currency: JsValue) -> JsResult { let forex_data = SEED_FOREX .get() .ok_or("Forex Data not seeded") .err_to_js()?; let from_currency: common_enums::Currency = serde_wasm_bindgen::from_value(from_currency)?; let to_currency: common_enums::Currency = serde_wasm_bindgen::from_value(to_currency)?; let converted_amount = convert_currency(forex_data, from_currency, to_currency, amount) .map_err(|_| "conversion not possible for provided values") .err_to_js()?; Ok(serde_wasm_bindgen::to_value(&converted_amount)?) } /// This function can be used by the frontend to get all the two letter country codes /// along with their country names. #[wasm_bindgen(js_name=getTwoLetterCountryCode)] pub fn get_two_letter_country_code() -> JsResult { let country_code_with_name = CountryAlpha2::iter() .map(|country_code| CountryCodeWithName { code: country_code, name: common_enums::Country::from_alpha2(country_code), }) .collect::<Vec<_>>(); Ok(serde_wasm_bindgen::to_value(&country_code_with_name)?) } /// This function can be used by the frontend to get all the merchant category codes /// along with their names. #[wasm_bindgen(js_name=getMerchantCategoryCodeWithName)] pub fn get_merchant_category_code_with_name() -> JsResult { let merchant_category_codes_with_name = MerchantCategoryCode::iter() .map(|mcc_value| MerchantCategoryCodeWithName { code: mcc_value, name: mcc_value.to_merchant_category_name(), }) .collect::<Vec<_>>(); Ok(serde_wasm_bindgen::to_value( &merchant_category_codes_with_name, )?) } /// This function can be used by the frontend to provide the WASM with information about /// all the merchant's connector accounts. The input argument is a vector of all the merchant's /// connector accounts from the API. #[cfg(feature = "v1")] #[wasm_bindgen(js_name = seedKnowledgeGraph)] pub fn seed_knowledge_graph(mcas: JsValue) -> JsResult { let mcas: Vec<api_models::admin::MerchantConnectorResponse> = serde_wasm_bindgen::from_value(mcas)?; let connectors: Vec<ast::ConnectorChoice> = mcas .iter() .map(|mca| { Ok::<_, strum::ParseError>(ast::ConnectorChoice { connector: RoutableConnectors::from_str(&mca.connector_name)?, }) }) .collect::<Result<_, _>>() .map_err(|_| "invalid connector name received") .err_to_js()?; let pm_filter = kgraph_utils::types::PaymentMethodFilters(HashMap::new()); let config = kgraph_utils::types::CountryCurrencyFilter { connector_configs: HashMap::new(), default_configs: Some(pm_filter), }; let mca_graph = kgraph_utils::mca::make_mca_graph(mcas, &config).err_to_js()?; let analysis_graph = hyperswitch_constraint_graph::ConstraintGraph::combine( &mca_graph, &dssa::truth::ANALYSIS_GRAPH, ) .err_to_js()?; SEED_DATA .set(SeedData { cgraph: analysis_graph, connectors, }) .map_err(|_| "Knowledge Graph has been already seeded".to_string()) .err_to_js()?; Ok(JsValue::NULL) } /// This function allows the frontend to get all the merchant's configured /// connectors that are valid for a rule based on the conditions specified in /// the rule #[wasm_bindgen(js_name = getValidConnectorsForRule)] pub fn get_valid_connectors_for_rule(rule: JsValue) -> JsResult { let seed_data = SEED_DATA.get().ok_or("Data not seeded").err_to_js()?; let rule: ast::Rule<ConnectorSelection> = serde_wasm_bindgen::from_value(rule)?; let dir_rule = ast::lowering::lower_rule(rule).err_to_js()?; let mut valid_connectors: Vec<(ast::ConnectorChoice, dir::DirValue)> = seed_data .connectors .iter() .cloned() .map(|choice| (choice.clone(), dir::DirValue::Connector(Box::new(choice)))) .collect(); let mut invalid_connectors: HashSet<ast::ConnectorChoice> = HashSet::new(); let mut ctx_manager = state_machine::RuleContextManager::new(&dir_rule, &[]); let dummy_meta = HashMap::new(); // For every conjunctive context in the Rule, verify validity of all still-valid connectors // using the knowledge graph while let Some(ctx) = ctx_manager.advance_mut().err_to_js()? { // Standalone conjunctive context analysis to ensure the context itself is valid before // checking it against merchant's connectors seed_data .cgraph .perform_context_analysis( ctx, &mut hyperswitch_constraint_graph::Memoization::new(), None, ) .err_to_js()?; // Update conjunctive context and run analysis on all of merchant's connectors. for (conn, choice) in &valid_connectors { if invalid_connectors.contains(conn) { continue; } let ctx_val = dssa::types::ContextValue::assertion(choice, &dummy_meta); ctx.push(ctx_val); let analysis_result = seed_data.cgraph.perform_context_analysis( ctx, &mut hyperswitch_constraint_graph::Memoization::new(), None, ); if analysis_result.is_err() { invalid_connectors.insert(conn.clone()); } ctx.pop(); } } valid_connectors.retain(|(k, _)| !invalid_connectors.contains(k)); let valid_connectors: Vec<ast::ConnectorChoice> = valid_connectors.into_iter().map(|c| c.0).collect(); Ok(serde_wasm_bindgen::to_value(&valid_connectors)?) } #[wasm_bindgen(js_name = analyzeProgram)] pub fn analyze_program(js_program: JsValue) -> JsResult { let program: ast::Program<ConnectorSelection> = serde_wasm_bindgen::from_value(js_program)?; analyzer::analyze(program, SEED_DATA.get().map(|sd| &sd.cgraph)).err_to_js()?; Ok(JsValue::NULL) } #[wasm_bindgen(js_name = runProgram)] pub fn run_program(program: JsValue, input: JsValue) -> JsResult { let program: ast::Program<ConnectorSelection> = serde_wasm_bindgen::from_value(program)?; let input: inputs::BackendInput = serde_wasm_bindgen::from_value(input)?; let backend = InterpreterBackend::with_program(program).err_to_js()?; let res: euclid::backend::BackendOutput<ConnectorSelection> = backend.execute(input).err_to_js()?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getAllConnectors)] pub fn get_all_connectors() -> JsResult { Ok(serde_wasm_bindgen::to_value(RoutableConnectors::VARIANTS)?) } #[wasm_bindgen(js_name = getAllKeys)] pub fn get_all_keys() -> JsResult { let excluded_keys = [ "Connector", // 3DS Decision Rule Keys should not be included in the payument routing keys "issuer_name", "issuer_country", "customer_device_platform", "customer_device_type", "customer_device_display_size", "acquirer_country", "acquirer_fraud_rate", ]; let keys: Vec<&'static str> = dir::DirKeyKind::VARIANTS .iter() .copied() .filter(|s| !excluded_keys.contains(s)) .collect(); Ok(serde_wasm_bindgen::to_value(&keys)?) } #[wasm_bindgen(js_name = getKeyType)] pub fn get_key_type(key: &str) -> Result<String, String> { let key = dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let key_str = key.get_type().to_string(); Ok(key_str) } #[wasm_bindgen(js_name = getThreeDsKeys)] pub fn get_three_ds_keys() -> JsResult { let keys = <common_types::payments::ConditionalConfigs as EuclidDirFilter>::ALLOWED; Ok(serde_wasm_bindgen::to_value(keys)?) } #[wasm_bindgen(js_name= getSurchargeKeys)] pub fn get_surcharge_keys() -> JsResult { let keys = <SurchargeDecisionConfigs as EuclidDirFilter>::ALLOWED; Ok(serde_wasm_bindgen::to_value(keys)?) } #[wasm_bindgen(js_name= getThreeDsDecisionRuleKeys)] pub fn get_three_ds_decision_rule_keys() -> JsResult { let keys = <ThreeDSDecisionRule as EuclidDirFilter>::ALLOWED; Ok(serde_wasm_bindgen::to_value(keys)?) } #[wasm_bindgen(js_name=parseToString)] pub fn parser(val: String) -> String { ron_parser::my_parse(val) } #[wasm_bindgen(js_name = getVariantValues)] pub fn get_variant_values(key: &str) -> Result<JsValue, JsValue> { let key = dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let variants: &[&str] = match key { dir::DirKeyKind::PaymentMethod => dir_enums::PaymentMethod::VARIANTS, dir::DirKeyKind::CardType => dir_enums::CardType::VARIANTS, dir::DirKeyKind::CardNetwork => dir_enums::CardNetwork::VARIANTS, dir::DirKeyKind::PayLaterType => dir_enums::PayLaterType::VARIANTS, dir::DirKeyKind::WalletType => dir_enums::WalletType::VARIANTS, dir::DirKeyKind::BankRedirectType => dir_enums::BankRedirectType::VARIANTS, dir::DirKeyKind::CryptoType => dir_enums::CryptoType::VARIANTS, dir::DirKeyKind::RewardType => dir_enums::RewardType::VARIANTS, dir::DirKeyKind::AuthenticationType => dir_enums::AuthenticationType::VARIANTS, dir::DirKeyKind::CaptureMethod => dir_enums::CaptureMethod::VARIANTS, dir::DirKeyKind::PaymentCurrency => dir_enums::PaymentCurrency::VARIANTS, dir::DirKeyKind::BusinessCountry => dir_enums::Country::VARIANTS, dir::DirKeyKind::BillingCountry => dir_enums::Country::VARIANTS, dir::DirKeyKind::BankTransferType => dir_enums::BankTransferType::VARIANTS, dir::DirKeyKind::UpiType => dir_enums::UpiType::VARIANTS, dir::DirKeyKind::SetupFutureUsage => dir_enums::SetupFutureUsage::VARIANTS, dir::DirKeyKind::PaymentType => dir_enums::PaymentType::VARIANTS, dir::DirKeyKind::MandateType => dir_enums::MandateType::VARIANTS, dir::DirKeyKind::MandateAcceptanceType => dir_enums::MandateAcceptanceType::VARIANTS, dir::DirKeyKind::CardRedirectType => dir_enums::CardRedirectType::VARIANTS, dir::DirKeyKind::GiftCardType => dir_enums::GiftCardType::VARIANTS, dir::DirKeyKind::VoucherType => dir_enums::VoucherType::VARIANTS, dir::DirKeyKind::BankDebitType => dir_enums::BankDebitType::VARIANTS, dir::DirKeyKind::RealTimePaymentType => dir_enums::RealTimePaymentType::VARIANTS, dir::DirKeyKind::OpenBankingType => dir_enums::OpenBankingType::VARIANTS, dir::DirKeyKind::MobilePaymentType => dir_enums::MobilePaymentType::VARIANTS, dir::DirKeyKind::IssuerCountry => dir_enums::Country::VARIANTS, dir::DirKeyKind::AcquirerCountry => dir_enums::Country::VARIANTS, dir::DirKeyKind::CustomerDeviceType => dir_enums::CustomerDeviceType::VARIANTS, dir::DirKeyKind::CustomerDevicePlatform => dir_enums::CustomerDevicePlatform::VARIANTS, dir::DirKeyKind::CustomerDeviceDisplaySize => { dir_enums::CustomerDeviceDisplaySize::VARIANTS } dir::DirKeyKind::PaymentAmount | dir::DirKeyKind::Connector | dir::DirKeyKind::CardBin | dir::DirKeyKind::BusinessLabel | dir::DirKeyKind::MetaData | dir::DirKeyKind::IssuerName | dir::DirKeyKind::AcquirerFraudRate => Err("Key does not have variants".to_string())?, }; Ok(serde_wasm_bindgen::to_value(variants)?) } #[wasm_bindgen(js_name = addTwo)] pub fn add_two(n1: i64, n2: i64) -> i64 { n1 + n2 } #[wasm_bindgen(js_name = getDescriptionCategory)] pub fn get_description_category() -> JsResult { let keys = dir::DirKeyKind::VARIANTS .iter() .copied() .filter(|s| s != &"Connector") .collect::<Vec<&'static str>>(); let mut category: HashMap<Option<&str>, Vec<types::Details<'_>>> = HashMap::new(); for key in keys { let dir_key = dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let details = types::Details { description: dir_key.get_detailed_message(), kind: dir_key.clone(), }; category .entry(dir_key.get_str("Category")) .and_modify(|val| val.push(details.clone())) .or_insert(vec![details]); } Ok(serde_wasm_bindgen::to_value(&category)?) } #[wasm_bindgen(js_name = getConnectorConfig)] pub fn get_connector_config(key: &str) -> JsResult { let key = api_model_enums::Connector::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_connector_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[cfg(feature = "payouts")] #[wasm_bindgen(js_name = getPayoutConnectorConfig)] pub fn get_payout_connector_config(key: &str) -> JsResult { let key = api_model_enums::PayoutConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_payout_connector_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getAuthenticationConnectorConfig)] pub fn get_authentication_connector_config(key: &str) -> JsResult { let key = api_model_enums::AuthenticationConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_authentication_connector_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getTaxProcessorConfig)] pub fn get_tax_processor_config(key: &str) -> JsResult { let key = api_model_enums::TaxConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_tax_processor_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getPMAuthenticationProcessorConfig)] pub fn get_pm_authentication_processor_config(key: &str) -> JsResult { let key: api_model_enums::PmAuthConnectors = api_model_enums::PmAuthConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_pm_authentication_processor_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getRequestPayload)] pub fn get_request_payload(input: JsValue, response: JsValue) -> JsResult { let input: DashboardRequestPayload = serde_wasm_bindgen::from_value(input)?; let api_response: ConnectorApiIntegrationPayload = serde_wasm_bindgen::from_value(response)?; let result = DashboardRequestPayload::create_connector_request(input, api_response); Ok(serde_wasm_bindgen::to_value(&result)?) } #[wasm_bindgen(js_name = getResponsePayload)] pub fn get_response_payload(input: JsValue) -> JsResult { let input: ConnectorApiIntegrationPayload = serde_wasm_bindgen::from_value(input)?; let result = ConnectorApiIntegrationPayload::get_transformed_response_payload(input); Ok(serde_wasm_bindgen::to_value(&result)?) } #[cfg(feature = "payouts")] #[wasm_bindgen(js_name = getAllPayoutKeys)] pub fn get_all_payout_keys() -> JsResult { let keys: Vec<&'static str> = dir::PayoutDirKeyKind::VARIANTS.to_vec(); Ok(serde_wasm_bindgen::to_value(&keys)?) } #[cfg(feature = "payouts")] #[wasm_bindgen(js_name = getPayoutVariantValues)] pub fn get_payout_variant_values(key: &str) -> Result<JsValue, JsValue> { let key = dir::PayoutDirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let variants: &[&str] = match key { dir::PayoutDirKeyKind::BusinessCountry => dir_enums::BusinessCountry::VARIANTS, dir::PayoutDirKeyKind::BillingCountry => dir_enums::BillingCountry::VARIANTS, dir::PayoutDirKeyKind::PayoutCurrency => dir_enums::PaymentCurrency::VARIANTS, dir::PayoutDirKeyKind::PayoutType => dir_enums::PayoutType::VARIANTS, dir::PayoutDirKeyKind::WalletType => dir_enums::PayoutWalletType::VARIANTS, dir::PayoutDirKeyKind::BankTransferType => dir_enums::PayoutBankTransferType::VARIANTS, dir::PayoutDirKeyKind::PayoutAmount | dir::PayoutDirKeyKind::BusinessLabel => { Err("Key does not have variants".to_string())? } }; Ok(serde_wasm_bindgen::to_value(variants)?) } #[cfg(feature = "payouts")] #[wasm_bindgen(js_name = getPayoutDescriptionCategory)] pub fn get_payout_description_category() -> JsResult { let keys = dir::PayoutDirKeyKind::VARIANTS.to_vec(); let mut category: HashMap<Option<&str>, Vec<types::PayoutDetails<'_>>> = HashMap::new(); for key in keys { let dir_key = dir::PayoutDirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let details = types::PayoutDetails { description: dir_key.get_detailed_message(), kind: dir_key.clone(), }; category .entry(dir_key.get_str("Category")) .and_modify(|val| val.push(details.clone())) .or_insert(vec![details]); } Ok(serde_wasm_bindgen::to_value(&category)?) } #[wasm_bindgen(js_name = getValidWebhookStatus)] pub fn get_valid_webhook_status(key: &str) -> JsResult { let event_class = EventClass::from_str(key) .map_err(|_| "Invalid webhook event type received".to_string()) .err_to_js()?; match event_class { EventClass::Payments => { let statuses: Vec<IntentStatus> = IntentStatus::iter() .filter(|intent_status| Into::<Option<EventType>>::into(*intent_status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } EventClass::Refunds => { let statuses: Vec<RefundStatus> = RefundStatus::iter() .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } EventClass::Disputes => { let statuses: Vec<DisputeStatus> = DisputeStatus::iter().collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } EventClass::Mandates => { let statuses: Vec<MandateStatus> = MandateStatus::iter() .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } #[cfg(feature = "payouts")] EventClass::Payouts => { let statuses: Vec<PayoutStatus> = PayoutStatus::iter() .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } } }
crates/euclid_wasm/src/lib.rs
euclid_wasm::src::lib
5,367
true
// File: crates/euclid_wasm/src/utils.rs // Module: euclid_wasm::src::utils use wasm_bindgen::prelude::*; pub trait JsResultExt<T> { fn err_to_js(self) -> Result<T, JsValue>; } impl<T, E> JsResultExt<T> for Result<T, E> where E: serde::Serialize, { fn err_to_js(self) -> Result<T, JsValue> { match self { Ok(t) => Ok(t), Err(e) => Err(serde_wasm_bindgen::to_value(&e)?), } } }
crates/euclid_wasm/src/utils.rs
euclid_wasm::src::utils
133
true
// File: crates/common_types/src/consts.rs // Module: common_types::src::consts //! Constants that are used in the domain level. /// API version #[cfg(feature = "v1")] pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V1; /// API version #[cfg(feature = "v2")] pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V2; /// Maximum Dispute Polling Interval In Hours pub const MAX_DISPUTE_POLLING_INTERVAL_IN_HOURS: i32 = 24; ///Default Dispute Polling Interval In Hours pub const DEFAULT_DISPUTE_POLLING_INTERVAL_IN_HOURS: i32 = 24; /// Default payment intent statuses that trigger a webhook pub const DEFAULT_PAYMENT_WEBHOOK_TRIGGER_STATUSES: &[common_enums::IntentStatus] = &[ common_enums::IntentStatus::Succeeded, common_enums::IntentStatus::Failed, common_enums::IntentStatus::PartiallyCaptured, common_enums::IntentStatus::RequiresMerchantAction, ]; /// Default refund statuses that trigger a webhook pub const DEFAULT_REFUND_WEBHOOK_TRIGGER_STATUSES: &[common_enums::RefundStatus] = &[ common_enums::RefundStatus::Success, common_enums::RefundStatus::Failure, common_enums::RefundStatus::TransactionFailure, ]; /// Default payout statuses that trigger a webhook pub const DEFAULT_PAYOUT_WEBHOOK_TRIGGER_STATUSES: &[common_enums::PayoutStatus] = &[ common_enums::PayoutStatus::Success, common_enums::PayoutStatus::Failed, common_enums::PayoutStatus::Initiated, common_enums::PayoutStatus::Pending, ];
crates/common_types/src/consts.rs
common_types::src::consts
382
true
// File: crates/common_types/src/callback_mapper.rs // Module: common_types::src::callback_mapper use common_utils::id_type; use diesel::{AsExpression, FromSqlRow}; #[derive( Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, AsExpression, FromSqlRow, )] #[diesel(sql_type = diesel::sql_types::Jsonb)] /// Represents the data associated with a callback mapper. pub enum CallbackMapperData { /// data variant used while processing the network token webhook NetworkTokenWebhook { /// Merchant id associated with the network token requestor reference id merchant_id: id_type::MerchantId, /// Payment Method id associated with the network token requestor reference id payment_method_id: String, /// Customer id associated with the network token requestor reference id customer_id: id_type::CustomerId, }, } impl CallbackMapperData { /// Retrieves the details of the network token webhook type from callback mapper data. pub fn get_network_token_webhook_details( &self, ) -> (id_type::MerchantId, String, id_type::CustomerId) { match self { Self::NetworkTokenWebhook { merchant_id, payment_method_id, customer_id, } => ( merchant_id.clone(), payment_method_id.clone(), customer_id.clone(), ), } } } common_utils::impl_to_sql_from_sql_json!(CallbackMapperData);
crates/common_types/src/callback_mapper.rs
common_types::src::callback_mapper
306
true