text
stringlengths
65
57.3k
file_path
stringlengths
22
92
module
stringclasses
38 values
type
stringclasses
7 values
struct_name
stringlengths
3
60
impl_count
int64
0
60
traits
listlengths
0
59
tokens
int64
16
8.19k
function_name
stringlengths
3
85
type_name
stringlengths
1
67
trait_name
stringclasses
573 values
method_count
int64
0
31
public_method_count
int64
0
19
submodule_count
int64
0
56
export_count
int64
0
9
// Implementation: impl UnifiedAuthenticationService for for ClickToPay // File: crates/router/src/core/unified_authentication_service.rs // Module: router // Methods: 4 total (0 public) impl UnifiedAuthenticationService for for ClickToPay
crates/router/src/core/unified_authentication_service.rs
router
impl_block
null
null
null
50
null
ClickToPay
UnifiedAuthenticationService for
4
0
null
null
// Function: signal_handler // File: crates/common_utils/src/signals.rs // Module: common_utils pub fn signal_handler(_sig: DummySignal, _sender: mpsc::Sender<()
crates/common_utils/src/signals.rs
common_utils
function_signature
null
null
null
42
signal_handler
null
null
null
null
null
null
// Function: payments_get_intent // File: crates/openapi/src/routes/payments.rs // Module: openapi pub fn payments_get_intent()
crates/openapi/src/routes/payments.rs
openapi
function_signature
null
null
null
31
payments_get_intent
null
null
null
null
null
null
// Function: store_key // File: crates/hyperswitch_domain_models/src/payment_method_data.rs // Module: hyperswitch_domain_models pub fn store_key(payment_method_id: &id_type::GlobalPaymentMethodId) -> Self
crates/hyperswitch_domain_models/src/payment_method_data.rs
hyperswitch_domain_models
function_signature
null
null
null
49
store_key
null
null
null
null
null
null
// File: crates/euclid/src/dssa/analyzer.rs // Module: euclid // Public functions: 3 //! Static Analysis for the Euclid Rule DSL //! //! Exposes certain functions that can be used to perform static analysis over programs //! in the Euclid Rule DSL. These include standard control flow analyses like testing //! conflicting assertions, to Domain Specific Analyses making use of the //! [`Knowledge Graph Framework`](crate::dssa::graph). use hyperswitch_constraint_graph::{ConstraintGraph, Memoization}; use rustc_hash::{FxHashMap, FxHashSet}; use crate::{ dssa::{ graph::CgraphExt, state_machine, truth, types::{self, EuclidAnalysable}, }, frontend::{ ast, dir::{self, EuclidDirFilter}, vir, }, types::{DataType, Metadata}, }; /// Analyses conflicting assertions on the same key in a conjunctive context. /// /// For example, /// ```notrust /// payment_method = card && ... && payment_method = bank_debit /// ```notrust /// This is a condition that will never evaluate to `true` given a single /// payment method and needs to be caught in analysis. pub fn analyze_conflicting_assertions( keywise_assertions: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>, assertion_metadata: &FxHashMap<&dir::DirValue, &Metadata>, ) -> Result<(), types::AnalysisError> { for (key, value_set) in keywise_assertions { if value_set.len() > 1 { let err_type = types::AnalysisErrorType::ConflictingAssertions { key: key.clone(), values: value_set .iter() .map(|val| types::ValueData { value: (*val).clone(), metadata: assertion_metadata .get(val) .map(|meta| (*meta).clone()) .unwrap_or_default(), }) .collect(), }; Err(types::AnalysisError { error_type: err_type, metadata: Default::default(), })?; } } Ok(()) } /// Analyses exhaustive negations on the same key in a conjunctive context. /// /// For example, /// ```notrust /// authentication_type /= three_ds && ... && authentication_type /= no_three_ds /// ```notrust /// This is a condition that will never evaluate to `true` given any authentication_type /// since all the possible values authentication_type can take have been negated. pub fn analyze_exhaustive_negations( keywise_negations: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>, keywise_negation_metadata: &FxHashMap<dir::DirKey, Vec<&Metadata>>, ) -> Result<(), types::AnalysisError> { for (key, negation_set) in keywise_negations { let mut value_set = if let Some(set) = key.kind.get_value_set() { set } else { continue; }; value_set.retain(|val| !negation_set.contains(val)); if value_set.is_empty() { let error_type = types::AnalysisErrorType::ExhaustiveNegation { key: key.clone(), metadata: keywise_negation_metadata .get(key) .cloned() .unwrap_or_default() .iter() .copied() .cloned() .collect(), }; Err(types::AnalysisError { error_type, metadata: Default::default(), })?; } } Ok(()) } fn analyze_negated_assertions( keywise_assertions: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>, assertion_metadata: &FxHashMap<&dir::DirValue, &Metadata>, keywise_negations: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>, negation_metadata: &FxHashMap<&dir::DirValue, &Metadata>, ) -> Result<(), types::AnalysisError> { for (key, negation_set) in keywise_negations { let assertion_set = if let Some(set) = keywise_assertions.get(key) { set } else { continue; }; let intersection = negation_set & assertion_set; intersection.iter().next().map_or(Ok(()), |val| { let error_type = types::AnalysisErrorType::NegatedAssertion { value: (*val).clone(), assertion_metadata: assertion_metadata .get(*val) .copied() .cloned() .unwrap_or_default(), negation_metadata: negation_metadata .get(*val) .copied() .cloned() .unwrap_or_default(), }; Err(types::AnalysisError { error_type, metadata: Default::default(), }) })?; } Ok(()) } fn perform_condition_analyses( context: &types::ConjunctiveContext<'_>, ) -> Result<(), types::AnalysisError> { let mut assertion_metadata: FxHashMap<&dir::DirValue, &Metadata> = FxHashMap::default(); let mut keywise_assertions: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> = FxHashMap::default(); let mut negation_metadata: FxHashMap<&dir::DirValue, &Metadata> = FxHashMap::default(); let mut keywise_negation_metadata: FxHashMap<dir::DirKey, Vec<&Metadata>> = FxHashMap::default(); let mut keywise_negations: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> = FxHashMap::default(); for ctx_val in context { let key = if let Some(k) = ctx_val.value.get_key() { k } else { continue; }; if let dir::DirKeyKind::Connector = key.kind { continue; } if !matches!(key.kind.get_type(), DataType::EnumVariant) { continue; } match ctx_val.value { types::CtxValueKind::Assertion(val) => { keywise_assertions .entry(key.clone()) .or_default() .insert(val); assertion_metadata.insert(val, ctx_val.metadata); } types::CtxValueKind::Negation(vals) => { let negation_set = keywise_negations.entry(key.clone()).or_default(); for val in vals { negation_set.insert(val); negation_metadata.insert(val, ctx_val.metadata); } keywise_negation_metadata .entry(key.clone()) .or_default() .push(ctx_val.metadata); } } } analyze_conflicting_assertions(&keywise_assertions, &assertion_metadata)?; analyze_exhaustive_negations(&keywise_negations, &keywise_negation_metadata)?; analyze_negated_assertions( &keywise_assertions, &assertion_metadata, &keywise_negations, &negation_metadata, )?; Ok(()) } fn perform_context_analyses( context: &types::ConjunctiveContext<'_>, knowledge_graph: &ConstraintGraph<dir::DirValue>, ) -> Result<(), types::AnalysisError> { perform_condition_analyses(context)?; let mut memo = Memoization::new(); knowledge_graph .perform_context_analysis(context, &mut memo, None) .map_err(|err| types::AnalysisError { error_type: types::AnalysisErrorType::GraphAnalysis(err, memo), metadata: Default::default(), })?; Ok(()) } pub fn analyze<O: EuclidAnalysable + EuclidDirFilter>( program: ast::Program<O>, knowledge_graph: Option<&ConstraintGraph<dir::DirValue>>, ) -> Result<vir::ValuedProgram<O>, types::AnalysisError> { let dir_program = ast::lowering::lower_program(program)?; let selection_data = state_machine::make_connector_selection_data(&dir_program); let mut ctx_manager = state_machine::AnalysisContextManager::new(&dir_program, &selection_data); while let Some(ctx) = ctx_manager.advance().map_err(|err| types::AnalysisError { metadata: Default::default(), error_type: types::AnalysisErrorType::StateMachine(err), })? { perform_context_analyses(ctx, knowledge_graph.unwrap_or(&truth::ANALYSIS_GRAPH))?; } dir::lowering::lower_program(dir_program) } #[cfg(all(test, feature = "ast_parser"))] mod tests { #![allow(clippy::panic, clippy::expect_used)] use std::{ops::Deref, sync::Weak}; use euclid_macros::knowledge; use hyperswitch_constraint_graph as cgraph; use super::*; use crate::{ dirval, dssa::graph::{self, euclid_graph_prelude}, types::DummyOutput, }; #[test] fn test_conflicting_assertion_detection() { let program_str = r#" default: ["stripe", "adyen"] stripe_first: ["stripe", "adyen"] { payment_method = wallet { amount > 500 & capture_method = automatic amount < 500 & payment_method = card } } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let analysis_result = analyze(program, None); if let Err(types::AnalysisError { error_type: types::AnalysisErrorType::ConflictingAssertions { key, values }, .. }) = analysis_result { assert!( matches!(key.kind, dir::DirKeyKind::PaymentMethod), "Key should be payment_method" ); let values: Vec<dir::DirValue> = values.into_iter().map(|v| v.value).collect(); assert_eq!(values.len(), 2, "There should be 2 conflicting conditions"); assert!( values.contains(&dirval!(PaymentMethod = Wallet)), "Condition should include payment_method = wallet" ); assert!( values.contains(&dirval!(PaymentMethod = Card)), "Condition should include payment_method = card" ); } else { panic!("Did not receive conflicting assertions error"); } } #[test] fn test_exhaustive_negation_detection() { let program_str = r#" default: ["stripe"] rule_1: ["adyen"] { payment_method /= wallet { capture_method = manual & payment_method /= card { authentication_type = three_ds & payment_method /= pay_later { amount > 1000 & payment_method /= bank_redirect { payment_method /= crypto & payment_method /= bank_debit & payment_method /= bank_transfer & payment_method /= upi & payment_method /= reward & payment_method /= voucher & payment_method /= gift_card & payment_method /= card_redirect & payment_method /= real_time_payment & payment_method /= open_banking & payment_method /= mobile_payment } } } } } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let analysis_result = analyze(program, None); if let Err(types::AnalysisError { error_type: types::AnalysisErrorType::ExhaustiveNegation { key, .. }, .. }) = analysis_result { assert!( matches!(key.kind, dir::DirKeyKind::PaymentMethod), "Expected key to be payment_method" ); } else { panic!("Expected exhaustive negation error"); } } #[test] fn test_negated_assertions_detection() { let program_str = r#" default: ["stripe"] rule_1: ["adyen"] { payment_method = wallet { amount > 500 { capture_method = automatic } amount < 501 { payment_method /= wallet } } } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let analysis_result = analyze(program, None); if let Err(types::AnalysisError { error_type: types::AnalysisErrorType::NegatedAssertion { value, .. }, .. }) = analysis_result { assert_eq!( value, dirval!(PaymentMethod = Wallet), "Expected to catch payment_method = wallet as conflict" ); } else { panic!("Expected negated assertion error"); } } #[test] fn test_negation_graph_analysis() { let graph = knowledge! { CaptureMethod(Automatic) ->> PaymentMethod(Card); }; let program_str = r#" default: ["stripe"] rule_1: ["adyen"] { amount > 500 { payment_method = pay_later } amount < 500 { payment_method /= wallet & payment_method /= pay_later } } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Graph"); let analysis_result = analyze(program, Some(&graph)); let error_type = match analysis_result { Err(types::AnalysisError { error_type, .. }) => error_type, _ => panic!("Error_type not found"), }; let a_err = match error_type { types::AnalysisErrorType::GraphAnalysis(trace, memo) => (trace, memo), _ => panic!("Graph Analysis not found"), }; let (trace, metadata) = match a_err.0 { graph::AnalysisError::NegationTrace { trace, metadata } => (trace, metadata), _ => panic!("Negation Trace not found"), }; let predecessor = match Weak::upgrade(&trace) .expect("Expected Arc not found") .deref() .clone() { cgraph::AnalysisTrace::Value { predecessors, .. } => { let _value = cgraph::NodeValue::Value(dir::DirValue::PaymentMethod( dir::enums::PaymentMethod::Card, )); let _relation = cgraph::Relation::Positive; predecessors } _ => panic!("Expected Negation Trace for payment method = card"), }; let pred = match predecessor { Some(cgraph::error::ValueTracePredecessor::Mandatory(predecessor)) => predecessor, _ => panic!("No predecessor found"), }; assert_eq!( metadata.len(), 2, "Expected two metadats for wallet and pay_later" ); assert!(matches!( *Weak::upgrade(&pred) .expect("Expected Arc not found") .deref(), cgraph::AnalysisTrace::Value { value: cgraph::NodeValue::Value(dir::DirValue::CaptureMethod( dir::enums::CaptureMethod::Automatic )), relation: cgraph::Relation::Positive, info: None, metadata: None, predecessors: None, } )); } }
crates/euclid/src/dssa/analyzer.rs
euclid
full_file
null
null
null
3,270
null
null
null
null
null
null
null
// Module Structure // File: crates/hyperswitch_connectors/src/connectors/mollie.rs // Module: hyperswitch_connectors // Public submodules: pub mod transformers;
crates/hyperswitch_connectors/src/connectors/mollie.rs
hyperswitch_connectors
module_structure
null
null
null
39
null
null
null
null
null
1
0
// Struct: AciRefundRequest // File: crates/hyperswitch_connectors/src/connectors/aci/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct AciRefundRequest
crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
hyperswitch_connectors
struct_definition
AciRefundRequest
0
[]
51
null
null
null
null
null
null
null
// File: crates/router/src/core/payment_methods/validator.rs // Module: router // Public functions: 2 use api_models::{admin, payment_methods::PaymentMethodCollectLinkRequest}; use common_utils::link_utils; use diesel_models::generic_link::PaymentMethodCollectLinkData; use error_stack::ResultExt; use masking::Secret; use crate::{ consts, core::{ errors::{self, RouterResult}, utils as core_utils, }, routes::{app::StorageInterface, SessionState}, types::domain, utils, }; #[cfg(feature = "v2")] pub async fn validate_request_and_initiate_payment_method_collect_link( _state: &SessionState, _merchant_context: &domain::MerchantContext, _req: &PaymentMethodCollectLinkRequest, ) -> RouterResult<PaymentMethodCollectLinkData> { todo!() } #[cfg(feature = "v1")] pub async fn validate_request_and_initiate_payment_method_collect_link( state: &SessionState, merchant_context: &domain::MerchantContext, req: &PaymentMethodCollectLinkRequest, ) -> RouterResult<PaymentMethodCollectLinkData> { // Validate customer_id let db: &dyn StorageInterface = &*state.store; let customer_id = req.customer_id.clone(); let merchant_id = merchant_context.get_merchant_account().get_id().clone(); #[cfg(feature = "v1")] match db .find_customer_by_customer_id_merchant_id( &state.into(), &customer_id, &merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await { Ok(_) => Ok(()), Err(err) => { if err.current_context().is_db_not_found() { Err(err).change_context(errors::ApiErrorResponse::InvalidRequestData { message: format!( "customer [{}] not found for merchant [{:?}]", customer_id.get_string_repr(), merchant_id ), }) } else { Err(err) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("database error while finding customer") } } }?; // Create payment method collect link ID let pm_collect_link_id = core_utils::get_or_generate_id( "pm_collect_link_id", &req.pm_collect_link_id, "pm_collect_link", )?; // Fetch all configs let default_config = &state.conf.generic_link.payment_method_collect; #[cfg(feature = "v1")] let merchant_config = merchant_context .get_merchant_account() .pm_collect_link_config .as_ref() .map(|config| { common_utils::ext_traits::ValueExt::parse_value::<admin::BusinessCollectLinkConfig>( config.clone(), "BusinessCollectLinkConfig", ) }) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "pm_collect_link_config in merchant_account", })?; #[cfg(feature = "v2")] let merchant_config = Option::<admin::BusinessCollectLinkConfig>::None; let merchant_ui_config = merchant_config.as_ref().map(|c| c.config.ui_config.clone()); let ui_config = req .ui_config .as_ref() .or(merchant_ui_config.as_ref()) .cloned(); // Form data to be injected in the link let (logo, merchant_name, theme) = match ui_config { Some(config) => (config.logo, config.merchant_name, config.theme), _ => (None, None, None), }; let pm_collect_link_config = link_utils::GenericLinkUiConfig { logo, merchant_name, theme, }; let client_secret = utils::generate_id(consts::ID_LENGTH, "pm_collect_link_secret"); let domain = merchant_config .clone() .and_then(|c| c.config.domain_name) .map(|domain| format!("https://{domain}")) .unwrap_or(state.base_url.clone()); let session_expiry = match req.session_expiry { Some(expiry) => expiry, None => default_config.expiry, }; let link = Secret::new(format!( "{domain}/payment_methods/collect/{}/{pm_collect_link_id}", merchant_id.get_string_repr() )); let enabled_payment_methods = match (&req.enabled_payment_methods, &merchant_config) { (Some(enabled_payment_methods), _) => enabled_payment_methods.clone(), (None, Some(config)) => config.enabled_payment_methods.clone(), _ => { let mut default_enabled_payout_methods: Vec<link_utils::EnabledPaymentMethod> = vec![]; for (payment_method, payment_method_types) in default_config.enabled_payment_methods.clone().into_iter() { let enabled_payment_method = link_utils::EnabledPaymentMethod { payment_method, payment_method_types: payment_method_types.into_iter().collect(), }; default_enabled_payout_methods.push(enabled_payment_method); } default_enabled_payout_methods } }; Ok(PaymentMethodCollectLinkData { pm_collect_link_id: pm_collect_link_id.clone(), customer_id, link, client_secret: Secret::new(client_secret), session_expiry, ui_config: pm_collect_link_config, enabled_payment_methods: Some(enabled_payment_methods), }) }
crates/router/src/core/payment_methods/validator.rs
router
full_file
null
null
null
1,152
null
null
null
null
null
null
null
// Struct: GetGlobalSearchRequest // File: crates/api_models/src/analytics/search.rs // Module: api_models // Implementations: 0 pub struct GetGlobalSearchRequest
crates/api_models/src/analytics/search.rs
api_models
struct_definition
GetGlobalSearchRequest
0
[]
39
null
null
null
null
null
null
null
// Struct: ZslRouterData // File: crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ZslRouterData<T>
crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs
hyperswitch_connectors
struct_definition
ZslRouterData
0
[]
51
null
null
null
null
null
null
null
// Struct: SepaAndBacsBillingDetails // File: crates/hyperswitch_domain_models/src/payment_method_data.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct SepaAndBacsBillingDetails
crates/hyperswitch_domain_models/src/payment_method_data.rs
hyperswitch_domain_models
struct_definition
SepaAndBacsBillingDetails
0
[]
51
null
null
null
null
null
null
null
// Struct: TrustpayRouterData // File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct TrustpayRouterData<T>
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
hyperswitch_connectors
struct_definition
TrustpayRouterData
0
[]
52
null
null
null
null
null
null
null
// Implementation: impl PaymentTokenData // File: crates/router/src/types/storage/payment_method.rs // Module: router // Methods: 6 total (6 public) impl PaymentTokenData
crates/router/src/types/storage/payment_method.rs
router
impl_block
null
null
null
39
null
PaymentTokenData
null
6
6
null
null
// Function: payouts_list // File: crates/router/src/routes/payouts.rs // Module: router pub fn payouts_list( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Query<payout_types::PayoutListConstraints>, ) -> HttpResponse
crates/router/src/routes/payouts.rs
router
function_signature
null
null
null
61
payouts_list
null
null
null
null
null
null
// Implementation: impl StoredCredentialMode // File: crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs // Module: hyperswitch_connectors // Methods: 1 total (1 public) impl StoredCredentialMode
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
hyperswitch_connectors
impl_block
null
null
null
52
null
StoredCredentialMode
null
1
1
null
null
// Implementation: impl HubspotProxyConfig // File: crates/external_services/src/crm.rs // Module: external_services // Methods: 1 total (0 public) impl HubspotProxyConfig
crates/external_services/src/crm.rs
external_services
impl_block
null
null
null
42
null
HubspotProxyConfig
null
1
0
null
null
// Implementation: impl AlwaysEnableOvercaptureBool // File: crates/common_types/src/primitive_wrappers.rs // Module: common_types // Methods: 1 total (1 public) impl AlwaysEnableOvercaptureBool
crates/common_types/src/primitive_wrappers.rs
common_types
impl_block
null
null
null
45
null
AlwaysEnableOvercaptureBool
null
1
1
null
null
// Implementation: impl MerchantAccountUpdateInternal // File: crates/diesel_models/src/merchant_account.rs // Module: diesel_models // Methods: 1 total (1 public) impl MerchantAccountUpdateInternal
crates/diesel_models/src/merchant_account.rs
diesel_models
impl_block
null
null
null
43
null
MerchantAccountUpdateInternal
null
1
1
null
null
// Function: new // File: crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs // Module: hyperswitch_connectors pub fn new(three_d_s_info: RedsysThreeDsInfo) -> Self
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
hyperswitch_connectors
function_signature
null
null
null
50
new
null
null
null
null
null
null
// Implementation: impl api::PayoutCreate for for Adyen // File: crates/hyperswitch_connectors/src/connectors/adyen.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PayoutCreate for for Adyen
crates/hyperswitch_connectors/src/connectors/adyen.rs
hyperswitch_connectors
impl_block
null
null
null
60
null
Adyen
api::PayoutCreate for
0
0
null
null
// Trait: GsmValidation // File: crates/router/src/core/payouts/retry.rs // Module: router pub trait GsmValidation
crates/router/src/core/payouts/retry.rs
router
trait_definition
null
null
null
31
null
null
GsmValidation
null
null
null
null
// Struct: DynamicData // File: crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct DynamicData
crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
hyperswitch_domain_models
struct_definition
DynamicData
0
[]
45
null
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/hyperswitch_vault/transformers.rs // Module: hyperswitch_connectors // Public structs: 7 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
full_file
null
null
null
955
null
null
null
null
null
null
null
// Struct: IatapayPaymentWebhookBody // File: crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct IatapayPaymentWebhookBody
crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs
hyperswitch_connectors
struct_definition
IatapayPaymentWebhookBody
0
[]
59
null
null
null
null
null
null
null
// Implementation: impl RoleName // File: crates/router/src/types/domain/user.rs // Module: router // Methods: 2 total (2 public) impl RoleName
crates/router/src/types/domain/user.rs
router
impl_block
null
null
null
36
null
RoleName
null
2
2
null
null
// Struct: PaysafeMeta // File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaysafeMeta
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
hyperswitch_connectors
struct_definition
PaysafeMeta
0
[]
48
null
null
null
null
null
null
null
// Struct: DlocalRefundsSyncRequest // File: crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct DlocalRefundsSyncRequest
crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
hyperswitch_connectors
struct_definition
DlocalRefundsSyncRequest
0
[]
53
null
null
null
null
null
null
null
// Implementation: impl ChargebeeInvoiceBody // File: crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs // Module: hyperswitch_connectors // Methods: 1 total (1 public) impl ChargebeeInvoiceBody
crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
hyperswitch_connectors
impl_block
null
null
null
53
null
ChargebeeInvoiceBody
null
1
1
null
null
// Function: routing_update_default_config_for_profile // File: crates/openapi/src/routes/routing.rs // Module: openapi pub fn routing_update_default_config_for_profile()
crates/openapi/src/routes/routing.rs
openapi
function_signature
null
null
null
37
routing_update_default_config_for_profile
null
null
null
null
null
null
// Function: generate_profile_authentication_report // File: crates/router/src/analytics.rs // Module: router pub fn generate_profile_authentication_report( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<ReportRequest>, ) -> impl Responder
crates/router/src/analytics.rs
router
function_signature
null
null
null
65
generate_profile_authentication_report
null
null
null
null
null
null
// Function: get_merchant_details_as_secret // File: crates/api_models/src/admin.rs // Module: api_models pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError>
crates/api_models/src/admin.rs
api_models
function_signature
null
null
null
58
get_merchant_details_as_secret
null
null
null
null
null
null
// Function: get_refund_id_as_string // File: crates/api_models/src/refunds.rs // Module: api_models pub fn get_refund_id_as_string(&self) -> String
crates/api_models/src/refunds.rs
api_models
function_signature
null
null
null
40
get_refund_id_as_string
null
null
null
null
null
null
headers .get(&key) .map(|source_str| { source_str .to_str() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( "Failed to convert header value to string for header key: {key}", )) }) .transpose() } pub fn get_id_type_by_key_from_headers<T: FromStr>( key: String, headers: &HeaderMap, ) -> RouterResult<Option<T>> { get_header_value_by_key(key.clone(), headers)? .map(|str_value| T::from_str(str_value)) .transpose() .map_err(|_err| { error_stack::report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: key, expected_format: "Valid Id String".to_string(), }) }) } pub fn get_jwt_from_authorization_header(headers: &HeaderMap) -> RouterResult<&str> { headers .get(headers::AUTHORIZATION) .get_required_value(headers::AUTHORIZATION)? .to_str() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert JWT token to string")? .strip_prefix("Bearer ") .ok_or(errors::ApiErrorResponse::InvalidJwtToken.into()) } pub fn get_cookie_from_header(headers: &HeaderMap) -> RouterResult<&str> { let cookie = headers .get(cookies::get_cookie_header()) .ok_or(report!(errors::ApiErrorResponse::CookieNotFound))?; cookie .to_str() .change_context(errors::ApiErrorResponse::InvalidCookie) } pub fn strip_jwt_token(token: &str) -> RouterResult<&str> { token .strip_prefix("Bearer ") .ok_or_else(|| errors::ApiErrorResponse::InvalidJwtToken.into()) } pub fn auth_type<'a, T, A>( default_auth: &'a dyn AuthenticateAndFetch<T, A>, jwt_auth_type: &'a dyn AuthenticateAndFetch<T, A>, headers: &HeaderMap, ) -> &'a dyn AuthenticateAndFetch<T, A> where { if is_jwt_auth(headers) { return jwt_auth_type; } default_auth } #[cfg(feature = "recon")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationDataWithUser, A> for JWTAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationDataWithUser, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let user_id = payload.user_id; let user = state .session_state() .global_store .find_user_by_id(&user_id) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch user for the user id")?; let auth = AuthenticationDataWithUser { merchant_account: merchant, key_store, profile_id: payload.profile_id.clone(), user, }; let auth_type = AuthenticationType::MerchantJwt { merchant_id: auth.merchant_account.get_id().clone(), user_id: Some(user_id), }; Ok((auth, auth_type)) } } async fn get_connected_merchant_account<A>( state: &A, connected_merchant_id: id_type::MerchantId, platform_org_id: id_type::OrganizationId, ) -> RouterResult<domain::MerchantAccount> where A: SessionStateInfo + Sync, { let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &connected_merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let connected_merchant_account = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &connected_merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation) .attach_printable("Failed to fetch merchant account for the merchant id")?; if platform_org_id != connected_merchant_account.organization_id { return Err(errors::ApiErrorResponse::InvalidPlatformOperation) .attach_printable("Access for merchant id Unauthorized"); } Ok(connected_merchant_account) } async fn get_platform_merchant_account<A>( state: &A, request_headers: &HeaderMap, merchant_account: domain::MerchantAccount, ) -> RouterResult<(domain::MerchantAccount, Option<domain::MerchantAccount>)> where A: SessionStateInfo + Sync, { let connected_merchant_id = get_and_validate_connected_merchant_id(request_headers, &merchant_account)?; match connected_merchant_id { Some(merchant_id) => { let connected_merchant_account = get_connected_merchant_account( state, merchant_id, merchant_account.organization_id.clone(), ) .await?; Ok((connected_merchant_account, Some(merchant_account))) } None => Ok((merchant_account, None)), } } fn get_and_validate_connected_merchant_id( request_headers: &HeaderMap, merchant_account: &domain::MerchantAccount, ) -> RouterResult<Option<id_type::MerchantId>> { HeaderMapStruct::new(request_headers) .get_id_type_from_header_if_present::<id_type::MerchantId>( headers::X_CONNECTED_MERCHANT_ID, )? .map(|merchant_id| { (merchant_account.is_platform_account()) .then_some(merchant_id) .ok_or(errors::ApiErrorResponse::InvalidPlatformOperation) }) .transpose() .attach_printable("Non platform_merchant_account using X_CONNECTED_MERCHANT_ID header") } fn throw_error_if_platform_merchant_authentication_required( request_headers: &HeaderMap, ) -> RouterResult<()> { HeaderMapStruct::new(request_headers) .get_id_type_from_header_if_present::<id_type::MerchantId>( headers::X_CONNECTED_MERCHANT_ID, )? .map_or(Ok(()), |_| { Err(errors::ApiErrorResponse::PlatformAccountAuthNotSupported.into()) }) } #[cfg(feature = "recon")] #[async_trait] impl<A> AuthenticateAndFetch<UserFromTokenWithRoleInfo, A> for JWTAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(UserFromTokenWithRoleInfo, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; let user = UserFromToken { user_id: payload.user_id.clone(), merchant_id: payload.merchant_id.clone(), org_id: payload.org_id, role_id: payload.role_id, profile_id: payload.profile_id, tenant_id: payload.tenant_id, }; Ok(( UserFromTokenWithRoleInfo { user, role_info }, AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "recon")] #[derive(serde::Serialize, serde::Deserialize)] pub struct ReconToken { pub user_id: String, pub merchant_id: id_type::MerchantId, pub role_id: String, pub exp: u64, pub org_id: id_type::OrganizationId, pub profile_id: id_type::ProfileId, pub tenant_id: Option<id_type::TenantId>, #[serde(skip_serializing_if = "Option::is_none")] pub acl: Option<String>, } #[cfg(all(feature = "olap", feature = "recon"))] impl ReconToken { pub async fn new_token( user_id: String, merchant_id: id_type::MerchantId, settings: &Settings, org_id: id_type::OrganizationId, profile_id: id_type::ProfileId, tenant_id: Option<id_type::TenantId>, role_info: authorization::roles::RoleInfo, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(exp_duration)?.as_secs(); let acl = role_info.get_recon_acl(); let optional_acl_str = serde_json::to_string(&acl) .inspect_err(|err| logger::error!("Failed to serialize acl to string: {}", err)) .change_context(errors::UserErrors::InternalServerError) .attach_printable("Failed to serialize acl to string. Using empty ACL") .ok(); let token_payload = Self { user_id, merchant_id, role_id: role_info.get_role_id().to_string(), exp, org_id, profile_id, tenant_id, acl: optional_acl_str, }; jwt::generate_jwt(&token_payload, settings).await } } #[derive(serde::Serialize, serde::Deserialize)] pub struct ExternalToken { pub user_id: String, pub merchant_id: id_type::MerchantId, pub exp: u64, pub external_service_type: ExternalServiceType, } impl ExternalToken { pub async fn new_token( user_id: String, merchant_id: id_type::MerchantId, settings: &Settings, external_service_type: ExternalServiceType, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(exp_duration)?.as_secs(); let token_payload = Self { user_id, merchant_id, exp, external_service_type, }; jwt::generate_jwt(&token_payload, settings).await } pub fn check_service_type( &self, required_service_type: &ExternalServiceType, ) -> RouterResult<()> { Ok(fp_utils::when( &self.external_service_type != required_service_type, || { Err(errors::ApiErrorResponse::AccessForbidden { resource: required_service_type.to_string(), }) }, )?) } }
crates/router/src/services/authentication.rs#chunk4
router
chunk
null
null
null
2,639
null
null
null
null
null
null
null
// Struct: Card // File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct Card
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
hyperswitch_connectors
struct_definition
Card
0
[]
46
null
null
null
null
null
null
null
// Function: get_role_name // File: crates/router/src/services/authorization/roles.rs // Module: router pub fn get_role_name(&self) -> &str
crates/router/src/services/authorization/roles.rs
router
function_signature
null
null
null
36
get_role_name
null
null
null
null
null
null
// Struct: PaymentService // File: crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentService
crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs
hyperswitch_connectors
struct_definition
PaymentService
0
[]
46
null
null
null
null
null
null
null
// Function: get_disputes_filters_profile // File: crates/router/src/routes/disputes.rs // Module: router pub fn get_disputes_filters_profile( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse
crates/router/src/routes/disputes.rs
router
function_signature
null
null
null
53
get_disputes_filters_profile
null
null
null
null
null
null
// Function: make_dsl_input_for_payouts // File: crates/router/src/core/payments/routing.rs // Module: router pub fn make_dsl_input_for_payouts( payout_data: &payouts::PayoutData, ) -> RoutingResult<dsl_inputs::BackendInput>
crates/router/src/core/payments/routing.rs
router
function_signature
null
null
null
65
make_dsl_input_for_payouts
null
null
null
null
null
null
// Function: update_payout_link // File: crates/diesel_models/src/query/generic_link.rs // Module: diesel_models pub fn update_payout_link( self, conn: &PgPooledConn, payout_link_update: PayoutLinkUpdate, ) -> StorageResult<Self>
crates/diesel_models/src/query/generic_link.rs
diesel_models
function_signature
null
null
null
64
update_payout_link
null
null
null
null
null
null
// Function: add_certificate // File: crates/common_utils/src/request.rs // Module: common_utils pub fn add_certificate(&mut self, certificate: Option<Secret<String>>)
crates/common_utils/src/request.rs
common_utils
function_signature
null
null
null
37
add_certificate
null
null
null
null
null
null
// Implementation: impl ApiEventMetric for for ApplicationResponse // File: crates/hyperswitch_domain_models/src/api.rs // Module: hyperswitch_domain_models // Methods: 1 total (0 public) impl ApiEventMetric for for ApplicationResponse
crates/hyperswitch_domain_models/src/api.rs
hyperswitch_domain_models
impl_block
null
null
null
52
null
ApplicationResponse
ApiEventMetric for
1
0
null
null
// Struct: ConnectorPostAuthenticationRequestData // File: crates/hyperswitch_domain_models/src/router_request_types/authentication.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct ConnectorPostAuthenticationRequestData
crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
hyperswitch_domain_models
struct_definition
ConnectorPostAuthenticationRequestData
0
[]
48
null
null
null
null
null
null
null
// Struct: NoonApplePaymentData // File: crates/hyperswitch_connectors/src/connectors/noon/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct NoonApplePaymentData
crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
hyperswitch_connectors
struct_definition
NoonApplePaymentData
0
[]
49
null
null
null
null
null
null
null
// Implementation: impl api::MandateSetup for for Nordea // File: crates/hyperswitch_connectors/src/connectors/nordea.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::MandateSetup for for Nordea
crates/hyperswitch_connectors/src/connectors/nordea.rs
hyperswitch_connectors
impl_block
null
null
null
62
null
Nordea
api::MandateSetup for
0
0
null
null
connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Jpmorgan, connectors::Klarna, connectors::Loonio, connectors::Netcetera, connectors::Nordea, connectors::Nomupay, connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Signifyd, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Vgs, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_connector_authentication_token { ($($path:ident::$connector:ident),*) => { $( impl ConnectorAuthenticationToken for $path::$connector {} impl ConnectorIntegration< AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, > for $path::$connector {} )* }; } default_imp_for_connector_authentication_token!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Barclaycard, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Billwerk, connectors::Bitpay, connectors::Bluecode, connectors::Bluesnap, connectors::Blackhawknetwork, connectors::Boku, connectors::Braintree, connectors::Breadpay, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Juspaythreedsserver, connectors::Jpmorgan, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mpgs, connectors::Netcetera, connectors::Nomupay, connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, connectors::Opayo, connectors::Opennode, connectors::Payeezy, connectors::Payload, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Paypal, connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Multisafepay, connectors::Paybox, connectors::Payme, connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Sift, connectors::Signifyd, connectors::Shift4, connectors::Silverflow, connectors::Stax, connectors::Stripe, connectors::Stripebilling, connectors::Square, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Vgs, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl ); macro_rules! default_imp_for_external_vault_proxy_payments_create { ($($path:ident::$connector:ident),*) => { $( impl ExternalVaultProxyPaymentsCreateV1 for $path::$connector {} impl ConnectorIntegration< ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData, > for $path::$connector {} )* }; } default_imp_for_external_vault_proxy_payments_create!( connectors::Aci, connectors::Adyen, connectors::Adyenplatform, connectors::Affirm, connectors::Airwallex, connectors::Amazonpay, connectors::Archipel, connectors::Authipay, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Blackhawknetwork, connectors::Bluecode, connectors::Bluesnap, connectors::Braintree, connectors::Breadpay, connectors::Boku, connectors::Cashtocode, connectors::Celero, connectors::Chargebee, connectors::Checkbook, connectors::Checkout, connectors::Coinbase, connectors::Coingate, connectors::Cryptopay, connectors::Custombilling, connectors::Cybersource, connectors::Datatrans, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, connectors::Dwolla, connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Finix, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, connectors::Flexiti, connectors::Forte, connectors::Getnet, connectors::Gigadat, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::HyperswitchVault, connectors::Hyperwallet, connectors::Iatapay, connectors::Inespay, connectors::Itaubank, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Katapult, connectors::Klarna, connectors::Loonio, connectors::Mifinity, connectors::Mollie, connectors::Moneris, connectors::Mpgs, connectors::Multisafepay, connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, connectors::Opennode, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payload, connectors::Payme, connectors::Payone, connectors::Paypal, connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, connectors::Peachpayments, connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, connectors::Riskified, connectors::Santander, connectors::Shift4, connectors::Sift, connectors::Silverflow, connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Tesouro, connectors::Threedsecureio, connectors::Thunes, connectors::Tokenex, connectors::Tokenio, connectors::Trustpay, connectors::Trustpayments, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayvantiv, connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, connectors::Vgs, connectors::Volt, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::CtpMastercard ); #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentsCompleteAuthorize for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorVerifyWebhookSource for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorCustomer for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorRedirectResponse for connectors::DummyConnector<T> { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, _action: PaymentAction, ) -> CustomResult<CallConnectorAction, ConnectorError> { Ok(CallConnectorAction::Trigger) } } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorTransactionId for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> Dispute for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> AcceptDispute for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> FileUpload for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> UploadFile for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> RetrieveFile for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> SubmitEvidence for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> DefendDispute for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> FetchDisputes for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Fetch, FetchDisputesRequestData, FetchDisputesResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> DisputeSync for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Dsync, DisputeSyncData, DisputeSyncResponse> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentsGiftCardBalanceCheck for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentsPreProcessing for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentsPostProcessing for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::Payouts for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutCreate for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutSync for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutEligibility for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutFulfill for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutCancel for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutQuote for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutRecipient for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> PayoutRecipientAccount for connectors::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentApprove for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Approve, PaymentsApproveData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentReject for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Reject, PaymentsRejectData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> FraudCheck for connectors::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> FraudCheckSale for connectors::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> for connectors::DummyConnector<T> { } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> FraudCheckCheckout for connectors::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> for connectors::DummyConnector<T> { } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> FraudCheckTransaction for connectors::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData> for connectors::DummyConnector<T> { } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> FraudCheckFulfillment for connectors::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> for connectors::DummyConnector<T> { } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> FraudCheckRecordReturn for connectors::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentIncrementalAuthorization for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorMandateRevoke for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorPreAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorPreAuthenticationVersionCall for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorPostAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< PostAuthentication, ConnectorPostAuthenticationRequestData, AuthenticationResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentAuthorizeSessionToken for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> TaxCalculation for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentSessionUpdate for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentPostSessionTokens for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentsCreateOrder for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<CreateOrder, CreateOrderRequestData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentUpdateMetadata for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentPostCaptureVoid for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> UasPreAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> UnifiedAuthenticationService for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> UasPostAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> UasAuthenticationConfirmation for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< AuthenticationConfirmation, UasConfirmationRequestData, UasAuthenticationResponseData, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> UasAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> RevenueRecovery for connectors::DummyConnector<T> {} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::revenue_recovery::BillingConnectorPaymentsSyncIntegration for connectors::DummyConnector<T> { } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, > for connectors::DummyConnector<T> { } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::revenue_recovery::RevenueRecoveryRecordBack for connectors::DummyConnector<T> { } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse> for connectors::DummyConnector<T> { } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> BillingConnectorInvoiceSyncIntegration for connectors::DummyConnector<T> {} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalVault for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalVaultInsert for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalVaultRetrieve for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalVaultDelete for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<ExternalVaultDeleteFlow, VaultRequestData, VaultResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalVaultCreate for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData, VaultResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorAuthenticationToken for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> ExternalVaultProxyPaymentsCreateV1 for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData> for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> Subscriptions for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> GetSubscriptionPlanPricesFlow for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< GetSubscriptionPlanPrices, GetSubscriptionPlanPricesRequest, GetSubscriptionPlanPricesResponse, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> GetSubscriptionPlansFlow for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< GetSubscriptionPlans, GetSubscriptionPlansRequest, GetSubscriptionPlansResponse, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> SubscriptionCreate for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< SubscriptionCreateFlow, SubscriptionCreateRequest, SubscriptionCreateResponse, > for connectors::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> GetSubscriptionEstimateFlow for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> ConnectorIntegration< GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse, > for connectors::DummyConnector<T> { }
crates/hyperswitch_connectors/src/default_implementations.rs#chunk7
hyperswitch_connectors
chunk
null
null
null
7,394
null
null
null
null
null
null
null
// Implementation: impl PartialEq for for PaymentIntentMetricsBucketIdentifier // File: crates/api_models/src/analytics/payment_intents.rs // Module: api_models // Methods: 1 total (0 public) impl PartialEq for for PaymentIntentMetricsBucketIdentifier
crates/api_models/src/analytics/payment_intents.rs
api_models
impl_block
null
null
null
52
null
PaymentIntentMetricsBucketIdentifier
PartialEq for
1
0
null
null
// Struct: DieselArray // File: crates/diesel_models/src/lib.rs // Module: diesel_models // Implementations: 0 pub struct DieselArray<T>
crates/diesel_models/src/lib.rs
diesel_models
struct_definition
DieselArray
0
[]
36
null
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/nordea/responses.rs // Module: hyperswitch_connectors // Public structs: 16 use common_enums::CountryAlpha2; use common_utils::types::StringMajorUnit; use masking::Secret; use serde::{Deserialize, Serialize}; use super::requests::{ CreditorAccount, DebitorAccount, InstructedAmount, PaymentsUrgency, RecurringInformation, ThirdPartyMessages, }; // OAuth token response structure #[derive(Debug, Serialize, Deserialize, Clone)] pub struct NordeaOAuthExchangeResponse { pub access_token: Option<Secret<String>>, pub expires_in: Option<i64>, pub refresh_token: Option<Secret<String>>, pub token_type: Option<String>, } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "PascalCase")] pub enum NordeaPaymentStatus { #[default] PendingConfirmation, PendingSecondConfirmation, PendingUserApproval, OnHold, Confirmed, Rejected, Paid, InsufficientFunds, LimitExceeded, UserApprovalFailed, UserApprovalTimeout, UserApprovalCancelled, Unknown, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct NordeaGroupHeader { /// Response creation time. Format: date-time. pub creation_date_time: Option<String>, /// HTTP code for response. Format: int32. pub http_code: Option<i32>, /// Original request id for correlation purposes pub message_identification: Option<String>, /// Details of paginated response pub message_pagination: Option<MessagePagination>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct NordeaResponseLinks { /// Describes the nature of the link, e.g. 'details' for a link to the detailed information of a listed resource. pub rel: Option<String>, /// Relative path to the linked resource pub href: Option<String>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum FeesType { Additional, Standard, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct TransactionFee { /// Monetary amount pub amount: InstructedAmount, pub description: Option<String>, pub excluded_from_total_fee: Option<bool>, pub percentage: Option<bool>, #[serde(rename = "type")] pub fees_type: Option<FeesType>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct BankFee { /// Example 'domestic_transaction' only for DK domestic payments #[serde(rename = "_type")] pub bank_fee_type: Option<String>, /// Country code according to ISO Alpha-2 pub country_code: Option<CountryAlpha2>, /// Currency code according to ISO 4217 pub currency_code: Option<api_models::enums::Currency>, /// Value of the fee. pub value: Option<StringMajorUnit>, pub fees: Option<Vec<TransactionFee>>, /// Monetary amount pub total_fee_amount: InstructedAmount, } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum ChargeBearer { Shar, Debt, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct ExchangeRate { pub base_currency: Option<api_models::enums::Currency>, pub exchange_currency: Option<api_models::enums::Currency>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct MessagePagination { /// Resource listing may return a continuationKey if there's more results available. /// Request may be retried with the continuationKey, but otherwise same parameters, in order to get more results. pub continuation_key: Option<String>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct NordeaPaymentsInitiateResponseData { /// Unique payment identifier assigned for new payment #[serde(rename = "_id")] pub payment_id: String, /// HATEOAS inspired links: 'rel' and 'href'. Context specific link (only GET supported) #[serde(rename = "_links")] pub links: Option<Vec<NordeaResponseLinks>>, /// Marked as required field in the docs, but connector does not send amount in payment_response.amount pub amount: Option<StringMajorUnit>, /// Bearer of charges. shar = The Debtor (sender of the payment) will pay all fees charged by the sending bank. /// The Creditor (recipient of the payment) will pay all fees charged by the receiving bank. /// debt = The Debtor (sender of the payment) will bear all of the payment transaction fees. /// The creditor (beneficiary) will receive the full amount of the payment. pub charge_bearer: Option<ChargeBearer>, /// Creditor of the payment #[serde(rename = "creditor")] pub creditor_account: CreditorAccount, pub currency: Option<api_models::enums::Currency>, /// Debtor of the payment #[serde(rename = "debtor")] pub debitor_account: Option<DebitorAccount>, /// Timestamp of payment creation. ISO 8601 format yyyy-mm-ddThh:mm:ss.fffZ. Format:date-time. pub entry_date_time: Option<String>, /// Unique identification as assigned by a partner to identify the payment. pub external_id: Option<String>, /// An amount the bank will charge for executing the payment pub fee: Option<BankFee>, pub indicative_exchange_rate: Option<ExchangeRate>, /// It is mentioned as `number`. It can be an integer or a decimal number. pub rate: Option<f32>, /// Monetary amount pub instructed_amount: Option<InstructedAmount>, /// Indication of cross border payment to own account pub is_own_account_transfer: Option<bool>, /// OTP Challenge pub otp_challenge: Option<String>, /// Status of the payment pub payment_status: NordeaPaymentStatus, /// Planned execution date will indicate the day the payment will be finalized. If the payment has been pushed due to cut-off, it will be indicated in planned execution date. Format:date. pub planned_execution_date: Option<String>, /// Recurring information pub recurring: Option<RecurringInformation>, /// Choose a preferred execution date (or leave blank for today's date). /// This should be a valid bank day, and depending on the country the date will either be pushed to the next valid bank day, /// or return an error if a non-banking day date was supplied (all dates accepted in sandbox). /// SEPA: max +5 years from yesterday, Domestic: max. +1 year from yesterday. NB: Not supported for Own transfer Non-Recurring Norway. /// Format:date. pub requested_execution_date: Option<String>, /// Timestamp of payment creation. ISO 8601 format yyyy-mm-ddThh:mm:ss.fffZ Format:date-time. pub timestamp: Option<String>, /// Additional messages for third parties pub tpp_messages: Option<Vec<ThirdPartyMessages>>, pub transaction_fee: Option<Vec<BankFee>>, /// Currency that the cross border payment will be transferred in. /// This field is only supported for cross border payments for DK. /// If this field is not supplied then the payment will use the currency specified for the currency field of instructed_amount. pub transfer_currency: Option<api_models::enums::Currency>, /// Urgency of the payment. NB: This field is supported for DK Domestic ('standard' and 'express') and NO Domestic bank transfer payments ('standard' and 'express'). /// Use 'express' for Straksbetaling (Instant payment). /// All other payment types ignore this input. /// For further details on urgencies and cut-offs, refer to the Nordea website. /// Value 'sameday' is marked as deprecated and will be removed in the future. pub urgency: Option<PaymentsUrgency>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct NordeaPaymentsInitiateResponse { /// Payment information #[serde(rename = "response")] pub payments_response: Option<NordeaPaymentsInitiateResponseData>, /// External response header pub group_header: Option<NordeaGroupHeader>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct NordeaPaymentsConfirmErrorObject { /// Error message pub error: Option<String>, /// Description of the error pub error_description: Option<String>, /// Payment id of the payment, the error is associated with pub payment_id: Option<String>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct NordeaPaymentsResponseWrapper { pub payments: Vec<NordeaPaymentsInitiateResponseData>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct NordeaPaymentsConfirmResponse { /// HATEOAS inspired links: 'rel' and 'href' #[serde(rename = "_links")] pub links: Option<Vec<NordeaResponseLinks>>, /// Error description pub errors: Option<Vec<NordeaPaymentsConfirmErrorObject>>, /// External response header pub group_header: Option<NordeaGroupHeader>, /// OTP Challenge pub otp_challenge: Option<String>, #[serde(rename = "response")] pub nordea_payments_response: Option<NordeaPaymentsResponseWrapper>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct NordeaOriginalRequest { /// Original request url #[serde(rename = "url")] pub nordea_url: Option<String>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct NordeaFailures { /// Failure code pub code: Option<String>, /// Failure description pub description: Option<String>, /// JSON path of the failing element if applicable pub path: Option<String>, /// Type of the validation error, e.g. NotNull #[serde(rename = "type")] pub failure_type: Option<String>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct NordeaErrorBody { // Serde JSON because connector returns an `(item)` object in failures array object /// More details on the occurred error: Validation error #[serde(rename = "failures")] pub nordea_failures: Option<Vec<NordeaFailures>>, /// Original request information #[serde(rename = "request")] pub nordea_request: Option<NordeaOriginalRequest>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct NordeaErrorResponse { /// Error response body pub error: Option<NordeaErrorBody>, /// External response header pub group_header: Option<NordeaGroupHeader>, #[serde(rename = "httpCode")] pub http_code: Option<String>, #[serde(rename = "moreInformation")] pub more_information: Option<String>, } // Nordea does not support refunds in Private APIs. Only Corporate APIs support Refunds
crates/hyperswitch_connectors/src/connectors/nordea/responses.rs
hyperswitch_connectors
full_file
null
null
null
2,341
null
null
null
null
null
null
null
// Function: generate_default_totp // File: crates/router/src/utils/user/two_factor_auth.rs // Module: router pub fn generate_default_totp( email: pii::Email, secret: Option<masking::Secret<String>>, issuer: String, ) -> UserResult<TOTP>
crates/router/src/utils/user/two_factor_auth.rs
router
function_signature
null
null
null
64
generate_default_totp
null
null
null
null
null
null
// Function: get_connector_name // File: crates/api_models/src/admin.rs // Module: api_models pub fn get_connector_name(&self) -> String
crates/api_models/src/admin.rs
api_models
function_signature
null
null
null
33
get_connector_name
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/tesouro/transformers.rs // Module: hyperswitch_connectors // Public structs: 8 use common_enums::enums; use common_utils::types::FloatMajorUnit; 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 TesouroRouterData<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 TesouroRouterData<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, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] pub struct TesouroPaymentsRequest { amount: FloatMajorUnit, card: TesouroCard, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct TesouroCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } impl TryFrom<&TesouroRouterData<&PaymentsAuthorizeRouterData>> for TesouroPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &TesouroRouterData<&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 TesouroAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for TesouroAuthType { 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 TesouroPaymentStatus { Succeeded, Failed, #[default] Processing, } impl From<TesouroPaymentStatus> for common_enums::AttemptStatus { fn from(item: TesouroPaymentStatus) -> Self { match item { TesouroPaymentStatus::Succeeded => Self::Charged, TesouroPaymentStatus::Failed => Self::Failure, TesouroPaymentStatus::Processing => Self::Authorizing, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct TesouroPaymentsResponse { status: TesouroPaymentStatus, id: String, } impl<F, T> TryFrom<ResponseRouterData<F, TesouroPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, TesouroPaymentsResponse, 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 TesouroRefundRequest { pub amount: FloatMajorUnit, } impl<F> TryFrom<&TesouroRouterData<&RefundsRouterData<F>>> for TesouroRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &TesouroRouterData<&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 TesouroErrorResponse { 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/tesouro/transformers.rs
hyperswitch_connectors
full_file
null
null
null
1,667
null
null
null
null
null
null
null
// Struct: Instruction // File: crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct Instruction
crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
hyperswitch_connectors
struct_definition
Instruction
0
[]
42
null
null
null
null
null
null
null
// Struct: ErrorDistributionAccumulator // File: crates/analytics/src/payments/accumulator.rs // Module: analytics // Implementations: 1 // Traits: PaymentDistributionAccumulator pub struct ErrorDistributionAccumulator
crates/analytics/src/payments/accumulator.rs
analytics
struct_definition
ErrorDistributionAccumulator
1
[ "PaymentDistributionAccumulator" ]
50
null
null
null
null
null
null
null
// Struct: PaymentResponse // File: crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentResponse
crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
hyperswitch_connectors
struct_definition
PaymentResponse
0
[]
45
null
null
null
null
null
null
null
// File: crates/router/src/core/payments/routing.rs // Module: router // Public functions: 27 // Public structs: 4 mod transformers; pub mod utils; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use std::collections::hash_map; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use std::hash::{Hash, Hasher}; use std::{collections::HashMap, str::FromStr, sync::Arc}; #[cfg(feature = "v1")] use api_models::open_router::{self as or_types, DecidedGateway, OpenRouterDecideGatewayRequest}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing as api_routing; use api_models::{ admin as admin_api, enums::{self as api_enums, CountryAlpha2}, routing::ConnectorSelection, }; use common_types::payments as common_payments_types; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use common_utils::ext_traits::AsyncExt; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use euclid::{ backend::{self, inputs as dsl_inputs, EuclidBackend}, dssa::graph::{self as euclid_graph, CgraphExt}, enums as euclid_enums, frontend::{ast, dir as euclid_dir}, }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use external_services::grpc_client::dynamic_routing::{ contract_routing_client::ContractBasedDynamicRouting, elimination_based_client::EliminationBasedRouting, success_rate_client::SuccessBasedDynamicRouting, DynamicRoutingError, }; use hyperswitch_domain_models::address::Address; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use hyperswitch_interfaces::events::routing_api_logs::{ApiMethod, RoutingEngine}; use kgraph_utils::{ mca as mca_graph, transformers::{IntoContext, IntoDirValue}, types::CountryCurrencyFilter, }; use masking::{PeekInterface, Secret}; use rand::distributions::{self, Distribution}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use rand::SeedableRng; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use router_env::{instrument, tracing}; use rustc_hash::FxHashMap; use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE}; #[cfg(feature = "v2")] use crate::core::admin; #[cfg(feature = "payouts")] use crate::core::payouts; #[cfg(feature = "v1")] use crate::core::routing::transformers::OpenRouterDecideGatewayRequestExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use crate::routes::app::SessionStateInfo; use crate::{ core::{ errors, errors as oss_errors, payments::{ routing::utils::DecisionEngineApiHandler, OperationSessionGetters, OperationSessionSetters, }, routing, }, logger, services, types::{ api::{self, routing as routing_types}, domain, storage as oss_storage, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, }, utils::{OptionExt, ValueExt}, SessionState, }; pub enum CachedAlgorithm { Single(Box<routing_types::RoutableConnectorChoice>), Priority(Vec<routing_types::RoutableConnectorChoice>), VolumeSplit(Vec<routing_types::ConnectorVolumeSplit>), Advanced(backend::VirInterpreterBackend<ConnectorSelection>), } #[cfg(feature = "v1")] pub struct SessionFlowRoutingInput<'a> { pub state: &'a SessionState, pub country: Option<CountryAlpha2>, pub key_store: &'a domain::MerchantKeyStore, pub merchant_account: &'a domain::MerchantAccount, pub payment_attempt: &'a oss_storage::PaymentAttempt, pub payment_intent: &'a oss_storage::PaymentIntent, pub chosen: api::SessionConnectorDatas, } #[cfg(feature = "v2")] pub struct SessionFlowRoutingInput<'a> { pub country: Option<CountryAlpha2>, pub payment_intent: &'a oss_storage::PaymentIntent, pub chosen: api::SessionConnectorDatas, } #[allow(dead_code)] #[cfg(feature = "v1")] pub struct SessionRoutingPmTypeInput<'a> { state: &'a SessionState, key_store: &'a domain::MerchantKeyStore, attempt_id: &'a str, routing_algorithm: &'a MerchantAccountRoutingAlgorithm, backend_input: dsl_inputs::BackendInput, allowed_connectors: FxHashMap<String, api::GetToken>, profile_id: &'a common_utils::id_type::ProfileId, } #[cfg(feature = "v2")] pub struct SessionRoutingPmTypeInput<'a> { routing_algorithm: &'a MerchantAccountRoutingAlgorithm, backend_input: dsl_inputs::BackendInput, allowed_connectors: FxHashMap<String, api::GetToken>, profile_id: &'a common_utils::id_type::ProfileId, } type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>; #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(untagged)] enum MerchantAccountRoutingAlgorithm { V1(routing_types::RoutingAlgorithmRef), } #[cfg(feature = "v1")] impl Default for MerchantAccountRoutingAlgorithm { fn default() -> Self { Self::V1(routing_types::RoutingAlgorithmRef::default()) } } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(untagged)] enum MerchantAccountRoutingAlgorithm { V1(Option<common_utils::id_type::RoutingId>), } #[cfg(feature = "payouts")] pub fn make_dsl_input_for_payouts( payout_data: &payouts::PayoutData, ) -> RoutingResult<dsl_inputs::BackendInput> { let mandate = dsl_inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }; let metadata = payout_data .payouts .metadata .clone() .map(|val| val.parse_value("routing_parameters")) .transpose() .change_context(errors::RoutingError::MetadataParsingError) .attach_printable("Unable to parse routing_parameters from metadata of payouts") .unwrap_or(None); let payment = dsl_inputs::PaymentInput { amount: payout_data.payouts.amount, card_bin: None, currency: payout_data.payouts.destination_currency, authentication_type: None, capture_method: None, business_country: payout_data .payout_attempt .business_country .map(api_enums::Country::from_alpha2), billing_country: payout_data .billing_address .as_ref() .and_then(|ba| ba.address.as_ref()) .and_then(|addr| addr.country) .map(api_enums::Country::from_alpha2), business_label: payout_data.payout_attempt.business_label.clone(), setup_future_usage: None, }; let payment_method = dsl_inputs::PaymentMethodInput { payment_method: payout_data .payouts .payout_type .map(api_enums::PaymentMethod::foreign_from), payment_method_type: payout_data .payout_method_data .as_ref() .map(api_enums::PaymentMethodType::foreign_from) .or_else(|| { payout_data.payment_method.as_ref().and_then(|pm| { #[cfg(feature = "v1")] { pm.payment_method_type } #[cfg(feature = "v2")] { pm.payment_method_subtype } }) }), card_network: None, }; Ok(dsl_inputs::BackendInput { mandate, metadata, payment, payment_method, acquirer_data: None, customer_device_data: None, issuer_data: None, }) } #[cfg(feature = "v2")] pub fn make_dsl_input( payments_dsl_input: &routing::PaymentsDslInput<'_>, ) -> RoutingResult<dsl_inputs::BackendInput> { let mandate_data = dsl_inputs::MandateData { mandate_acceptance_type: payments_dsl_input.setup_mandate.as_ref().and_then( |mandate_data| { mandate_data .customer_acceptance .as_ref() .map(|customer_accept| match customer_accept.acceptance_type { common_payments_types::AcceptanceType::Online => { euclid_enums::MandateAcceptanceType::Online } common_payments_types::AcceptanceType::Offline => { euclid_enums::MandateAcceptanceType::Offline } }) }, ), mandate_type: payments_dsl_input .setup_mandate .as_ref() .and_then(|mandate_data| { mandate_data .mandate_type .clone() .map(|mandate_type| match mandate_type { hyperswitch_domain_models::mandates::MandateDataType::SingleUse(_) => { euclid_enums::MandateType::SingleUse } hyperswitch_domain_models::mandates::MandateDataType::MultiUse(_) => { euclid_enums::MandateType::MultiUse } }) }), payment_type: Some( if payments_dsl_input .recurring_details .as_ref() .is_some_and(|data| { matches!( data, api_models::mandates::RecurringDetails::ProcessorPaymentToken(_) ) }) { euclid_enums::PaymentType::PptMandate } else { payments_dsl_input.setup_mandate.map_or_else( || euclid_enums::PaymentType::NonMandate, |_| euclid_enums::PaymentType::SetupMandate, ) }, ), }; let payment_method_input = dsl_inputs::PaymentMethodInput { payment_method: Some(payments_dsl_input.payment_attempt.payment_method_type), payment_method_type: Some(payments_dsl_input.payment_attempt.payment_method_subtype), card_network: payments_dsl_input .payment_method_data .as_ref() .and_then(|pm_data| match pm_data { domain::PaymentMethodData::Card(card) => card.card_network.clone(), _ => None, }), }; let payment_input = dsl_inputs::PaymentInput { amount: payments_dsl_input .payment_attempt .amount_details .get_net_amount(), card_bin: payments_dsl_input.payment_method_data.as_ref().and_then( |pm_data| match pm_data { domain::PaymentMethodData::Card(card) => Some(card.card_number.get_card_isin()), _ => None, }, ), currency: payments_dsl_input.currency, authentication_type: Some(payments_dsl_input.payment_attempt.authentication_type), capture_method: Some(payments_dsl_input.payment_intent.capture_method), business_country: None, billing_country: payments_dsl_input .address .get_payment_method_billing() .and_then(|billing_address| billing_address.address.as_ref()) .and_then(|address_details| address_details.country) .map(api_enums::Country::from_alpha2), business_label: None, setup_future_usage: Some(payments_dsl_input.payment_intent.setup_future_usage), }; let metadata = payments_dsl_input .payment_intent .metadata .clone() .map(|value| value.parse_value("routing_parameters")) .transpose() .change_context(errors::RoutingError::MetadataParsingError) .attach_printable("Unable to parse routing_parameters from metadata of payment_intent") .unwrap_or(None); Ok(dsl_inputs::BackendInput { metadata, payment: payment_input, payment_method: payment_method_input, mandate: mandate_data, acquirer_data: None, customer_device_data: None, issuer_data: None, }) } #[cfg(feature = "v1")] pub fn make_dsl_input( payments_dsl_input: &routing::PaymentsDslInput<'_>, ) -> RoutingResult<dsl_inputs::BackendInput> { let mandate_data = dsl_inputs::MandateData { mandate_acceptance_type: payments_dsl_input.setup_mandate.as_ref().and_then( |mandate_data| { mandate_data .customer_acceptance .as_ref() .map(|cat| match cat.acceptance_type { common_payments_types::AcceptanceType::Online => { euclid_enums::MandateAcceptanceType::Online } common_payments_types::AcceptanceType::Offline => { euclid_enums::MandateAcceptanceType::Offline } }) }, ), mandate_type: payments_dsl_input .setup_mandate .as_ref() .and_then(|mandate_data| { mandate_data.mandate_type.clone().map(|mt| match mt { hyperswitch_domain_models::mandates::MandateDataType::SingleUse(_) => { euclid_enums::MandateType::SingleUse } hyperswitch_domain_models::mandates::MandateDataType::MultiUse(_) => { euclid_enums::MandateType::MultiUse } }) }), payment_type: Some( if payments_dsl_input .recurring_details .as_ref() .is_some_and(|data| { matches!( data, api_models::mandates::RecurringDetails::ProcessorPaymentToken(_) ) }) { euclid_enums::PaymentType::PptMandate } else { payments_dsl_input.setup_mandate.map_or_else( || euclid_enums::PaymentType::NonMandate, |_| euclid_enums::PaymentType::SetupMandate, ) }, ), }; let payment_method_input = dsl_inputs::PaymentMethodInput { payment_method: payments_dsl_input.payment_attempt.payment_method, payment_method_type: payments_dsl_input.payment_attempt.payment_method_type, card_network: payments_dsl_input .payment_method_data .as_ref() .and_then(|pm_data| match pm_data { domain::PaymentMethodData::Card(card) => card.card_network.clone(), _ => None, }), }; let payment_input = dsl_inputs::PaymentInput { amount: payments_dsl_input.payment_attempt.get_total_amount(), card_bin: payments_dsl_input.payment_method_data.as_ref().and_then( |pm_data| match pm_data { domain::PaymentMethodData::Card(card) => { Some(card.card_number.peek().chars().take(6).collect()) } _ => None, }, ), currency: payments_dsl_input.currency, authentication_type: payments_dsl_input.payment_attempt.authentication_type, capture_method: payments_dsl_input .payment_attempt .capture_method .and_then(|cm| cm.foreign_into()), business_country: payments_dsl_input .payment_intent .business_country .map(api_enums::Country::from_alpha2), billing_country: payments_dsl_input .address .get_payment_method_billing() .and_then(|bic| bic.address.as_ref()) .and_then(|add| add.country) .map(api_enums::Country::from_alpha2), business_label: payments_dsl_input.payment_intent.business_label.clone(), setup_future_usage: payments_dsl_input.payment_intent.setup_future_usage, }; let metadata = payments_dsl_input .payment_intent .parse_and_get_metadata("routing_parameters") .change_context(errors::RoutingError::MetadataParsingError) .attach_printable("Unable to parse routing_parameters from metadata of payment_intent") .unwrap_or(None); Ok(dsl_inputs::BackendInput { metadata, payment: payment_input, payment_method: payment_method_input, mandate: mandate_data, acquirer_data: None, customer_device_data: None, issuer_data: None, }) } pub async fn perform_static_routing_v1( state: &SessionState, merchant_id: &common_utils::id_type::MerchantId, algorithm_id: Option<&common_utils::id_type::RoutingId>, business_profile: &domain::Profile, transaction_data: &routing::TransactionData<'_>, ) -> RoutingResult<( Vec<routing_types::RoutableConnectorChoice>, Option<common_enums::RoutingApproach>, )> { logger::debug!("euclid_routing: performing routing for connector selection"); let get_merchant_fallback_config = || async { #[cfg(feature = "v1")] return routing::helpers::get_merchant_default_config( &*state.clone().store, business_profile.get_id().get_string_repr(), &api_enums::TransactionType::from(transaction_data), ) .await .change_context(errors::RoutingError::FallbackConfigFetchFailed); #[cfg(feature = "v2")] return admin::ProfileWrapper::new(business_profile.clone()) .get_default_fallback_list_of_connector_under_profile() .change_context(errors::RoutingError::FallbackConfigFetchFailed); }; let algorithm_id = if let Some(id) = algorithm_id { id } else { let fallback_config = get_merchant_fallback_config().await?; logger::debug!("euclid_routing: active algorithm isn't present, default falling back"); return Ok((fallback_config, None)); }; let cached_algorithm = ensure_algorithm_cached_v1( state, merchant_id, algorithm_id, business_profile.get_id(), &api_enums::TransactionType::from(transaction_data), ) .await?; let backend_input = match transaction_data { routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?, #[cfg(feature = "payouts")] routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?, }; let payment_id = match transaction_data { routing::TransactionData::Payment(payment_data) => payment_data .payment_attempt .payment_id .clone() .get_string_repr() .to_string(), #[cfg(feature = "payouts")] routing::TransactionData::Payout(payout_data) => payout_data .payout_attempt .payout_id .get_string_repr() .to_string(), }; // Decision of de-routing is stored let de_evaluated_connector = if !state.conf.open_router.static_routing_enabled { logger::debug!("decision_engine_euclid: decision_engine routing not enabled"); Vec::default() } else { utils::decision_engine_routing( state, backend_input.clone(), business_profile, payment_id, get_merchant_fallback_config().await?, ) .await .map_err(|e| // errors are ignored as this is just for diff checking as of now (optional flow). logger::error!(decision_engine_euclid_evaluate_error=?e, "decision_engine_euclid: error in evaluation of rule") ) .unwrap_or_default() }; let (routable_connectors, routing_approach) = match cached_algorithm.as_ref() { CachedAlgorithm::Single(conn) => ( vec![(**conn).clone()], Some(common_enums::RoutingApproach::StraightThroughRouting), ), CachedAlgorithm::Priority(plist) => (plist.clone(), None), CachedAlgorithm::VolumeSplit(splits) => ( perform_volume_split(splits.to_vec()) .change_context(errors::RoutingError::ConnectorSelectionFailed)?, Some(common_enums::RoutingApproach::VolumeBasedRouting), ), CachedAlgorithm::Advanced(interpreter) => ( execute_dsl_and_get_connector_v1(backend_input, interpreter)?, Some(common_enums::RoutingApproach::RuleBasedRouting), ), }; // Results are logged for diff(between legacy and decision_engine's euclid) and have parameters as: // is_equal: verifies all output are matching in order, // is_equal_length: matches length of both outputs (useful for verifying volume based routing // results) // de_response: response from the decision_engine's euclid // hs_response: response from legacy_euclid utils::compare_and_log_result( de_evaluated_connector.clone(), routable_connectors.clone(), "evaluate_routing".to_string(), ); Ok(( utils::select_routing_result( state, business_profile, routable_connectors, de_evaluated_connector, ) .await, routing_approach, )) } async fn ensure_algorithm_cached_v1( state: &SessionState, merchant_id: &common_utils::id_type::MerchantId, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, transaction_type: &api_enums::TransactionType, ) -> RoutingResult<Arc<CachedAlgorithm>> { let key = { match transaction_type { common_enums::TransactionType::Payment => { format!( "routing_config_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr(), ) } #[cfg(feature = "payouts")] common_enums::TransactionType::Payout => { format!( "routing_config_po_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr() ) } common_enums::TransactionType::ThreeDsAuthentication => { Err(errors::RoutingError::InvalidTransactionType)? } } }; let cached_algorithm = ROUTING_CACHE .get_val::<Arc<CachedAlgorithm>>(CacheKey { key: key.clone(), prefix: state.tenant.redis_key_prefix.clone(), }) .await; let algorithm = if let Some(algo) = cached_algorithm { algo } else { refresh_routing_cache_v1(state, key.clone(), algorithm_id, profile_id).await? }; Ok(algorithm) } pub fn perform_straight_through_routing( algorithm: &routing_types::StraightThroughAlgorithm, creds_identifier: Option<&str>, ) -> RoutingResult<(Vec<routing_types::RoutableConnectorChoice>, bool)> { Ok(match algorithm { routing_types::StraightThroughAlgorithm::Single(conn) => { (vec![(**conn).clone()], creds_identifier.is_none()) } routing_types::StraightThroughAlgorithm::Priority(conns) => (conns.clone(), true), routing_types::StraightThroughAlgorithm::VolumeSplit(splits) => ( perform_volume_split(splits.to_vec()) .change_context(errors::RoutingError::ConnectorSelectionFailed) .attach_printable( "Volume Split connector selection error in straight through routing", )?, true, ), }) } pub fn perform_routing_for_single_straight_through_algorithm( algorithm: &routing_types::StraightThroughAlgorithm, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { Ok(match algorithm { routing_types::StraightThroughAlgorithm::Single(connector) => vec![(**connector).clone()], routing_types::StraightThroughAlgorithm::Priority(_) | routing_types::StraightThroughAlgorithm::VolumeSplit(_) => { Err(errors::RoutingError::DslIncorrectSelectionAlgorithm) .attach_printable("Unsupported algorithm received as a result of static routing")? } }) } fn execute_dsl_and_get_connector_v1( backend_input: dsl_inputs::BackendInput, interpreter: &backend::VirInterpreterBackend<ConnectorSelection>, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { let routing_output: routing_types::StaticRoutingAlgorithm = interpreter .execute(backend_input) .map(|out| out.connector_selection.foreign_into()) .change_context(errors::RoutingError::DslExecutionError)?; Ok(match routing_output { routing_types::StaticRoutingAlgorithm::Priority(plist) => plist, routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => perform_volume_split(splits) .change_context(errors::RoutingError::DslFinalConnectorSelectionFailed)?, _ => Err(errors::RoutingError::DslIncorrectSelectionAlgorithm) .attach_printable("Unsupported algorithm received as a result of static routing")?, }) } pub async fn refresh_routing_cache_v1( state: &SessionState, key: String, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> RoutingResult<Arc<CachedAlgorithm>> { let algorithm = { let algorithm = state .store .find_routing_algorithm_by_profile_id_algorithm_id(profile_id, algorithm_id) .await .change_context(errors::RoutingError::DslMissingInDb)?; let algorithm: routing_types::StaticRoutingAlgorithm = algorithm .algorithm_data .parse_value("RoutingAlgorithm") .change_context(errors::RoutingError::DslParsingError)?; algorithm }; let cached_algorithm = match algorithm { routing_types::StaticRoutingAlgorithm::Single(conn) => CachedAlgorithm::Single(conn), routing_types::StaticRoutingAlgorithm::Priority(plist) => CachedAlgorithm::Priority(plist), routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => { CachedAlgorithm::VolumeSplit(splits) } routing_types::StaticRoutingAlgorithm::Advanced(program) => { let interpreter = backend::VirInterpreterBackend::with_program(program) .change_context(errors::RoutingError::DslBackendInitError) .attach_printable("Error initializing DSL interpreter backend")?; CachedAlgorithm::Advanced(interpreter) } api_models::routing::StaticRoutingAlgorithm::ThreeDsDecisionRule(_program) => { Err(errors::RoutingError::InvalidRoutingAlgorithmStructure) .attach_printable("Unsupported algorithm received")? } }; let arc_cached_algorithm = Arc::new(cached_algorithm); ROUTING_CACHE .push( CacheKey { key, prefix: state.tenant.redis_key_prefix.clone(), }, arc_cached_algorithm.clone(), ) .await; Ok(arc_cached_algorithm) } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub fn perform_dynamic_routing_volume_split( splits: Vec<api_models::routing::RoutingVolumeSplit>, rng_seed: Option<&str>, ) -> RoutingResult<api_models::routing::RoutingVolumeSplit> { let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect(); let weighted_index = distributions::WeightedIndex::new(weights) .change_context(errors::RoutingError::VolumeSplitFailed) .attach_printable("Error creating weighted distribution for volume split")?; let idx = if let Some(seed) = rng_seed { let mut hasher = hash_map::DefaultHasher::new(); seed.hash(&mut hasher); let hash = hasher.finish(); let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(hash); weighted_index.sample(&mut rng) } else { let mut rng = rand::thread_rng(); weighted_index.sample(&mut rng) }; let routing_choice = *splits .get(idx) .ok_or(errors::RoutingError::VolumeSplitFailed) .attach_printable("Volume split index lookup failed")?; Ok(routing_choice) } pub fn perform_volume_split( mut splits: Vec<routing_types::ConnectorVolumeSplit>, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect(); let weighted_index = distributions::WeightedIndex::new(weights) .change_context(errors::RoutingError::VolumeSplitFailed) .attach_printable("Error creating weighted distribution for volume split")?; let mut rng = rand::thread_rng(); let idx = weighted_index.sample(&mut rng); splits .get(idx) .ok_or(errors::RoutingError::VolumeSplitFailed) .attach_printable("Volume split index lookup failed")?; // Panic Safety: We have performed a `get(idx)` operation just above which will // ensure that the index is always present, else throw an error. let removed = splits.remove(idx); splits.insert(0, removed); Ok(splits.into_iter().map(|sp| sp.connector).collect()) } // #[cfg(feature = "v1")] pub async fn get_merchant_cgraph( state: &SessionState, key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, transaction_type: &api_enums::TransactionType, ) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> { let merchant_id = &key_store.merchant_id; let key = { match transaction_type { api_enums::TransactionType::Payment => { format!( "cgraph_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr() ) } #[cfg(feature = "payouts")] api_enums::TransactionType::Payout => { format!( "cgraph_po_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr() ) } api_enums::TransactionType::ThreeDsAuthentication => { Err(errors::RoutingError::InvalidTransactionType)? } } }; let cached_cgraph = CGRAPH_CACHE .get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>>( CacheKey { key: key.clone(), prefix: state.tenant.redis_key_prefix.clone(), }, ) .await; let cgraph = if let Some(graph) = cached_cgraph { graph } else { refresh_cgraph_cache(state, key_store, key.clone(), profile_id, transaction_type).await? }; Ok(cgraph) } // #[cfg(feature = "v1")] pub async fn refresh_cgraph_cache( state: &SessionState, key_store: &domain::MerchantKeyStore, key: String, profile_id: &common_utils::id_type::ProfileId, transaction_type: &api_enums::TransactionType, ) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> { let mut merchant_connector_accounts = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), &key_store.merchant_id, false, key_store, ) .await .change_context(errors::RoutingError::KgraphCacheRefreshFailed)?; match transaction_type { api_enums::TransactionType::Payment => { merchant_connector_accounts.retain(|mca| { mca.connector_type != storage_enums::ConnectorType::PaymentVas && mca.connector_type != storage_enums::ConnectorType::PaymentMethodAuth && mca.connector_type != storage_enums::ConnectorType::PayoutProcessor && mca.connector_type != storage_enums::ConnectorType::AuthenticationProcessor }); } #[cfg(feature = "payouts")] api_enums::TransactionType::Payout => { merchant_connector_accounts .retain(|mca| mca.connector_type == storage_enums::ConnectorType::PayoutProcessor); } api_enums::TransactionType::ThreeDsAuthentication => { Err(errors::RoutingError::InvalidTransactionType)? } }; let connector_type = match transaction_type { api_enums::TransactionType::Payment => common_enums::ConnectorType::PaymentProcessor, #[cfg(feature = "payouts")] api_enums::TransactionType::Payout => common_enums::ConnectorType::PayoutProcessor, api_enums::TransactionType::ThreeDsAuthentication => { Err(errors::RoutingError::InvalidTransactionType)? } }; let merchant_connector_accounts = merchant_connector_accounts .filter_based_on_profile_and_connector_type(profile_id, connector_type); let api_mcas = merchant_connector_accounts .into_iter() .map(admin_api::MerchantConnectorResponse::foreign_try_from) .collect::<Result<Vec<_>, _>>() .change_context(errors::RoutingError::KgraphCacheRefreshFailed)?; let connector_configs = state .conf .pm_filters .0 .clone() .into_iter() .filter(|(key, _)| key != "default") .map(|(key, value)| { let key = api_enums::RoutableConnectors::from_str(&key) .map_err(|_| errors::RoutingError::InvalidConnectorName(key))?; Ok((key, value.foreign_into())) }) .collect::<Result<HashMap<_, _>, errors::RoutingError>>()?; let default_configs = state .conf .pm_filters .0 .get("default") .cloned() .map(ForeignFrom::foreign_from); let config_pm_filters = CountryCurrencyFilter { connector_configs, default_configs, }; let cgraph = Arc::new( mca_graph::make_mca_graph(api_mcas, &config_pm_filters) .change_context(errors::RoutingError::KgraphCacheRefreshFailed) .attach_printable("when construction cgraph")?, ); CGRAPH_CACHE .push( CacheKey { key, prefix: state.tenant.redis_key_prefix.clone(), }, Arc::clone(&cgraph), ) .await; Ok(cgraph) } #[allow(clippy::too_many_arguments)] pub async fn perform_cgraph_filtering( state: &SessionState, key_store: &domain::MerchantKeyStore, chosen: Vec<routing_types::RoutableConnectorChoice>, backend_input: dsl_inputs::BackendInput, eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, profile_id: &common_utils::id_type::ProfileId, transaction_type: &api_enums::TransactionType, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { let context = euclid_graph::AnalysisContext::from_dir_values( backend_input .into_context() .change_context(errors::RoutingError::KgraphAnalysisError)?, ); let cached_cgraph = get_merchant_cgraph(state, key_store, profile_id, transaction_type).await?; let mut final_selection = Vec::<routing_types::RoutableConnectorChoice>::new(); for choice in chosen { let routable_connector = choice.connector; let euclid_choice: ast::ConnectorChoice = choice.clone().foreign_into(); let dir_val = euclid_choice .into_dir_value() .change_context(errors::RoutingError::KgraphAnalysisError)?; let cgraph_eligible = cached_cgraph .check_value_validity( dir_val, &context, &mut hyperswitch_constraint_graph::Memoization::new(), &mut hyperswitch_constraint_graph::CycleCheck::new(), None, ) .change_context(errors::RoutingError::KgraphAnalysisError)?; let filter_eligible = eligible_connectors.is_none_or(|list| list.contains(&routable_connector)); if cgraph_eligible && filter_eligible { final_selection.push(choice); } } Ok(final_selection) } pub async fn perform_eligibility_analysis( state: &SessionState, key_store: &domain::MerchantKeyStore, chosen: Vec<routing_types::RoutableConnectorChoice>, transaction_data: &routing::TransactionData<'_>, eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, profile_id: &common_utils::id_type::ProfileId, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { let backend_input = match transaction_data { routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?, #[cfg(feature = "payouts")] routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?, }; perform_cgraph_filtering( state, key_store, chosen, backend_input, eligible_connectors, profile_id, &api_enums::TransactionType::from(transaction_data), ) .await } pub async fn perform_fallback_routing( state: &SessionState, key_store: &domain::MerchantKeyStore, transaction_data: &routing::TransactionData<'_>, eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, business_profile: &domain::Profile, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { #[cfg(feature = "v1")] let fallback_config = routing::helpers::get_merchant_default_config( &*state.store, match transaction_data {
crates/router/src/core/payments/routing.rs#chunk0
router
chunk
null
null
null
8,181
null
null
null
null
null
null
null
// Struct: AuthenticationDetails // File: crates/router/src/types/payment_methods.rs // Module: router // Implementations: 0 pub struct AuthenticationDetails
crates/router/src/types/payment_methods.rs
router
struct_definition
AuthenticationDetails
0
[]
33
null
null
null
null
null
null
null
// Struct: TesouroPaymentsRequest // File: crates/hyperswitch_connectors/src/connectors/tesouro/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct TesouroPaymentsRequest
crates/hyperswitch_connectors/src/connectors/tesouro/transformers.rs
hyperswitch_connectors
struct_definition
TesouroPaymentsRequest
0
[]
50
null
null
null
null
null
null
null
// Implementation: impl ConnectorCommon for for Payme // File: crates/hyperswitch_connectors/src/connectors/payme.rs // Module: hyperswitch_connectors // Methods: 5 total (0 public) impl ConnectorCommon for for Payme
crates/hyperswitch_connectors/src/connectors/payme.rs
hyperswitch_connectors
impl_block
null
null
null
53
null
Payme
ConnectorCommon for
5
0
null
null
// Function: get_specific_file_key // File: crates/router/src/utils/user/theme.rs // Module: router pub fn get_specific_file_key(theme_id: &str, file_name: &str) -> PathBuf
crates/router/src/utils/user/theme.rs
router
function_signature
null
null
null
45
get_specific_file_key
null
null
null
null
null
null
// Struct: Merchant // File: crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct Merchant
crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
hyperswitch_connectors
struct_definition
Merchant
0
[]
44
null
null
null
null
null
null
null
// Implementation: impl api::PaymentSession for for Amazonpay // File: crates/hyperswitch_connectors/src/connectors/amazonpay.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentSession for for Amazonpay
crates/hyperswitch_connectors/src/connectors/amazonpay.rs
hyperswitch_connectors
impl_block
null
null
null
58
null
Amazonpay
api::PaymentSession for
0
0
null
null
// Function: frm_fulfillment_core // File: crates/router/src/core/fraud_check.rs // Module: router pub fn frm_fulfillment_core( state: SessionState, merchant_context: domain::MerchantContext, req: frm_core_types::FrmFulfillmentRequest, ) -> RouterResponse<frm_types::FraudCheckResponseData>
crates/router/src/core/fraud_check.rs
router
function_signature
null
null
null
77
frm_fulfillment_core
null
null
null
null
null
null
// Implementation: impl api::RefundSync for for Mifinity // File: crates/hyperswitch_connectors/src/connectors/mifinity.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::RefundSync for for Mifinity
crates/hyperswitch_connectors/src/connectors/mifinity.rs
hyperswitch_connectors
impl_block
null
null
null
62
null
Mifinity
api::RefundSync for
0
0
null
null
// Implementation: impl SerializableSecret for for i8 // File: crates/masking/src/serde.rs // Module: masking // Methods: 0 total (0 public) impl SerializableSecret for for i8
crates/masking/src/serde.rs
masking
impl_block
null
null
null
44
null
i8
SerializableSecret for
0
0
null
null
// Implementation: impl UcsReferenceId // File: crates/common_utils/src/ucs_types.rs // Module: common_utils // Methods: 1 total (1 public) impl UcsReferenceId
crates/common_utils/src/ucs_types.rs
common_utils
impl_block
null
null
null
42
null
UcsReferenceId
null
1
1
null
null
// Function: invalidate // File: crates/router/src/routes/cache.rs // Module: router pub fn invalidate( state: web::Data<AppState>, req: HttpRequest, key: web::Path<String>, ) -> impl Responder
crates/router/src/routes/cache.rs
router
function_signature
null
null
null
51
invalidate
null
null
null
null
null
null
// Struct: ApiRequest // File: crates/hyperswitch_connectors/src/connectors/zen/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ApiRequest
crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
hyperswitch_connectors
struct_definition
ApiRequest
0
[]
45
null
null
null
null
null
null
null
// Implementation: impl api::PaymentSync for for UnifiedAuthenticationService // File: crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentSync for for UnifiedAuthenticationService
crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
UnifiedAuthenticationService
api::PaymentSync for
0
0
null
null
// Struct: PaysafeProfile // File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaysafeProfile
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
hyperswitch_connectors
struct_definition
PaysafeProfile
0
[]
48
null
null
null
null
null
null
null
// Implementation: impl ToTokens for for OperationsEnumMeta // File: crates/router_derive/src/macros/operation.rs // Module: router_derive // Methods: 1 total (0 public) impl ToTokens for for OperationsEnumMeta
crates/router_derive/src/macros/operation.rs
router_derive
impl_block
null
null
null
51
null
OperationsEnumMeta
ToTokens for
1
0
null
null
// Implementation: impl api::PaymentCapture for for Katapult // File: crates/hyperswitch_connectors/src/connectors/katapult.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentCapture for for Katapult
crates/hyperswitch_connectors/src/connectors/katapult.rs
hyperswitch_connectors
impl_block
null
null
null
58
null
Katapult
api::PaymentCapture for
0
0
null
null
// Struct: PaymentIntent // File: crates/hyperswitch_domain_models/src/payments.rs // Module: hyperswitch_domain_models // Implementations: 2 pub struct PaymentIntent
crates/hyperswitch_domain_models/src/payments.rs
hyperswitch_domain_models
struct_definition
PaymentIntent
2
[]
40
null
null
null
null
null
null
null
// Module Structure // File: crates/hyperswitch_connectors/src/connectors/fiservemea.rs // Module: hyperswitch_connectors // Public submodules: pub mod transformers;
crates/hyperswitch_connectors/src/connectors/fiservemea.rs
hyperswitch_connectors
module_structure
null
null
null
41
null
null
null
null
null
1
0
// Struct: RefundReasonAccumulator // File: crates/analytics/src/refunds/accumulator.rs // Module: analytics // Implementations: 1 // Traits: RefundMetricAccumulator pub struct RefundReasonAccumulator
crates/analytics/src/refunds/accumulator.rs
analytics
struct_definition
RefundReasonAccumulator
1
[ "RefundMetricAccumulator" ]
53
null
null
null
null
null
null
null
// Implementation: impl api::Payment for for Fiservemea // File: crates/hyperswitch_connectors/src/connectors/fiservemea.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::Payment for for Fiservemea
crates/hyperswitch_connectors/src/connectors/fiservemea.rs
hyperswitch_connectors
impl_block
null
null
null
64
null
Fiservemea
api::Payment for
0
0
null
null
// Implementation: impl ToArchipelBillingAddress for for AddressDetails // File: crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs // Module: hyperswitch_connectors // Methods: 1 total (0 public) impl ToArchipelBillingAddress for for AddressDetails
crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs
hyperswitch_connectors
impl_block
null
null
null
62
null
AddressDetails
ToArchipelBillingAddress for
1
0
null
null
// Struct: GooglePayAllowedPaymentMethods // File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct GooglePayAllowedPaymentMethods
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
hyperswitch_connectors
struct_definition
GooglePayAllowedPaymentMethods
0
[]
52
null
null
null
null
null
null
null
// File: crates/router/tests/connectors/bitpay.rs // Module: router use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums, PaymentAddress}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct BitpayTest; impl ConnectorActions for BitpayTest {} impl utils::Connector for BitpayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Bitpay; utils::construct_connector_data_old( Box::new(Bitpay::new()), types::Connector::Bitpay, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .bitpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "bitpay".to_string() } } static CONNECTOR: BitpayTest = BitpayTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: None, network: None, }), confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, // capture_method: Some(capture_method), browser_info: None, order_details: None, order_category: None, email: None, customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, router_return_url: Some(String::from("https://google.com/")), webhook_url: Some(String::from("https://google.com/")), complete_authorize_url: None, capture_method: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, ..utils::PaymentAuthorizeType::default().0 }) } // Creates a payment using the manual capture flow #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let resp = response.clone().response.ok().unwrap(); assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); let endpoint = match resp { types::PaymentsResponseData::TransactionResponse { redirection_data, .. } => Some(redirection_data), _ => None, }; assert!(endpoint.is_some()) } // Synchronizes a successful transaction. #[actix_web::test] async fn should_sync_authorized_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "NPf27TDfyU5mhcTCw2oaq4".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a expired transaction. #[actix_web::test] async fn should_sync_expired_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "bUsFf4RjQEahjbjGcETRS".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Failure); }
crates/router/tests/connectors/bitpay.rs
router
full_file
null
null
null
1,166
null
null
null
null
null
null
null
// Struct: CaptureOptions // File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct CaptureOptions
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
hyperswitch_connectors
struct_definition
CaptureOptions
0
[]
48
null
null
null
null
null
null
null
// File: crates/analytics/src/search.rs // Module: analytics // Public functions: 3 use api_models::analytics::search::{ GetGlobalSearchRequest, GetSearchRequestWithIndex, GetSearchResponse, OpenMsearchOutput, OpensearchOutput, SearchIndex, SearchStatus, }; use common_utils::errors::{CustomResult, ReportSwitchExt}; use error_stack::ResultExt; use router_env::tracing; use serde_json::Value; use crate::{ enums::AuthInfo, opensearch::{OpenSearchClient, OpenSearchError, OpenSearchQuery, OpenSearchQueryBuilder}, }; pub fn convert_to_value<T: Into<Value>>(items: Vec<T>) -> Vec<Value> { items.into_iter().map(|item| item.into()).collect() } pub async fn msearch_results( client: &OpenSearchClient, req: GetGlobalSearchRequest, search_params: Vec<AuthInfo>, indexes: Vec<SearchIndex>, ) -> CustomResult<Vec<GetSearchResponse>, OpenSearchError> { if req.query.trim().is_empty() && req .filters .as_ref() .is_none_or(|filters| filters.is_all_none()) { return Err(OpenSearchError::BadRequestError( "Both query and filters are empty".to_string(), ) .into()); } let mut query_builder = OpenSearchQueryBuilder::new( OpenSearchQuery::Msearch(indexes.clone()), req.query, search_params, ); if let Some(filters) = req.filters { if let Some(currency) = filters.currency { if !currency.is_empty() { query_builder .add_filter_clause("currency.keyword".to_string(), convert_to_value(currency)) .switch()?; } }; if let Some(status) = filters.status { if !status.is_empty() { query_builder .add_filter_clause("status.keyword".to_string(), convert_to_value(status)) .switch()?; } }; if let Some(payment_method) = filters.payment_method { if !payment_method.is_empty() { query_builder .add_filter_clause( "payment_method.keyword".to_string(), convert_to_value(payment_method), ) .switch()?; } }; if let Some(customer_email) = filters.customer_email { if !customer_email.is_empty() { query_builder .add_filter_clause( "customer_email.keyword".to_string(), convert_to_value( customer_email .iter() .filter_map(|email| { // TODO: Add trait based inputs instead of converting this to strings serde_json::to_value(email) .ok() .and_then(|a| a.as_str().map(|a| a.to_string())) }) .collect(), ), ) .switch()?; } }; if let Some(search_tags) = filters.search_tags { if !search_tags.is_empty() { query_builder .add_filter_clause( "feature_metadata.search_tags.keyword".to_string(), convert_to_value( search_tags .iter() .filter_map(|search_tag| { // TODO: Add trait based inputs instead of converting this to strings serde_json::to_value(search_tag) .ok() .and_then(|a| a.as_str().map(|a| a.to_string())) }) .collect(), ), ) .switch()?; } }; if let Some(connector) = filters.connector { if !connector.is_empty() { query_builder .add_filter_clause("connector.keyword".to_string(), convert_to_value(connector)) .switch()?; } }; if let Some(payment_method_type) = filters.payment_method_type { if !payment_method_type.is_empty() { query_builder .add_filter_clause( "payment_method_type.keyword".to_string(), convert_to_value(payment_method_type), ) .switch()?; } }; if let Some(card_network) = filters.card_network { if !card_network.is_empty() { query_builder .add_filter_clause( "card_network.keyword".to_string(), convert_to_value(card_network), ) .switch()?; } }; if let Some(card_last_4) = filters.card_last_4 { if !card_last_4.is_empty() { query_builder .add_filter_clause( "card_last_4.keyword".to_string(), convert_to_value(card_last_4), ) .switch()?; } }; if let Some(payment_id) = filters.payment_id { if !payment_id.is_empty() { query_builder .add_filter_clause( "payment_id.keyword".to_string(), convert_to_value(payment_id), ) .switch()?; } }; if let Some(amount) = filters.amount { if !amount.is_empty() { query_builder .add_filter_clause("amount".to_string(), convert_to_value(amount)) .switch()?; } }; if let Some(customer_id) = filters.customer_id { if !customer_id.is_empty() { query_builder .add_filter_clause( "customer_id.keyword".to_string(), convert_to_value(customer_id), ) .switch()?; } }; }; if let Some(time_range) = req.time_range { query_builder.set_time_range(time_range.into()).switch()?; }; let response_text: OpenMsearchOutput = client .execute(query_builder) .await .change_context(OpenSearchError::ConnectionError)? .text() .await .change_context(OpenSearchError::ResponseError) .and_then(|body: String| { serde_json::from_str::<OpenMsearchOutput>(&body) .change_context(OpenSearchError::DeserialisationError) .attach_printable(body.clone()) })?; let response_body: OpenMsearchOutput = response_text; Ok(response_body .responses .into_iter() .zip(indexes) .map(|(index_hit, index)| match index_hit { OpensearchOutput::Success(success) => GetSearchResponse { count: success.hits.total.value, index, hits: success .hits .hits .into_iter() .map(|hit| hit.source) .collect(), status: SearchStatus::Success, }, OpensearchOutput::Error(error) => { tracing::error!( index = ?index, error_response = ?error, "Search error" ); GetSearchResponse { count: 0, index, hits: Vec::new(), status: SearchStatus::Failure, } } }) .collect()) } pub async fn search_results( client: &OpenSearchClient, req: GetSearchRequestWithIndex, search_params: Vec<AuthInfo>, ) -> CustomResult<GetSearchResponse, OpenSearchError> { let search_req = req.search_req; if search_req.query.trim().is_empty() && search_req .filters .as_ref() .is_none_or(|filters| filters.is_all_none()) { return Err(OpenSearchError::BadRequestError( "Both query and filters are empty".to_string(), ) .into()); } let mut query_builder = OpenSearchQueryBuilder::new( OpenSearchQuery::Search(req.index), search_req.query, search_params, ); if let Some(filters) = search_req.filters { if let Some(currency) = filters.currency { if !currency.is_empty() { query_builder .add_filter_clause("currency.keyword".to_string(), convert_to_value(currency)) .switch()?; } }; if let Some(status) = filters.status { if !status.is_empty() { query_builder .add_filter_clause("status.keyword".to_string(), convert_to_value(status)) .switch()?; } }; if let Some(payment_method) = filters.payment_method { if !payment_method.is_empty() { query_builder .add_filter_clause( "payment_method.keyword".to_string(), convert_to_value(payment_method), ) .switch()?; } }; if let Some(customer_email) = filters.customer_email { if !customer_email.is_empty() { query_builder .add_filter_clause( "customer_email.keyword".to_string(), convert_to_value( customer_email .iter() .filter_map(|email| { // TODO: Add trait based inputs instead of converting this to strings serde_json::to_value(email) .ok() .and_then(|a| a.as_str().map(|a| a.to_string())) }) .collect(), ), ) .switch()?; } }; if let Some(search_tags) = filters.search_tags { if !search_tags.is_empty() { query_builder .add_filter_clause( "feature_metadata.search_tags.keyword".to_string(), convert_to_value( search_tags .iter() .filter_map(|search_tag| { // TODO: Add trait based inputs instead of converting this to strings serde_json::to_value(search_tag) .ok() .and_then(|a| a.as_str().map(|a| a.to_string())) }) .collect(), ), ) .switch()?; } }; if let Some(connector) = filters.connector { if !connector.is_empty() { query_builder .add_filter_clause("connector.keyword".to_string(), convert_to_value(connector)) .switch()?; } }; if let Some(payment_method_type) = filters.payment_method_type { if !payment_method_type.is_empty() { query_builder .add_filter_clause( "payment_method_type.keyword".to_string(), convert_to_value(payment_method_type), ) .switch()?; } }; if let Some(card_network) = filters.card_network { if !card_network.is_empty() { query_builder .add_filter_clause( "card_network.keyword".to_string(), convert_to_value(card_network), ) .switch()?; } }; if let Some(card_last_4) = filters.card_last_4 { if !card_last_4.is_empty() { query_builder .add_filter_clause( "card_last_4.keyword".to_string(), convert_to_value(card_last_4), ) .switch()?; } }; if let Some(payment_id) = filters.payment_id { if !payment_id.is_empty() { query_builder .add_filter_clause( "payment_id.keyword".to_string(), convert_to_value(payment_id), ) .switch()?; } }; if let Some(amount) = filters.amount { if !amount.is_empty() { query_builder .add_filter_clause("amount".to_string(), convert_to_value(amount)) .switch()?; } }; if let Some(customer_id) = filters.customer_id { if !customer_id.is_empty() { query_builder .add_filter_clause( "customer_id.keyword".to_string(), convert_to_value(customer_id), ) .switch()?; } }; }; if let Some(time_range) = search_req.time_range { query_builder.set_time_range(time_range.into()).switch()?; }; query_builder .set_offset_n_count(search_req.offset, search_req.count) .switch()?; let response_text: OpensearchOutput = client .execute(query_builder) .await .change_context(OpenSearchError::ConnectionError)? .text() .await .change_context(OpenSearchError::ResponseError) .and_then(|body: String| { serde_json::from_str::<OpensearchOutput>(&body) .change_context(OpenSearchError::DeserialisationError) .attach_printable(body.clone()) })?; let response_body: OpensearchOutput = response_text; match response_body { OpensearchOutput::Success(success) => Ok(GetSearchResponse { count: success.hits.total.value, index: req.index, hits: success .hits .hits .into_iter() .map(|hit| hit.source) .collect(), status: SearchStatus::Success, }), OpensearchOutput::Error(error) => { tracing::error!( index = ?req.index, error_response = ?error, "Search error" ); Ok(GetSearchResponse { count: 0, index: req.index, hits: Vec::new(), status: SearchStatus::Failure, }) } } }
crates/analytics/src/search.rs
analytics
full_file
null
null
null
2,737
null
null
null
null
null
null
null
// Function: polymorphic_schema // File: crates/router_derive/src/lib.rs // Module: router_derive pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream
crates/router_derive/src/lib.rs
router_derive
function_signature
null
null
null
44
polymorphic_schema
null
null
null
null
null
null
// File: crates/common_utils/src/new_type.rs // Module: common_utils // Public structs: 9 //! Contains new types with restrictions use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{ consts::MAX_ALLOWED_MERCHANT_NAME_LENGTH, pii::{Email, UpiVpaMaskingStrategy}, transformers::ForeignFrom, }; #[nutype::nutype( derive(Clone, Serialize, Deserialize, Debug), validate(len_char_min = 1, len_char_max = MAX_ALLOWED_MERCHANT_NAME_LENGTH) )] pub struct MerchantName(String); impl masking::SerializableSecret for MerchantName {} /// Function for masking alphanumeric characters in a string. /// /// # Arguments /// `val` /// - holds reference to the string to be masked. /// `unmasked_char_count` /// - minimum character count to remain unmasked for identification /// - this number is for keeping the characters unmasked from /// both beginning (if feasible) and ending of the string. /// `min_masked_char_count` /// - this ensures the minimum number of characters to be masked /// /// # Behaviour /// - Returns the original string if its length is less than or equal to `unmasked_char_count`. /// - If the string length allows, keeps `unmasked_char_count` characters unmasked at both start and end. /// - Otherwise, keeps `unmasked_char_count` characters unmasked only at the end. /// - Only alphanumeric characters are masked; other characters remain unchanged. /// /// # Examples /// Sort Code /// (12-34-56, 2, 2) -> 12-**-56 /// Routing number /// (026009593, 3, 3) -> 026***593 /// CNPJ /// (12345678901, 4, 4) -> *******8901 /// CNPJ /// (12345678901, 4, 3) -> 1234***8901 /// Pix key /// (123e-a452-1243-1244-000, 4, 4) -> 123e-****-****-****-000 /// IBAN /// (AL35202111090000000001234567, 5, 5) -> AL352******************34567 fn apply_mask(val: &str, unmasked_char_count: usize, min_masked_char_count: usize) -> String { let len = val.len(); if len <= unmasked_char_count { return val.to_string(); } let mask_start_index = // For showing only last `unmasked_char_count` characters if len < (unmasked_char_count * 2 + min_masked_char_count) { 0 // For showing first and last `unmasked_char_count` characters } else { unmasked_char_count }; let mask_end_index = len - unmasked_char_count - 1; let range = mask_start_index..=mask_end_index; val.chars() .enumerate() .fold(String::new(), |mut acc, (index, ch)| { if ch.is_alphanumeric() && range.contains(&index) { acc.push('*'); } else { acc.push(ch); } acc }) } /// Masked sort code #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedSortCode(Secret<String>); impl From<String> for MaskedSortCode { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 2, 2); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedSortCode { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked Routing number #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedRoutingNumber(Secret<String>); impl From<String> for MaskedRoutingNumber { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 3, 3); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedRoutingNumber { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked bank account #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedBankAccount(Secret<String>); impl From<String> for MaskedBankAccount { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 4, 4); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedBankAccount { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked IBAN #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedIban(Secret<String>); impl From<String> for MaskedIban { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 5, 5); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedIban { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked IBAN #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedBic(Secret<String>); impl From<String> for MaskedBic { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 3, 2); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedBic { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked UPI ID #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedUpiVpaId(Secret<String>); impl From<String> for MaskedUpiVpaId { fn from(src: String) -> Self { let unmasked_char_count = 2; let masked_value = if let Some((user_identifier, bank_or_psp)) = src.split_once('@') { let masked_user_identifier = user_identifier .to_string() .chars() .take(unmasked_char_count) .collect::<String>() + &"*".repeat(user_identifier.len() - unmasked_char_count); format!("{masked_user_identifier}@{bank_or_psp}") } else { let masked_value = apply_mask(src.as_ref(), unmasked_char_count, 8); masked_value }; Self(Secret::from(masked_value)) } } impl From<Secret<String, UpiVpaMaskingStrategy>> for MaskedUpiVpaId { fn from(secret: Secret<String, UpiVpaMaskingStrategy>) -> Self { Self::from(secret.expose()) } } /// Masked Email #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedEmail(Secret<String>); impl From<String> for MaskedEmail { fn from(src: String) -> Self { let unmasked_char_count = 2; let masked_value = if let Some((user_identifier, domain)) = src.split_once('@') { let masked_user_identifier = user_identifier .to_string() .chars() .take(unmasked_char_count) .collect::<String>() + &"*".repeat(user_identifier.len() - unmasked_char_count); format!("{masked_user_identifier}@{domain}") } else { let masked_value = apply_mask(src.as_ref(), unmasked_char_count, 8); masked_value }; Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedEmail { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } impl ForeignFrom<Email> for MaskedEmail { fn foreign_from(email: Email) -> Self { let email_value: String = email.expose().peek().to_owned(); Self::from(email_value) } } /// Masked Phone Number #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedPhoneNumber(Secret<String>); impl From<String> for MaskedPhoneNumber { fn from(src: String) -> Self { let unmasked_char_count = 2; let masked_value = if unmasked_char_count <= src.len() { let len = src.len(); // mask every character except the last 2 "*".repeat(len - unmasked_char_count).to_string() + src .get(len.saturating_sub(unmasked_char_count)..) .unwrap_or("") } else { src }; Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedPhoneNumber { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } #[cfg(test)] mod apply_mask_fn_test { use masking::PeekInterface; use crate::new_type::{ apply_mask, MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId, }; #[test] fn test_masked_types() { let sort_code = MaskedSortCode::from("110011".to_string()); let routing_number = MaskedRoutingNumber::from("056008849".to_string()); let bank_account = MaskedBankAccount::from("12345678901234".to_string()); let iban = MaskedIban::from("NL02ABNA0123456789".to_string()); let upi_vpa = MaskedUpiVpaId::from("someusername@okhdfcbank".to_string()); // Standard masked data tests assert_eq!(sort_code.0.peek().to_owned(), "11**11".to_string()); assert_eq!(routing_number.0.peek().to_owned(), "056***849".to_string()); assert_eq!( bank_account.0.peek().to_owned(), "1234******1234".to_string() ); assert_eq!(iban.0.peek().to_owned(), "NL02A********56789".to_string()); assert_eq!( upi_vpa.0.peek().to_owned(), "so**********@okhdfcbank".to_string() ); } #[test] fn test_apply_mask_fn() { let value = "12345678901".to_string(); // Generic masked tests assert_eq!(apply_mask(&value, 2, 2), "12*******01".to_string()); assert_eq!(apply_mask(&value, 3, 2), "123*****901".to_string()); assert_eq!(apply_mask(&value, 3, 3), "123*****901".to_string()); assert_eq!(apply_mask(&value, 4, 3), "1234***8901".to_string()); assert_eq!(apply_mask(&value, 4, 4), "*******8901".to_string()); assert_eq!(apply_mask(&value, 5, 4), "******78901".to_string()); assert_eq!(apply_mask(&value, 5, 5), "******78901".to_string()); assert_eq!(apply_mask(&value, 6, 5), "*****678901".to_string()); assert_eq!(apply_mask(&value, 6, 6), "*****678901".to_string()); assert_eq!(apply_mask(&value, 7, 6), "****5678901".to_string()); assert_eq!(apply_mask(&value, 7, 7), "****5678901".to_string()); assert_eq!(apply_mask(&value, 8, 7), "***45678901".to_string()); assert_eq!(apply_mask(&value, 8, 8), "***45678901".to_string()); } }
crates/common_utils/src/new_type.rs
common_utils
full_file
null
null
null
2,822
null
null
null
null
null
null
null
// Function: apply // File: crates/api_models/src/payment_methods.rs // Module: api_models pub fn apply(&self, card_data_from_locker: Card) -> CardDetail
crates/api_models/src/payment_methods.rs
api_models
function_signature
null
null
null
39
apply
null
null
null
null
null
null
// Struct: EventBuilder // File: crates/events/src/lib.rs // Module: events // Implementations: 1 pub struct EventBuilder<T, A, E, D>
crates/events/src/lib.rs
events
struct_definition
EventBuilder
1
[]
39
null
null
null
null
null
null
null
// File: crates/router/src/core/connector_validation.rs // Module: router // Public functions: 1 // Public structs: 1 use api_models::enums as api_enums; use common_utils::pii; use error_stack::ResultExt; use external_services::http_client::client; use masking::PeekInterface; use pm_auth::connector::plaid::transformers::PlaidAuthType; use crate::{core::errors, types, types::transformers::ForeignTryFrom}; pub struct ConnectorAuthTypeAndMetadataValidation<'a> { pub connector_name: &'a api_models::enums::Connector, pub auth_type: &'a types::ConnectorAuthType, pub connector_meta_data: &'a Option<pii::SecretSerdeValue>, } impl ConnectorAuthTypeAndMetadataValidation<'_> { pub fn validate_auth_and_metadata_type( &self, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { let connector_auth_type_validation = ConnectorAuthTypeValidation { auth_type: self.auth_type, }; connector_auth_type_validation.validate_connector_auth_type()?; self.validate_auth_and_metadata_type_with_connector() .map_err(|err| match *err.current_context() { errors::ConnectorError::InvalidConnectorName => { err.change_context(errors::ApiErrorResponse::InvalidRequestData { message: "The connector name is invalid".to_string(), }) } errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err .change_context(errors::ApiErrorResponse::InvalidRequestData { message: format!("The {field_name} is invalid"), }), errors::ConnectorError::FailedToObtainAuthType => { err.change_context(errors::ApiErrorResponse::InvalidRequestData { message: "The auth type is invalid for the connector".to_string(), }) } _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData { message: "The request body is invalid".to_string(), }), }) } fn validate_auth_and_metadata_type_with_connector( &self, ) -> Result<(), error_stack::Report<errors::ConnectorError>> { use crate::connector::*; match self.connector_name { api_enums::Connector::Vgs => { vgs::transformers::VgsAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Adyenplatform => { adyenplatform::transformers::AdyenplatformAuthType::try_from(self.auth_type)?; Ok(()) } #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyBillingConnector | api_enums::Connector::DummyConnector1 | api_enums::Connector::DummyConnector2 | api_enums::Connector::DummyConnector3 | api_enums::Connector::DummyConnector4 | api_enums::Connector::DummyConnector5 | api_enums::Connector::DummyConnector6 | api_enums::Connector::DummyConnector7 => { hyperswitch_connectors::connectors::dummyconnector::transformers::DummyConnectorAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Aci => { aci::transformers::AciAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Adyen => { adyen::transformers::AdyenAuthType::try_from(self.auth_type)?; adyen::transformers::AdyenConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Affirm => { affirm::transformers::AffirmAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Airwallex => { airwallex::transformers::AirwallexAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Amazonpay => { amazonpay::transformers::AmazonpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Archipel => { archipel::transformers::ArchipelAuthType::try_from(self.auth_type)?; archipel::transformers::ArchipelConfigData::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Authipay => { authipay::transformers::AuthipayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Authorizedotnet => { authorizedotnet::transformers::AuthorizedotnetAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bankofamerica => { bankofamerica::transformers::BankOfAmericaAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Barclaycard => { barclaycard::transformers::BarclaycardAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Billwerk => { billwerk::transformers::BillwerkAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bitpay => { bitpay::transformers::BitpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bambora => { bambora::transformers::BamboraAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bamboraapac => { bamboraapac::transformers::BamboraapacAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Boku => { boku::transformers::BokuAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bluesnap => { bluesnap::transformers::BluesnapAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Blackhawknetwork => { blackhawknetwork::transformers::BlackhawknetworkAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bluecode => { bluecode::transformers::BluecodeAuthType::try_from(self.auth_type)?; bluecode::transformers::BluecodeMetadataObject::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Braintree => { braintree::transformers::BraintreeAuthType::try_from(self.auth_type)?; braintree::transformers::BraintreeMeta::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Breadpay => { breadpay::transformers::BreadpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Cardinal => Ok(()), api_enums::Connector::Cashtocode => { cashtocode::transformers::CashtocodeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Chargebee => { chargebee::transformers::ChargebeeAuthType::try_from(self.auth_type)?; chargebee::transformers::ChargebeeMetadata::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Celero => { celero::transformers::CeleroAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Checkbook => { checkbook::transformers::CheckbookAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Checkout => { checkout::transformers::CheckoutAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Coinbase => { coinbase::transformers::CoinbaseAuthType::try_from(self.auth_type)?; coinbase::transformers::CoinbaseConnectorMeta::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Coingate => { coingate::transformers::CoingateAuthType::try_from(self.auth_type)?; coingate::transformers::CoingateConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Cryptopay => { cryptopay::transformers::CryptopayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::CtpMastercard => Ok(()), api_enums::Connector::Custombilling => Ok(()), api_enums::Connector::CtpVisa => Ok(()), api_enums::Connector::Cybersource => { cybersource::transformers::CybersourceAuthType::try_from(self.auth_type)?; cybersource::transformers::CybersourceConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Datatrans => { datatrans::transformers::DatatransAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Deutschebank => { deutschebank::transformers::DeutschebankAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Digitalvirgo => { digitalvirgo::transformers::DigitalvirgoAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Dlocal => { dlocal::transformers::DlocalAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Dwolla => { dwolla::transformers::DwollaAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Ebanx => { ebanx::transformers::EbanxAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Elavon => { elavon::transformers::ElavonAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Facilitapay => { facilitapay::transformers::FacilitapayAuthType::try_from(self.auth_type)?; facilitapay::transformers::FacilitapayConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Fiserv => { fiserv::transformers::FiservAuthType::try_from(self.auth_type)?; fiserv::transformers::FiservSessionObject::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Fiservemea => { fiservemea::transformers::FiservemeaAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Fiuu => { fiuu::transformers::FiuuAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Flexiti => { flexiti::transformers::FlexitiAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Forte => { forte::transformers::ForteAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Getnet => { getnet::transformers::GetnetAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Gigadat => { gigadat::transformers::GigadatAuthType::try_from(self.auth_type)?; gigadat::transformers::GigadatConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Globalpay => { globalpay::transformers::GlobalpayAuthType::try_from(self.auth_type)?; globalpay::transformers::GlobalPayMeta::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Globepay => { globepay::transformers::GlobepayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Gocardless => { gocardless::transformers::GocardlessAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Gpayments => { gpayments::transformers::GpaymentsAuthType::try_from(self.auth_type)?; gpayments::transformers::GpaymentsMetaData::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Hipay => { hipay::transformers::HipayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Helcim => { helcim::transformers::HelcimAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::HyperswitchVault => { hyperswitch_vault::transformers::HyperswitchVaultAuthType::try_from( self.auth_type, )?; Ok(()) } api_enums::Connector::Iatapay => { iatapay::transformers::IatapayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Inespay => { inespay::transformers::InespayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Itaubank => { itaubank::transformers::ItaubankAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Jpmorgan => { jpmorgan::transformers::JpmorganAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Juspaythreedsserver => Ok(()), api_enums::Connector::Klarna => { klarna::transformers::KlarnaAuthType::try_from(self.auth_type)?; klarna::transformers::KlarnaConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Loonio => { loonio::transformers::LoonioAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Mifinity => { mifinity::transformers::MifinityAuthType::try_from(self.auth_type)?; mifinity::transformers::MifinityConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Mollie => { mollie::transformers::MollieAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Moneris => { moneris::transformers::MonerisAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Multisafepay => { multisafepay::transformers::MultisafepayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Netcetera => { netcetera::transformers::NetceteraAuthType::try_from(self.auth_type)?; netcetera::transformers::NetceteraMetaData::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Nexinets => { nexinets::transformers::NexinetsAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nexixpay => { nexixpay::transformers::NexixpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nmi => { nmi::transformers::NmiAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nomupay => { nomupay::transformers::NomupayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Noon => { noon::transformers::NoonAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nordea => { nordea::transformers::NordeaAuthType::try_from(self.auth_type)?; nordea::transformers::NordeaConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Novalnet => { novalnet::transformers::NovalnetAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nuvei => { nuvei::transformers::NuveiAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Opennode => { opennode::transformers::OpennodeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paybox => { paybox::transformers::PayboxAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Payload => { payload::transformers::PayloadAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Payme => { payme::transformers::PaymeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paypal => { paypal::transformers::PaypalAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paysafe => { paysafe::transformers::PaysafeAuthType::try_from(self.auth_type)?; paysafe::transformers::PaysafeConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Payone => { payone::transformers::PayoneAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paystack => { paystack::transformers::PaystackAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Payu => { payu::transformers::PayuAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Peachpayments => { peachpayments::transformers::PeachpaymentsAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Placetopay => { placetopay::transformers::PlacetopayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Powertranz => { powertranz::transformers::PowertranzAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Prophetpay => { prophetpay::transformers::ProphetpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Rapyd => { rapyd::transformers::RapydAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Razorpay => { razorpay::transformers::RazorpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Recurly => { recurly::transformers::RecurlyAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Redsys => { redsys::transformers::RedsysAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Santander => { santander::transformers::SantanderAuthType::try_from(self.auth_type)?; santander::transformers::SantanderMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Shift4 => { shift4::transformers::Shift4AuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Silverflow => { silverflow::transformers::SilverflowAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Square => { square::transformers::SquareAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Stax => { stax::transformers::StaxAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Taxjar => { taxjar::transformers::TaxjarAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Stripe => { stripe::transformers::StripeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Stripebilling => { stripebilling::transformers::StripebillingAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Trustpay => { trustpay::transformers::TrustpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Trustpayments => { trustpayments::transformers::TrustpaymentsAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Tokenex => { tokenex::transformers::TokenexAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Tokenio => { tokenio::transformers::TokenioAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Tsys => { tsys::transformers::TsysAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Volt => { volt::transformers::VoltAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Wellsfargo => { wellsfargo::transformers::WellsfargoAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Wise => { wise::transformers::WiseAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Worldline => { worldline::transformers::WorldlineAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Worldpay => { worldpay::transformers::WorldpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Worldpayvantiv => { worldpayvantiv::transformers::WorldpayvantivAuthType::try_from(self.auth_type)?; worldpayvantiv::transformers::WorldpayvantivMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Worldpayxml => { worldpayxml::transformers::WorldpayxmlAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Xendit => { xendit::transformers::XenditAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Zen => { zen::transformers::ZenAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Zsl => { zsl::transformers::ZslAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Signifyd => { signifyd::transformers::SignifydAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Riskified => { riskified::transformers::RiskifiedAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Plaid => { PlaidAuthType::foreign_try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Threedsecureio => { threedsecureio::transformers::ThreedsecureioAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Phonepe => { phonepe::transformers::PhonepeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paytm => { paytm::transformers::PaytmAuthType::try_from(self.auth_type)?; Ok(()) } } } } struct ConnectorAuthTypeValidation<'a> { auth_type: &'a types::ConnectorAuthType, } impl ConnectorAuthTypeValidation<'_> { fn validate_connector_auth_type( &self, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { let validate_non_empty_field = |field_value: &str, field_name: &str| { if field_value.trim().is_empty() { Err(errors::ApiErrorResponse::InvalidDataFormat { field_name: format!("connector_account_details.{field_name}"), expected_format: "a non empty String".to_string(), } .into()) } else { Ok(()) } }; match self.auth_type { hyperswitch_domain_models::router_data::ConnectorAuthType::TemporaryAuth => Ok(()), hyperswitch_domain_models::router_data::ConnectorAuthType::HeaderKey { api_key } => { validate_non_empty_field(api_key.peek(), "api_key") } hyperswitch_domain_models::router_data::ConnectorAuthType::BodyKey { api_key, key1, } => { validate_non_empty_field(api_key.peek(), "api_key")?; validate_non_empty_field(key1.peek(), "key1") } hyperswitch_domain_models::router_data::ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => { validate_non_empty_field(api_key.peek(), "api_key")?; validate_non_empty_field(key1.peek(), "key1")?; validate_non_empty_field(api_secret.peek(), "api_secret") } hyperswitch_domain_models::router_data::ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => { validate_non_empty_field(api_key.peek(), "api_key")?; validate_non_empty_field(key1.peek(), "key1")?; validate_non_empty_field(api_secret.peek(), "api_secret")?; validate_non_empty_field(key2.peek(), "key2") } hyperswitch_domain_models::router_data::ConnectorAuthType::CurrencyAuthKey { auth_key_map, } => { if auth_key_map.is_empty() { Err(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details.auth_key_map".to_string(), expected_format: "a non empty map".to_string(), } .into()) } else { Ok(()) } } hyperswitch_domain_models::router_data::ConnectorAuthType::CertificateAuth { certificate, private_key, } => { client::create_identity_from_certificate_and_key( certificate.to_owned(), private_key.to_owned(), ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details.certificate or connector_account_details.private_key" .to_string(), expected_format: "a valid base64 encoded string of PEM encoded Certificate and Private Key" .to_string(), })?; Ok(()) } hyperswitch_domain_models::router_data::ConnectorAuthType::NoKey => Ok(()), } } }
crates/router/src/core/connector_validation.rs
router
full_file
null
null
null
6,016
null
null
null
null
null
null
null
// Implementation: impl PaymentMethodsEnabled // File: crates/common_types/src/payment_methods.rs // Module: common_types // Methods: 2 total (2 public) impl PaymentMethodsEnabled
crates/common_types/src/payment_methods.rs
common_types
impl_block
null
null
null
39
null
PaymentMethodsEnabled
null
2
2
null
null
// Implementation: impl RefundSync for for Wellsfargo // File: crates/hyperswitch_connectors/src/connectors/wellsfargo.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl RefundSync for for Wellsfargo
crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
hyperswitch_connectors
impl_block
null
null
null
59
null
Wellsfargo
RefundSync for
0
0
null
null
// Struct: Restriction // File: crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct Restriction
crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs
hyperswitch_connectors
struct_definition
Restriction
0
[]
46
null
null
null
null
null
null
null
// File: crates/router_env/src/logger/types.rs // Module: router_env //! Types. use serde::Deserialize; use strum::{Display, EnumString}; pub use tracing::{ field::{Field, Visit}, Level, Value, }; /// Category and tag of log event. /// /// Don't hesitate to add your variant if it is missing here. #[derive(Debug, Default, Deserialize, Clone, Display, EnumString)] pub enum Tag { /// General. #[default] General, /// Redis: get. RedisGet, /// Redis: set. RedisSet, /// API: incoming web request. ApiIncomingRequest, /// API: outgoing web request. ApiOutgoingRequest, /// Data base: create. DbCreate, /// Data base: read. DbRead, /// Data base: updare. DbUpdate, /// Data base: delete. DbDelete, /// Begin Request BeginRequest, /// End Request EndRequest, /// Call initiated to connector. InitiatedToConnector, /// Event: general. Event, /// Compatibility Layer Request CompatibilityLayerRequest, } /// API Flow #[derive(Debug, Display, Clone, PartialEq, Eq)] pub enum Flow { /// Health check HealthCheck, /// Deep health Check DeepHealthCheck, /// Organization create flow OrganizationCreate, /// Organization retrieve flow OrganizationRetrieve, /// Organization update flow OrganizationUpdate, /// Merchants account create flow. MerchantsAccountCreate, /// Merchants account retrieve flow. MerchantsAccountRetrieve, /// Merchants account update flow. MerchantsAccountUpdate, /// Merchants account delete flow. MerchantsAccountDelete, /// Merchant Connectors create flow. MerchantConnectorsCreate, /// Merchant Connectors retrieve flow. MerchantConnectorsRetrieve, /// Merchant account list MerchantAccountList, /// Merchant Connectors update flow. MerchantConnectorsUpdate, /// Merchant Connectors delete flow. MerchantConnectorsDelete, /// Merchant Connectors list flow. MerchantConnectorsList, /// Merchant Transfer Keys MerchantTransferKey, /// ConfigKey create flow. ConfigKeyCreate, /// ConfigKey fetch flow. ConfigKeyFetch, /// Enable platform account flow. EnablePlatformAccount, /// ConfigKey Update flow. ConfigKeyUpdate, /// ConfigKey Delete flow. ConfigKeyDelete, /// Customers create flow. CustomersCreate, /// Customers retrieve flow. CustomersRetrieve, /// Customers update flow. CustomersUpdate, /// Customers delete flow. CustomersDelete, /// Customers get mandates flow. CustomersGetMandates, /// Create an Ephemeral Key. EphemeralKeyCreate, /// Delete an Ephemeral Key. EphemeralKeyDelete, /// Mandates retrieve flow. MandatesRetrieve, /// Mandates revoke flow. MandatesRevoke, /// Mandates list flow. MandatesList, /// Payment methods create flow. PaymentMethodsCreate, /// Payment methods migrate flow. PaymentMethodsMigrate, /// Payment methods batch update flow. PaymentMethodsBatchUpdate, /// Payment methods list flow. PaymentMethodsList, /// Payment method save flow PaymentMethodSave, /// Customer payment methods list flow. CustomerPaymentMethodsList, /// Payment methods token data get flow. GetPaymentMethodTokenData, /// List Customers for a merchant CustomersList, /// Retrieve countries and currencies for connector and payment method ListCountriesCurrencies, /// Payment method create collect link flow. PaymentMethodCollectLink, /// Payment methods retrieve flow. PaymentMethodsRetrieve, /// Payment methods update flow. PaymentMethodsUpdate, /// Payment methods delete flow. PaymentMethodsDelete, /// Default Payment method flow. DefaultPaymentMethodsSet, /// Payments create flow. PaymentsCreate, /// Payments Retrieve flow. PaymentsRetrieve, /// Payments Retrieve force sync flow. PaymentsRetrieveForceSync, /// Payments Retrieve using merchant reference id PaymentsRetrieveUsingMerchantReferenceId, /// Payments update flow. PaymentsUpdate, /// Payments confirm flow. PaymentsConfirm, /// Payments capture flow. PaymentsCapture, /// Payments cancel flow. PaymentsCancel, /// Payments cancel post capture flow. PaymentsCancelPostCapture, /// Payments approve flow. PaymentsApprove, /// Payments reject flow. PaymentsReject, /// Payments Session Token flow PaymentsSessionToken, /// Payments start flow. PaymentsStart, /// Payments list flow. PaymentsList, /// Payments filters flow PaymentsFilters, /// Payments aggregates flow PaymentsAggregate, /// Payments Create Intent flow PaymentsCreateIntent, /// Payments Get Intent flow PaymentsGetIntent, /// Payments Update Intent flow PaymentsUpdateIntent, /// Payments confirm intent flow PaymentsConfirmIntent, /// Payments create and confirm intent flow PaymentsCreateAndConfirmIntent, /// Payment attempt list flow PaymentAttemptsList, #[cfg(feature = "payouts")] /// Payouts create flow PayoutsCreate, #[cfg(feature = "payouts")] /// Payouts retrieve flow. PayoutsRetrieve, #[cfg(feature = "payouts")] /// Payouts update flow. PayoutsUpdate, /// Payouts confirm flow. PayoutsConfirm, #[cfg(feature = "payouts")] /// Payouts cancel flow. PayoutsCancel, #[cfg(feature = "payouts")] /// Payouts fulfill flow. PayoutsFulfill, #[cfg(feature = "payouts")] /// Payouts list flow. PayoutsList, #[cfg(feature = "payouts")] /// Payouts filter flow. PayoutsFilter, /// Payouts accounts flow. PayoutsAccounts, /// Payout link initiate flow PayoutLinkInitiate, /// Payments Redirect flow PaymentsRedirect, /// Payemnts Complete Authorize Flow PaymentsCompleteAuthorize, /// Refunds create flow. RefundsCreate, /// Refunds retrieve flow. RefundsRetrieve, /// Refunds retrieve force sync flow. RefundsRetrieveForceSync, /// Refunds update flow. RefundsUpdate, /// Refunds list flow. RefundsList, /// Refunds filters flow RefundsFilters, /// Refunds aggregates flow RefundsAggregate, // Retrieve forex flow. RetrieveForexFlow, /// Toggles recon service for a merchant. ReconMerchantUpdate, /// Recon token request flow. ReconTokenRequest, /// Initial request for recon service. ReconServiceRequest, /// Recon token verification flow ReconVerifyToken, /// Routing create flow, RoutingCreateConfig, /// Routing link config RoutingLinkConfig, /// Routing link config RoutingUnlinkConfig, /// Routing retrieve config RoutingRetrieveConfig, /// Routing retrieve active config RoutingRetrieveActiveConfig, /// Routing retrieve default config RoutingRetrieveDefaultConfig, /// Routing retrieve dictionary RoutingRetrieveDictionary, /// Rule migration for decision-engine DecisionEngineRuleMigration, /// Routing update config RoutingUpdateConfig, /// Routing update default config RoutingUpdateDefaultConfig, /// Routing delete config RoutingDeleteConfig, /// Subscription create flow, CreateSubscription, /// Subscription confirm flow, ConfirmSubscription, /// Create dynamic routing CreateDynamicRoutingConfig, /// Toggle dynamic routing ToggleDynamicRouting, /// Update dynamic routing config UpdateDynamicRoutingConfigs, /// Add record to blocklist AddToBlocklist, /// Delete record from blocklist DeleteFromBlocklist, /// List entries from blocklist ListBlocklist, /// Toggle blocklist for merchant ToggleBlocklistGuard, /// Incoming Webhook Receive IncomingWebhookReceive, /// Recovery incoming webhook receive RecoveryIncomingWebhookReceive, /// Validate payment method flow ValidatePaymentMethod, /// API Key create flow ApiKeyCreate, /// API Key retrieve flow ApiKeyRetrieve, /// API Key update flow ApiKeyUpdate, /// API Key revoke flow ApiKeyRevoke, /// API Key list flow ApiKeyList, /// Dispute Retrieve flow DisputesRetrieve, /// Dispute List flow DisputesList, /// Dispute Filters flow DisputesFilters, /// Cards Info flow CardsInfo, /// Create File flow CreateFile, /// Delete File flow DeleteFile, /// Retrieve File flow RetrieveFile, /// Dispute Evidence submission flow DisputesEvidenceSubmit, /// Create Config Key flow CreateConfigKey, /// Attach Dispute Evidence flow AttachDisputeEvidence, /// Delete Dispute Evidence flow DeleteDisputeEvidence, /// Disputes aggregate flow DisputesAggregate, /// Retrieve Dispute Evidence flow RetrieveDisputeEvidence, /// Invalidate cache flow CacheInvalidate, /// Payment Link Retrieve flow PaymentLinkRetrieve, /// payment Link Initiate flow PaymentLinkInitiate, /// payment Link Initiate flow PaymentSecureLinkInitiate, /// Payment Link List flow PaymentLinkList, /// Payment Link Status PaymentLinkStatus, /// Create a profile ProfileCreate, /// Update a profile ProfileUpdate, /// Retrieve a profile ProfileRetrieve, /// Delete a profile ProfileDelete, /// List all the profiles for a merchant ProfileList, /// Different verification flows Verification, /// Rust locker migration RustLockerMigration, /// Gsm Rule Creation flow GsmRuleCreate, /// Gsm Rule Retrieve flow GsmRuleRetrieve, /// Gsm Rule Update flow GsmRuleUpdate, /// Apple pay certificates migration ApplePayCertificatesMigration, /// Gsm Rule Delete flow GsmRuleDelete, /// Get data from embedded flow GetDataFromHyperswitchAiFlow, // List all chat interactions ListAllChatInteractions, /// User Sign Up UserSignUp, /// User Sign Up UserSignUpWithMerchantId, /// User Sign In UserSignIn, /// User transfer key UserTransferKey, /// User connect account UserConnectAccount, /// Upsert Decision Manager Config DecisionManagerUpsertConfig, /// Delete Decision Manager Config DecisionManagerDeleteConfig, /// Retrieve Decision Manager Config DecisionManagerRetrieveConfig, /// Manual payment fulfillment acknowledgement FrmFulfillment, /// Get connectors feature matrix FeatureMatrix, /// Change password flow ChangePassword, /// Signout flow Signout, /// Set Dashboard Metadata flow SetDashboardMetadata, /// Get Multiple Dashboard Metadata flow GetMultipleDashboardMetadata, /// Payment Connector Verify VerifyPaymentConnector, /// Internal user signup InternalUserSignup, /// Create tenant level user TenantUserCreate, /// Switch org SwitchOrg, /// Switch merchant v2 SwitchMerchantV2, /// Switch profile SwitchProfile, /// Get permission info GetAuthorizationInfo, /// Get Roles info GetRolesInfo, /// Get Parent Group Info GetParentGroupInfo, /// List roles v2 ListRolesV2, /// List invitable roles at entity level ListInvitableRolesAtEntityLevel, /// List updatable roles at entity level ListUpdatableRolesAtEntityLevel, /// Get role GetRole, /// Get parent info for role GetRoleV2, /// Get role from token GetRoleFromToken, /// Get resources and groups for role from token GetRoleFromTokenV2, /// Update user role UpdateUserRole, /// Create merchant account for user in a org UserMerchantAccountCreate, /// Create Platform CreatePlatformAccount, /// Create Org in a given tenancy UserOrgMerchantCreate, /// Generate Sample Data GenerateSampleData, /// Delete Sample Data DeleteSampleData, /// Get details of a user GetUserDetails, /// Get details of a user role in a merchant account GetUserRoleDetails, /// PaymentMethodAuth Link token create PmAuthLinkTokenCreate, /// PaymentMethodAuth Exchange token create PmAuthExchangeToken, /// Get reset password link ForgotPassword, /// Reset password using link ResetPassword, /// Force set or force change password RotatePassword, /// Invite multiple users InviteMultipleUser, /// Reinvite user ReInviteUser, /// Accept invite from email AcceptInviteFromEmail, /// Delete user role DeleteUserRole, /// Incremental Authorization flow PaymentsIncrementalAuthorization, /// Get action URL for connector onboarding GetActionUrl, /// Sync connector onboarding status SyncOnboardingStatus, /// Reset tracking id ResetTrackingId, /// Verify email Token VerifyEmail, /// Send verify email VerifyEmailRequest, /// Update user account details UpdateUserAccountDetails, /// Accept user invitation using entities AcceptInvitationsV2, /// Accept user invitation using entities before user login AcceptInvitationsPreAuth, /// Initiate external authentication for a payment PaymentsExternalAuthentication, /// Authorize the payment after external 3ds authentication PaymentsAuthorize, /// Create Role CreateRole, /// Create Role V2 CreateRoleV2, /// Update Role UpdateRole, /// User email flow start UserFromEmail, /// Begin TOTP TotpBegin, /// Reset TOTP TotpReset, /// Verify TOTP TotpVerify, /// Update TOTP secret TotpUpdate, /// Verify Access Code RecoveryCodeVerify, /// Generate or Regenerate recovery codes RecoveryCodesGenerate, /// Terminate two factor authentication TerminateTwoFactorAuth, /// Check 2FA status TwoFactorAuthStatus, /// Create user authentication method CreateUserAuthenticationMethod, /// Update user authentication method UpdateUserAuthenticationMethod, /// List user authentication methods ListUserAuthenticationMethods, /// Get sso auth url GetSsoAuthUrl, /// Signin with SSO SignInWithSso, /// Auth Select AuthSelect, /// List Orgs for user ListOrgForUser, /// List Merchants for user in org ListMerchantsForUserInOrg, /// List Profile for user in org and merchant ListProfileForUserInOrgAndMerchant, /// List Users in Org ListUsersInLineage, /// List invitations for user ListInvitationsForUser, /// Get theme using lineage GetThemeUsingLineage, /// Get theme using theme id GetThemeUsingThemeId, /// Upload file to theme storage UploadFileToThemeStorage, /// Create theme CreateTheme, /// Update theme UpdateTheme, /// Delete theme DeleteTheme, /// Create user theme CreateUserTheme, /// Update user theme UpdateUserTheme, /// Delete user theme DeleteUserTheme, /// Upload file to user theme storage UploadFileToUserThemeStorage, /// Get user theme using theme id GetUserThemeUsingThemeId, ///List All Themes In Lineage ListAllThemesInLineage, /// Get user theme using lineage GetUserThemeUsingLineage, /// List initial webhook delivery attempts WebhookEventInitialDeliveryAttemptList, /// List delivery attempts for a webhook event WebhookEventDeliveryAttemptList, /// Manually retry the delivery for a webhook event WebhookEventDeliveryRetry, /// Retrieve status of the Poll RetrievePollStatus, /// Toggles the extended card info feature in profile level ToggleExtendedCardInfo, /// Toggles the extended card info feature in profile level ToggleConnectorAgnosticMit, /// Get the extended card info associated to a payment_id GetExtendedCardInfo, /// Manually update the refund details like status, error code, error message etc. RefundsManualUpdate, /// Manually update the payment details like status, error code, error message etc. PaymentsManualUpdate, /// Dynamic Tax Calcultion SessionUpdateTaxCalculation, ProxyConfirmIntent, /// Payments post session tokens flow PaymentsPostSessionTokens, /// Payments Update Metadata PaymentsUpdateMetadata, /// Payments start redirection flow PaymentStartRedirection, /// Volume split on the routing type VolumeSplitOnRoutingType, /// Routing evaluate rule flow RoutingEvaluateRule, /// Relay flow Relay, /// Relay retrieve flow RelayRetrieve, /// Card tokenization flow TokenizeCard, /// Card tokenization using payment method flow TokenizeCardUsingPaymentMethodId, /// Cards batch tokenization flow TokenizeCardBatch, /// Incoming Relay Webhook Receive IncomingRelayWebhookReceive, /// Generate Hypersense Token HypersenseTokenRequest, /// Verify Hypersense Token HypersenseVerifyToken, /// Signout Hypersense Token HypersenseSignoutToken, /// Payment Method Session Create PaymentMethodSessionCreate, /// Payment Method Session Retrieve PaymentMethodSessionRetrieve, // Payment Method Session Update PaymentMethodSessionUpdate, /// Update a saved payment method using the payment methods session PaymentMethodSessionUpdateSavedPaymentMethod, /// Delete a saved payment method using the payment methods session PaymentMethodSessionDeleteSavedPaymentMethod, /// Confirm a payment method session with payment method data PaymentMethodSessionConfirm, /// Create Cards Info flow CardsInfoCreate, /// Update Cards Info flow CardsInfoUpdate, /// Cards Info migrate flow CardsInfoMigrate, ///Total payment method count for merchant TotalPaymentMethodCount, /// Process Tracker Revenue Recovery Workflow Retrieve RevenueRecoveryRetrieve, /// Process Tracker Revenue Recovery Workflow Resume RevenueRecoveryResume, /// Tokenization flow TokenizationCreate, /// Tokenization retrieve flow TokenizationRetrieve, /// Clone Connector flow CloneConnector, /// Authentication Create flow AuthenticationCreate, /// Authentication Eligibility flow AuthenticationEligibility, /// Authentication Sync flow AuthenticationSync, /// Authentication Sync Post Update flow AuthenticationSyncPostUpdate, /// Authentication Authenticate flow AuthenticationAuthenticate, ///Proxy Flow Proxy, /// Profile Acquirer Create flow ProfileAcquirerCreate, /// Profile Acquirer Update flow ProfileAcquirerUpdate, /// ThreeDs Decision Rule Execute flow ThreeDsDecisionRuleExecute, /// Incoming Network Token Webhook Receive IncomingNetworkTokenWebhookReceive, /// Decision Engine Decide Gateway Call DecisionEngineDecideGatewayCall, /// Decision Engine Gateway Feedback Call DecisionEngineGatewayFeedbackCall, /// Recovery payments create flow. RecoveryPaymentsCreate, /// Tokenization delete flow TokenizationDelete, /// Payment method data backfill flow RecoveryDataBackfill, /// Gift card balance check flow GiftCardBalanceCheck, } /// Trait for providing generic behaviour to flow metric pub trait FlowMetric: ToString + std::fmt::Debug + Clone {} impl FlowMetric for Flow {} /// Category of log event. #[derive(Debug)] pub enum Category { /// Redis: general. Redis, /// API: general. Api, /// Database: general. Store, /// Event: general. Event, /// General: general. General, }
crates/router_env/src/logger/types.rs
router_env
full_file
null
null
null
4,347
null
null
null
null
null
null
null
// Implementation: impl api::PaymentAuthorize for for Peachpayments // File: crates/hyperswitch_connectors/src/connectors/peachpayments.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentAuthorize for for Peachpayments
crates/hyperswitch_connectors/src/connectors/peachpayments.rs
hyperswitch_connectors
impl_block
null
null
null
59
null
Peachpayments
api::PaymentAuthorize for
0
0
null
null
// Function: is_payout_terminal_state // File: crates/router/src/core/payouts/helpers.rs // Module: router pub fn is_payout_terminal_state(status: api_enums::PayoutStatus) -> bool
crates/router/src/core/payouts/helpers.rs
router
function_signature
null
null
null
46
is_payout_terminal_state
null
null
null
null
null
null
// Function: new // File: crates/hyperswitch_connectors/src/connectors/bambora.rs // Module: hyperswitch_connectors pub fn new() -> &'static Self
crates/hyperswitch_connectors/src/connectors/bambora.rs
hyperswitch_connectors
function_signature
null
null
null
39
new
null
null
null
null
null
null
// Struct: PlaidErrorResponse // File: crates/hyperswitch_connectors/src/connectors/plaid/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PlaidErrorResponse
crates/hyperswitch_connectors/src/connectors/plaid/transformers.rs
hyperswitch_connectors
struct_definition
PlaidErrorResponse
0
[]
47
null
null
null
null
null
null
null
// Implementation: impl HealthCheckInterface for for Store // File: crates/drainer/src/health_check.rs // Module: drainer // Methods: 2 total (0 public) impl HealthCheckInterface for for Store
crates/drainer/src/health_check.rs
drainer
impl_block
null
null
null
46
null
Store
HealthCheckInterface for
2
0
null
null
// Struct: FiuuErrorResponse // File: crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct FiuuErrorResponse
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
hyperswitch_connectors
struct_definition
FiuuErrorResponse
0
[]
50
null
null
null
null
null
null
null
// Struct: PayloadErrorResponse // File: crates/hyperswitch_connectors/src/connectors/payload/responses.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PayloadErrorResponse
crates/hyperswitch_connectors/src/connectors/payload/responses.rs
hyperswitch_connectors
struct_definition
PayloadErrorResponse
0
[]
44
null
null
null
null
null
null
null
// Struct: GigadatTransactionStatusResponse // File: crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct GigadatTransactionStatusResponse
crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs
hyperswitch_connectors
struct_definition
GigadatTransactionStatusResponse
0
[]
55
null
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/elavon.rs // Module: hyperswitch_connectors // Public functions: 2 // Public structs: 1 pub mod transformers; use std::{collections::HashMap, str, sync::LazyLock}; use common_enums::{enums, CaptureMethod, PaymentMethod, PaymentMethodType}; use common_utils::{ errors::CustomResult, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::report; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use masking::{Secret, WithoutType}; use serde::Serialize; use transformers as elavon; use crate::{ constants::headers, types::ResponseRouterData, utils, utils::{is_mandate_supported, PaymentMethodDataType}, }; pub fn struct_to_xml<T: Serialize>( item: &T, ) -> Result<HashMap<String, Secret<String, WithoutType>>, errors::ConnectorError> { let xml_content = quick_xml::se::to_string_with_root("txn", &item).map_err(|e| { router_env::logger::error!("Error serializing Struct: {:?}", e); errors::ConnectorError::ResponseDeserializationFailed })?; let mut result = HashMap::new(); result.insert( "xmldata".to_string(), Secret::<_, WithoutType>::new(xml_content), ); Ok(result) } #[derive(Clone)] pub struct Elavon { amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Elavon { pub fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, } } } impl api::Payment for Elavon {} impl api::PaymentSession for Elavon {} impl api::ConnectorAccessToken for Elavon {} impl api::MandateSetup for Elavon {} impl api::PaymentAuthorize for Elavon {} impl api::PaymentSync for Elavon {} impl api::PaymentCapture for Elavon {} impl api::PaymentVoid for Elavon {} impl api::Refund for Elavon {} impl api::RefundExecute for Elavon {} impl api::RefundSync for Elavon {} impl api::PaymentToken for Elavon {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Elavon { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Elavon where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Elavon { fn id(&self) -> &'static str { "elavon" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/x-www-form-urlencoded" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.elavon.base_url.as_ref() } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Elavon {} impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Elavon {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Elavon {} impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Elavon { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}processxml.do", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = elavon::ElavonRouterData::from((amount, req)); let connector_req = elavon::ElavonPaymentsRequest::try_from(&connector_router_data)?; router_env::logger::info!(raw_connector_request=?connector_req); Ok(RequestContent::FormUrlEncoded(Box::new(struct_to_xml( &connector_req, )?))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: elavon::ElavonPaymentsResponse = utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Elavon { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}processxml.do", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = elavon::SyncRequest::try_from(req)?; router_env::logger::info!(raw_connector_request=?connector_req); Ok(RequestContent::FormUrlEncoded(Box::new(struct_to_xml( &connector_req, )?))) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .set_body(types::PaymentsSyncType::get_request_body( self, req, connectors, )?) .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: elavon::ElavonSyncResponse = utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Elavon { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}processxml.do", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, )?; let connector_router_data = elavon::ElavonRouterData::from((amount, req)); let connector_req = elavon::PaymentsCaptureRequest::try_from(&connector_router_data)?; router_env::logger::info!(raw_connector_request=?connector_req); Ok(RequestContent::FormUrlEncoded(Box::new(struct_to_xml( &connector_req, )?))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: elavon::ElavonPaymentsResponse = utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Elavon { fn build_request( &self, _req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("Cancel/Void flow".to_string()).into()) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Elavon { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}processxml.do", self.base_url(connectors))) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = elavon::ElavonRouterData::from((refund_amount, req)); let connector_req = elavon::ElavonRefundRequest::try_from(&connector_router_data)?; router_env::logger::info!(raw_connector_request=?connector_req); Ok(RequestContent::FormUrlEncoded(Box::new(struct_to_xml( &connector_req, )?))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: elavon::ElavonPaymentsResponse = utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Elavon { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}processxml.do", self.base_url(connectors))) } fn get_request_body( &self, req: &RefundSyncRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = elavon::SyncRequest::try_from(req)?; router_env::logger::info!(raw_connector_request=?connector_req); Ok(RequestContent::FormUrlEncoded(Box::new(struct_to_xml( &connector_req, )?))) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .set_body(types::RefundSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: elavon::ElavonSyncResponse = utils::deserialize_xml_to_struct(&res.response)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Elavon { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } impl ConnectorValidation for Elavon { fn validate_mandate_payment( &self, pm_type: Option<PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]); is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } static ELAVON_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ CaptureMethod::Automatic, CaptureMethod::Manual, CaptureMethod::SequentialAutomatic, ]; let supported_card_network = vec![ common_enums::CardNetwork::Visa, common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::JCB, common_enums::CardNetwork::DinersClub, common_enums::CardNetwork::UnionPay, common_enums::CardNetwork::Discover, common_enums::CardNetwork::CartesBancaires, common_enums::CardNetwork::Interac, ]; let mut elavon_supported_payment_methods = SupportedPaymentMethods::new(); elavon_supported_payment_methods.add( PaymentMethod::Card, PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::NotSupported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); elavon_supported_payment_methods.add( PaymentMethod::Card, PaymentMethodType::Debit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::NotSupported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); elavon_supported_payment_methods }); static ELAVON_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Elavon", description: "Elavon, a wholly owned subsidiary of U.S. Bank, has been a global leader in payment processing for more than 30 years.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Sandbox, }; static ELAVON_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Elavon { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&ELAVON_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*ELAVON_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&ELAVON_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/elavon.rs
hyperswitch_connectors
full_file
null
null
null
5,258
null
null
null
null
null
null
null
// Function: find_by_merchant_id // File: crates/diesel_models/src/query/api_keys.rs // Module: diesel_models pub fn find_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, limit: Option<i64>, offset: Option<i64>, ) -> StorageResult<Vec<Self>>
crates/diesel_models/src/query/api_keys.rs
diesel_models
function_signature
null
null
null
83
find_by_merchant_id
null
null
null
null
null
null
// Function: get_destination_url // File: crates/router/src/core/proxy/utils.rs // Module: router pub fn get_destination_url(&self) -> &str
crates/router/src/core/proxy/utils.rs
router
function_signature
null
null
null
35
get_destination_url
null
null
null
null
null
null