id
stringlengths
11
116
type
stringclasses
1 value
granularity
stringclasses
4 values
content
stringlengths
16
477k
metadata
dict
fn_clm_router_list_payment_methods_-3112188759941136735
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/cards pub async fn list_payment_methods( state: routes::SessionState, merchant_context: domain::MerchantContext, mut req: api::PaymentMethodListRequest, ) -> errors::RouterResponse<api::PaymentMethodListResponse> { let db = &*state.store; let pm_config_mapping = &state.conf.pm_filters; let key_manager_state = &(&state).into(); let payment_intent = if let Some(cs) = &req.client_secret { if cs.starts_with("pm_") { validate_payment_method_and_client_secret(&state, cs, db, &merchant_context).await?; None } else { helpers::verify_payment_intent_time_and_client_secret( &state, &merchant_context, req.client_secret.clone(), ) .await? } } else { None }; let shipping_address = payment_intent .as_ref() .async_map(|pi| async { helpers::get_address_by_id( &state, pi.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &pi.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await }) .await .transpose()? .flatten(); let billing_address = payment_intent .as_ref() .async_map(|pi| async { helpers::get_address_by_id( &state, pi.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &pi.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await }) .await .transpose()? .flatten(); let customer = payment_intent .as_ref() .async_and_then(|pi| async { pi.customer_id .as_ref() .async_and_then(|cust| async { db.find_customer_by_customer_id_merchant_id( key_manager_state, cust, &pi.merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) .ok() }) .await }) .await; let payment_attempt = payment_intent .as_ref() .async_map(|pi| async { db.find_payment_attempt_by_payment_id_merchant_id_attempt_id( &pi.payment_id, &pi.merchant_id, &pi.active_attempt.get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) }) .await .transpose()?; let setup_future_usage = payment_intent.as_ref().and_then(|pi| pi.setup_future_usage); let is_cit_transaction = payment_attempt .as_ref() .map(|pa| pa.mandate_details.is_some()) .unwrap_or(false) || setup_future_usage .map(|future_usage| future_usage == common_enums::FutureUsage::OffSession) .unwrap_or(false); let payment_type = payment_attempt.as_ref().map(|pa| { let amount = api::Amount::from(pa.net_amount.get_order_amount()); let mandate_type = if pa.mandate_id.is_some() { Some(api::MandateTransactionType::RecurringMandateTransaction) } else if is_cit_transaction { Some(api::MandateTransactionType::NewMandateTransaction) } else { None }; helpers::infer_payment_type(amount, mandate_type.as_ref()) }); let all_mcas = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( key_manager_state, merchant_context.get_merchant_account().get_id(), false, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let profile_id = payment_intent .as_ref() .and_then(|payment_intent| payment_intent.profile_id.as_ref()) .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Profile id not found".to_string(), })?; let business_profile = db .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; // filter out payment connectors based on profile_id let filtered_mcas = all_mcas .clone() .filter_based_on_profile_and_connector_type(profile_id, ConnectorType::PaymentProcessor); logger::debug!(mca_before_filtering=?filtered_mcas); let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![]; // Key creation for storing PM_FILTER_CGRAPH let key = { format!( "pm_filters_cgraph_{}_{}", merchant_context .get_merchant_account() .get_id() .get_string_repr(), profile_id.get_string_repr() ) }; if let Some(graph) = get_merchant_pm_filter_graph(&state, &key).await { // Derivation of PM_FILTER_CGRAPH from MokaCache successful for mca in &filtered_mcas { let payment_methods = match &mca.payment_methods_enabled { Some(pm) => pm, None => continue, }; filter_payment_methods( &graph, mca.get_id(), payment_methods, &mut req, &mut response, payment_intent.as_ref(), payment_attempt.as_ref(), billing_address.as_ref(), mca.connector_name.clone(), &state.conf, ) .await?; } } else { // No PM_FILTER_CGRAPH Cache present in MokaCache let mut builder = cgraph::ConstraintGraphBuilder::new(); for mca in &filtered_mcas { let domain_id = builder.make_domain( mca.get_id().get_string_repr().to_string(), mca.connector_name.as_str(), ); let Ok(domain_id) = domain_id else { logger::error!("Failed to construct domain for list payment methods"); return Err(errors::ApiErrorResponse::InternalServerError.into()); }; let payment_methods = match &mca.payment_methods_enabled { Some(pm) => pm, None => continue, }; if let Err(e) = make_pm_graph( &mut builder, domain_id, payment_methods, mca.connector_name.clone(), pm_config_mapping, &state.conf.mandates.supported_payment_methods, &state.conf.mandates.update_mandate_supported, ) { logger::error!( "Failed to construct constraint graph for list payment methods {e:?}" ); } } // Refreshing our CGraph cache let graph = refresh_pm_filters_cache(&state, &key, builder.build()).await; for mca in &filtered_mcas { let payment_methods = match &mca.payment_methods_enabled { Some(pm) => pm, None => continue, }; filter_payment_methods( &graph, mca.get_id().clone(), payment_methods, &mut req, &mut response, payment_intent.as_ref(), payment_attempt.as_ref(), billing_address.as_ref(), mca.connector_name.clone(), &state.conf, ) .await?; } } logger::info!( "The Payment Methods available after Constraint Graph filtering are {:?}", response ); let mut pmt_to_auth_connector: HashMap< enums::PaymentMethod, HashMap<enums::PaymentMethodType, String>, > = HashMap::new(); if let Some((payment_attempt, payment_intent)) = payment_attempt.as_ref().zip(payment_intent.as_ref()) { let routing_enabled_pms = &router_consts::ROUTING_ENABLED_PAYMENT_METHODS; let routing_enabled_pm_types = &router_consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES; let mut chosen = api::SessionConnectorDatas::new(Vec::new()); for intermediate in &response { if routing_enabled_pm_types.contains(&intermediate.payment_method_type) || routing_enabled_pms.contains(&intermediate.payment_method) { let connector_data = helpers::get_connector_data_with_token( &state, intermediate.connector.to_string(), None, intermediate.payment_method_type, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("invalid connector name received")?; chosen.push(api::SessionConnectorData { payment_method_sub_type: intermediate.payment_method_type, payment_method_type: intermediate.payment_method, connector: connector_data, business_sub_label: None, }); } } let sfr = SessionFlowRoutingInput { state: &state, country: billing_address.clone().and_then(|ad| ad.country), key_store: merchant_context.get_merchant_key_store(), merchant_account: merchant_context.get_merchant_account(), payment_attempt, payment_intent, chosen, }; let (result, routing_approach) = routing::perform_session_flow_routing( sfr, &business_profile, &enums::TransactionType::Payment, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error performing session flow routing")?; response.retain(|intermediate| { if !routing_enabled_pm_types.contains(&intermediate.payment_method_type) && !routing_enabled_pms.contains(&intermediate.payment_method) { return true; } if let Some(choice) = result.get(&intermediate.payment_method_type) { if let Some(first_routable_connector) = choice.first() { intermediate.connector == first_routable_connector .connector .connector_name .to_string() && first_routable_connector .connector .merchant_connector_id .as_ref() .map(|merchant_connector_id| { *merchant_connector_id.get_string_repr() == intermediate.merchant_connector_id }) .unwrap_or_default() } else { false } } else { false } }); let mut routing_info: storage::PaymentRoutingInfo = payment_attempt .straight_through_algorithm .clone() .map(|val| val.parse_value("PaymentRoutingInfo")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid PaymentRoutingInfo format found in payment attempt")? .unwrap_or(storage::PaymentRoutingInfo { algorithm: None, pre_routing_results: None, }); let mut pre_routing_results: HashMap< api_enums::PaymentMethodType, storage::PreRoutingConnectorChoice, > = HashMap::new(); for (pm_type, routing_choice) in result { let mut routable_choice_list = vec![]; for choice in routing_choice { let routable_choice = routing_types::RoutableConnectorChoice { choice_kind: routing_types::RoutableChoiceKind::FullStruct, connector: choice .connector .connector_name .to_string() .parse::<api_enums::RoutableConnectors>() .change_context(errors::ApiErrorResponse::InternalServerError)?, merchant_connector_id: choice.connector.merchant_connector_id.clone(), }; routable_choice_list.push(routable_choice); } pre_routing_results.insert( pm_type, storage::PreRoutingConnectorChoice::Multiple(routable_choice_list), ); } let redis_conn = db .get_redis_conn() .map_err(|redis_error| logger::error!(?redis_error)) .ok(); let mut val = Vec::new(); for (payment_method_type, routable_connector_choice) in &pre_routing_results { let routable_connector_list = match routable_connector_choice { storage::PreRoutingConnectorChoice::Single(routable_connector) => { vec![routable_connector.clone()] } storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { routable_connector_list.clone() } }; let first_routable_connector = routable_connector_list .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; let matched_mca = filtered_mcas.iter().find(|m| { first_routable_connector.merchant_connector_id.as_ref() == Some(&m.get_id()) }); if let Some(m) = matched_mca { let pm_auth_config = m .pm_auth_config .as_ref() .map(|config| { serde_json::from_value::<PaymentMethodAuthConfig>(config.clone().expose()) .change_context(errors::StorageError::DeserializationFailed) .attach_printable("Failed to deserialize Payment Method Auth config") }) .transpose() .unwrap_or_else(|error| { logger::error!(?error); None }); if let Some(config) = pm_auth_config { for inner_config in config.enabled_payment_methods.iter() { let is_active_mca = all_mcas .iter() .any(|mca| mca.get_id() == inner_config.mca_id); if inner_config.payment_method_type == *payment_method_type && is_active_mca { let pm = pmt_to_auth_connector .get(&inner_config.payment_method) .cloned(); let inner_map = if let Some(mut inner_map) = pm { inner_map.insert( *payment_method_type, inner_config.connector_name.clone(), ); inner_map } else { HashMap::from([( *payment_method_type, inner_config.connector_name.clone(), )]) }; pmt_to_auth_connector.insert(inner_config.payment_method, inner_map); val.push(inner_config.clone()); } } }; } } let pm_auth_key = payment_intent.payment_id.get_pm_auth_key(); let redis_expiry = state.conf.payment_method_auth.get_inner().redis_expiry; if let Some(rc) = redis_conn { rc.serialize_and_set_key_with_expiry(&pm_auth_key.as_str().into(), val, redis_expiry) .await .attach_printable("Failed to store pm auth data in redis") .unwrap_or_else(|error| { logger::error!(?error); }) }; routing_info.pre_routing_results = Some(pre_routing_results); let encoded = routing_info .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize payment routing info to value")?; let attempt_update = storage::PaymentAttemptUpdate::UpdateTrackers { payment_token: None, connector: None, straight_through_algorithm: Some(encoded), amount_capturable: None, updated_by: merchant_context .get_merchant_account() .storage_scheme .to_string(), merchant_connector_id: None, surcharge_amount: None, tax_amount: None, routing_approach, is_stored_credential: None, }; state .store .update_payment_attempt_with_attempt_id( payment_attempt.clone(), attempt_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; } // Check for `use_billing_as_payment_method_billing` config under business_profile // If this is disabled, then the billing details in required fields will be empty and have to be collected by the customer let billing_address_for_calculating_required_fields = business_profile .use_billing_as_payment_method_billing .unwrap_or(true) .then_some(billing_address.as_ref()) .flatten(); let req = api_models::payments::PaymentsRequest::foreign_try_from(( payment_attempt.as_ref(), payment_intent.as_ref(), shipping_address.as_ref(), billing_address_for_calculating_required_fields, customer.as_ref(), ))?; let req_val = serde_json::to_value(req).ok(); logger::debug!(filtered_payment_methods=?response); let mut payment_experiences_consolidated_hm: HashMap< api_enums::PaymentMethod, HashMap<api_enums::PaymentMethodType, HashMap<api_enums::PaymentExperience, Vec<String>>>, > = HashMap::new(); let mut card_networks_consolidated_hm: HashMap< api_enums::PaymentMethod, HashMap<api_enums::PaymentMethodType, HashMap<api_enums::CardNetwork, Vec<String>>>, > = HashMap::new(); let mut banks_consolidated_hm: HashMap<api_enums::PaymentMethodType, Vec<String>> = HashMap::new(); let mut bank_debits_consolidated_hm = HashMap::<api_enums::PaymentMethodType, Vec<String>>::new(); let mut bank_transfer_consolidated_hm = HashMap::<api_enums::PaymentMethodType, Vec<String>>::new(); // All the required fields will be stored here and later filtered out based on business profile config let mut required_fields_hm = HashMap::< api_enums::PaymentMethod, HashMap<api_enums::PaymentMethodType, HashMap<String, RequiredFieldInfo>>, >::new(); for element in response.clone() { let payment_method = element.payment_method; let payment_method_type = element.payment_method_type; let connector = element.connector.clone(); let connector_variant = api_enums::Connector::from_str(connector.as_str()) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| format!("unable to parse connector name {connector:?}"))?; state.conf.required_fields.0.get(&payment_method).map( |required_fields_hm_for_each_payment_method_type| { required_fields_hm_for_each_payment_method_type .0 .get(&payment_method_type) .map(|required_fields_hm_for_each_connector| { required_fields_hm.entry(payment_method).or_default(); required_fields_hm_for_each_connector .fields .get(&connector_variant) .map(|required_fields_final| { let mut required_fields_hs = required_fields_final.common.clone(); if is_cit_transaction { required_fields_hs .extend(required_fields_final.mandate.clone()); } else { required_fields_hs .extend(required_fields_final.non_mandate.clone()); } required_fields_hs = should_collect_shipping_or_billing_details_from_wallet_connector( payment_method, element.payment_experience.as_ref(), &business_profile, required_fields_hs.clone(), ); // get the config, check the enums while adding { for (key, val) in &mut required_fields_hs { let temp = req_val .as_ref() .and_then(|r| get_val(key.to_owned(), r)); if let Some(s) = temp { val.value = Some(s.into()) }; } } let existing_req_fields_hs = required_fields_hm .get_mut(&payment_method) .and_then(|inner_hm| inner_hm.get_mut(&payment_method_type)); // If payment_method_type already exist in required_fields_hm, extend the required_fields hs to existing hs. if let Some(inner_hs) = existing_req_fields_hs { inner_hs.extend(required_fields_hs); } else { required_fields_hm.get_mut(&payment_method).map(|inner_hm| { inner_hm.insert(payment_method_type, required_fields_hs) }); } }) }) }, ); if let Some(payment_experience) = element.payment_experience { if let Some(payment_method_hm) = payment_experiences_consolidated_hm.get_mut(&payment_method) { if let Some(payment_method_type_hm) = payment_method_hm.get_mut(&payment_method_type) { if let Some(vector_of_connectors) = payment_method_type_hm.get_mut(&payment_experience) { vector_of_connectors.push(connector); } else { payment_method_type_hm.insert(payment_experience, vec![connector]); } } else { payment_method_hm.insert( payment_method_type, HashMap::from([(payment_experience, vec![connector])]), ); } } else { let inner_hm = HashMap::from([(payment_experience, vec![connector])]); let payment_method_type_hm = HashMap::from([(payment_method_type, inner_hm)]); payment_experiences_consolidated_hm.insert(payment_method, payment_method_type_hm); } } if let Some(card_networks) = element.card_networks { if let Some(payment_method_hm) = card_networks_consolidated_hm.get_mut(&payment_method) { if let Some(payment_method_type_hm) = payment_method_hm.get_mut(&payment_method_type) { for card_network in card_networks { if let Some(vector_of_connectors) = payment_method_type_hm.get_mut(&card_network) { let connector = element.connector.clone(); vector_of_connectors.push(connector); } else { let connector = element.connector.clone(); payment_method_type_hm.insert(card_network, vec![connector]); } } } else { let mut inner_hashmap: HashMap<api_enums::CardNetwork, Vec<String>> = HashMap::new(); for card_network in card_networks { if let Some(vector_of_connectors) = inner_hashmap.get_mut(&card_network) { let connector = element.connector.clone(); vector_of_connectors.push(connector); } else { let connector = element.connector.clone(); inner_hashmap.insert(card_network, vec![connector]); } } payment_method_hm.insert(payment_method_type, inner_hashmap); } } else { let mut inner_hashmap: HashMap<api_enums::CardNetwork, Vec<String>> = HashMap::new(); for card_network in card_networks { if let Some(vector_of_connectors) = inner_hashmap.get_mut(&card_network) { let connector = element.connector.clone(); vector_of_connectors.push(connector); } else { let connector = element.connector.clone(); inner_hashmap.insert(card_network, vec![connector]); } } let payment_method_type_hm = HashMap::from([(payment_method_type, inner_hashmap)]); card_networks_consolidated_hm.insert(payment_method, payment_method_type_hm); } } if element.payment_method == api_enums::PaymentMethod::BankRedirect { let connector = element.connector.clone(); if let Some(vector_of_connectors) = banks_consolidated_hm.get_mut(&element.payment_method_type) { vector_of_connectors.push(connector); } else { banks_consolidated_hm.insert(element.payment_method_type, vec![connector]); } } if element.payment_method == api_enums::PaymentMethod::BankDebit { let connector = element.connector.clone(); if let Some(vector_of_connectors) = bank_debits_consolidated_hm.get_mut(&element.payment_method_type) { vector_of_connectors.push(connector); } else { bank_debits_consolidated_hm.insert(element.payment_method_type, vec![connector]); } } if element.payment_method == api_enums::PaymentMethod::BankTransfer { let connector = element.connector.clone(); if let Some(vector_of_connectors) = bank_transfer_consolidated_hm.get_mut(&element.payment_method_type) { vector_of_connectors.push(connector); } else { bank_transfer_consolidated_hm.insert(element.payment_method_type, vec![connector]); } } } let mut payment_method_responses: Vec<ResponsePaymentMethodsEnabled> = vec![]; for key in payment_experiences_consolidated_hm.iter() { let mut payment_method_types = vec![]; for payment_method_types_hm in key.1 { let mut payment_experience_types = vec![]; for payment_experience_type in payment_method_types_hm.1 { payment_experience_types.push(PaymentExperienceTypes { payment_experience_type: *payment_experience_type.0, eligible_connectors: payment_experience_type.1.clone(), }) } payment_method_types.push(ResponsePaymentMethodTypes { payment_method_type: *payment_method_types_hm.0, payment_experience: Some(payment_experience_types), card_networks: None, bank_names: None, bank_debits: None, bank_transfers: None, // Required fields for PayLater payment method required_fields: required_fields_hm .get(key.0) .and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0)) .cloned(), surcharge_details: None, pm_auth_connector: pmt_to_auth_connector .get(key.0) .and_then(|pm_map| pm_map.get(payment_method_types_hm.0)) .cloned(), }) } payment_method_responses.push(ResponsePaymentMethodsEnabled { payment_method: *key.0, payment_method_types, }) } for key in card_networks_consolidated_hm.iter() { let mut payment_method_types = vec![]; for payment_method_types_hm in key.1 { let mut card_network_types = vec![]; for card_network_type in payment_method_types_hm.1 { card_network_types.push(CardNetworkTypes { card_network: card_network_type.0.clone(), eligible_connectors: card_network_type.1.clone(), surcharge_details: None, }) } payment_method_types.push(ResponsePaymentMethodTypes { payment_method_type: *payment_method_types_hm.0, card_networks: Some(card_network_types), payment_experience: None, bank_names: None, bank_debits: None, bank_transfers: None, // Required fields for Card payment method required_fields: required_fields_hm .get(key.0) .and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0)) .cloned(), surcharge_details: None, pm_auth_connector: pmt_to_auth_connector .get(key.0) .and_then(|pm_map| pm_map.get(payment_method_types_hm.0)) .cloned(), }) } payment_method_responses.push(ResponsePaymentMethodsEnabled { payment_method: *key.0, payment_method_types, }) } let mut bank_redirect_payment_method_types = vec![]; for key in banks_consolidated_hm.iter() { let payment_method_type = *key.0; let connectors = key.1.clone(); let bank_names = get_banks(&state, payment_method_type, connectors)?; bank_redirect_payment_method_types.push({ ResponsePaymentMethodTypes { payment_method_type, bank_names: Some(bank_names), payment_experience: None, card_networks: None, bank_debits: None, bank_transfers: None, // Required fields for BankRedirect payment method required_fields: required_fields_hm .get(&api_enums::PaymentMethod::BankRedirect) .and_then(|inner_hm| inner_hm.get(key.0)) .cloned(), surcharge_details: None, pm_auth_connector: pmt_to_auth_connector .get(&enums::PaymentMethod::BankRedirect) .and_then(|pm_map| pm_map.get(key.0)) .cloned(), } }) } if !bank_redirect_payment_method_types.is_empty() { payment_method_responses.push(ResponsePaymentMethodsEnabled { payment_method: api_enums::PaymentMethod::BankRedirect, payment_method_types: bank_redirect_payment_method_types, }); } let mut bank_debit_payment_method_types = vec![]; for key in bank_debits_consolidated_hm.iter() { let payment_method_type = *key.0; let connectors = key.1.clone(); bank_debit_payment_method_types.push({ ResponsePaymentMethodTypes { payment_method_type, bank_names: None, payment_experience: None, card_networks: None, bank_debits: Some(api_models::payment_methods::BankDebitTypes { eligible_connectors: connectors.clone(), }), bank_transfers: None, // Required fields for BankDebit payment method required_fields: required_fields_hm .get(&api_enums::PaymentMethod::BankDebit) .and_then(|inner_hm| inner_hm.get(key.0)) .cloned(), surcharge_details: None, pm_auth_connector: pmt_to_auth_connector .get(&enums::PaymentMethod::BankDebit) .and_then(|pm_map| pm_map.get(key.0)) .cloned(), } }) } if !bank_debit_payment_method_types.is_empty() { payment_method_responses.push(ResponsePaymentMethodsEnabled { payment_method: api_enums::PaymentMethod::BankDebit, payment_method_types: bank_debit_payment_method_types, }); } let mut bank_transfer_payment_method_types = vec![]; for key in bank_transfer_consolidated_hm.iter() { let payment_method_type = *key.0; let connectors = key.1.clone(); bank_transfer_payment_method_types.push({ ResponsePaymentMethodTypes { payment_method_type, bank_names: None, payment_experience: None, card_networks: None, bank_debits: None, bank_transfers: Some(api_models::payment_methods::BankTransferTypes { eligible_connectors: connectors, }), // Required fields for BankTransfer payment method required_fields: required_fields_hm .get(&api_enums::PaymentMethod::BankTransfer) .and_then(|inner_hm| inner_hm.get(key.0)) .cloned(), surcharge_details: None, pm_auth_connector: pmt_to_auth_connector .get(&enums::PaymentMethod::BankTransfer) .and_then(|pm_map| pm_map.get(key.0)) .cloned(), } }) } if !bank_transfer_payment_method_types.is_empty() { payment_method_responses.push(ResponsePaymentMethodsEnabled { payment_method: api_enums::PaymentMethod::BankTransfer, payment_method_types: bank_transfer_payment_method_types, }); } let currency = payment_intent.as_ref().and_then(|pi| pi.currency); let skip_external_tax_calculation = payment_intent .as_ref() .and_then(|intent| intent.skip_external_tax_calculation) .unwrap_or(false); let request_external_three_ds_authentication = payment_intent .as_ref() .and_then(|intent| intent.request_external_three_ds_authentication) .unwrap_or(false); let merchant_surcharge_configs = if let Some((payment_attempt, payment_intent)) = payment_attempt.as_ref().zip(payment_intent) { Box::pin(call_surcharge_decision_management( state, &merchant_context, &business_profile, payment_attempt, payment_intent, billing_address, &mut payment_method_responses, )) .await? } else { api_surcharge_decision_configs::MerchantSurchargeConfigs::default() }; let collect_shipping_details_from_wallets = if business_profile .always_collect_shipping_details_from_wallet_connector .unwrap_or(false) { business_profile.always_collect_shipping_details_from_wallet_connector } else { business_profile.collect_shipping_details_from_wallet_connector }; let collect_billing_details_from_wallets = if business_profile .always_collect_billing_details_from_wallet_connector .unwrap_or(false) { business_profile.always_collect_billing_details_from_wallet_connector } else { business_profile.collect_billing_details_from_wallet_connector }; let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled(); Ok(services::ApplicationResponse::Json( api::PaymentMethodListResponse { redirect_url: business_profile.return_url.clone(), merchant_name: merchant_context .get_merchant_account() .merchant_name .to_owned(), payment_type, payment_methods: payment_method_responses, mandate_payment: payment_attempt.and_then(|inner| inner.mandate_details).map( |d| match d { hyperswitch_domain_models::mandates::MandateDataType::SingleUse(i) => { api::MandateType::SingleUse(api::MandateAmountData { amount: i.amount, currency: i.currency, start_date: i.start_date, end_date: i.end_date, metadata: i.metadata, }) } hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(i)) => { api::MandateType::MultiUse(Some(api::MandateAmountData { amount: i.amount, currency: i.currency, start_date: i.start_date, end_date: i.end_date, metadata: i.metadata, })) } hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) => { api::MandateType::MultiUse(None) } }, ), show_surcharge_breakup_screen: merchant_surcharge_configs .show_surcharge_breakup_screen .unwrap_or_default(), currency, request_external_three_ds_authentication, collect_shipping_details_from_wallets, collect_billing_details_from_wallets, is_tax_calculation_enabled: is_tax_connector_enabled && !skip_external_tax_calculation, }, )) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 778, "total_crates": null }
fn_clm_router_list_customer_payment_method_-3112188759941136735
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/cards pub async fn list_customer_payment_method( state: &routes::SessionState, merchant_context: domain::MerchantContext, payment_intent: Option<storage::PaymentIntent>, customer_id: &id_type::CustomerId, limit: Option<i64>, ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { let db = &*state.store; let key_manager_state = &state.into(); let off_session_payment_flag = payment_intent .as_ref() .map(|pi| { matches!( pi.setup_future_usage, Some(common_enums::FutureUsage::OffSession) ) }) .unwrap_or(false); let customer = db .find_customer_by_customer_id_merchant_id( &state.into(), customer_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; let requires_cvv = configs::get_config_bool( state, router_consts::superposition::REQUIRES_CVV, // superposition key &merchant_context .get_merchant_account() .get_id() .get_requires_cvv_key(), // database key Some( external_services::superposition::ConfigContext::new().with( "merchant_id", merchant_context .get_merchant_account() .get_id() .get_string_repr(), ), ), // context true, // default value ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch requires_cvv config")?; let resp = db .find_payment_method_by_customer_id_merchant_id_status( &(state.into()), merchant_context.get_merchant_key_store(), customer_id, merchant_context.get_merchant_account().get_id(), common_enums::PaymentMethodStatus::Active, limit, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let mut customer_pms = Vec::new(); let profile_id = payment_intent .as_ref() .map(|payment_intent| { payment_intent .profile_id .clone() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent") }) .transpose()?; let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), profile_id.as_ref(), merchant_context.get_merchant_account().get_id(), ) .await?; let is_connector_agnostic_mit_enabled = business_profile .as_ref() .and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled) .unwrap_or(false); for pm in resp.into_iter() { let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token"); let payment_method = pm .get_payment_method_type() .get_required_value("payment_method")?; let pm_list_context = get_pm_list_context( state, &payment_method, merchant_context.get_merchant_key_store(), &pm, Some(parent_payment_method_token.clone()), true, false, &merchant_context, ) .await?; if pm_list_context.is_none() { continue; } let pm_list_context = pm_list_context.get_required_value("PaymentMethodListContext")?; // Retrieve the masked bank details to be sent as a response let bank_details = if payment_method == enums::PaymentMethod::BankDebit { get_masked_bank_details(&pm).await.unwrap_or_else(|error| { logger::error!(?error); None }) } else { None }; let payment_method_billing = pm .payment_method_billing_address .clone() .map(|decrypted_data| decrypted_data.into_inner().expose()) .map(|decrypted_value| decrypted_value.parse_value("payment method billing address")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to decrypt payment method billing address details")?; let connector_mandate_details = pm .get_common_mandate_reference() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize to Payment Mandate Reference ")?; let mca_enabled = get_mca_status( state, merchant_context.get_merchant_key_store(), profile_id.clone(), merchant_context.get_merchant_account().get_id(), is_connector_agnostic_mit_enabled, Some(connector_mandate_details), pm.network_transaction_id.as_ref(), ) .await?; let requires_cvv = if is_connector_agnostic_mit_enabled { requires_cvv && !(off_session_payment_flag && (pm.connector_mandate_details.is_some() || pm.network_transaction_id.is_some())) } else { requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some()) }; // Need validation for enabled payment method ,querying MCA let pma = api::CustomerPaymentMethod { payment_token: parent_payment_method_token.to_owned(), payment_method_id: pm.payment_method_id.clone(), customer_id: pm.customer_id.clone(), payment_method, payment_method_type: pm.get_payment_method_subtype(), payment_method_issuer: pm.payment_method_issuer, card: pm_list_context.card_details, metadata: pm.metadata, payment_method_issuer_code: pm.payment_method_issuer_code, recurring_enabled: mca_enabled, installment_payment_enabled: Some(false), payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), created: Some(pm.created_at), #[cfg(feature = "payouts")] bank_transfer: pm_list_context.bank_transfer_details, bank: bank_details, surcharge_details: None, requires_cvv, last_used_at: Some(pm.last_used_at), default_payment_method_set: customer.default_payment_method_id.is_some() && customer.default_payment_method_id == Some(pm.payment_method_id), billing: payment_method_billing, }; if requires_cvv || mca_enabled.unwrap_or(false) { customer_pms.push(pma.to_owned()); } let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let intent_fulfillment_time = business_profile .as_ref() .and_then(|b_profile| b_profile.get_order_fulfillment_time()) .unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME); let hyperswitch_token_data = pm_list_context .hyperswitch_token_data .get_required_value("PaymentTokenData")?; ParentPaymentMethodToken::create_key_for_token(( &parent_payment_method_token, pma.payment_method, )) .insert(intent_fulfillment_time, hyperswitch_token_data, state) .await?; if let Some(metadata) = pma.metadata { let pm_metadata_vec: payment_methods::PaymentMethodMetadata = metadata .parse_value("PaymentMethodMetadata") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to deserialize metadata to PaymentmethodMetadata struct", )?; for pm_metadata in pm_metadata_vec.payment_method_tokenization { let key = format!( "pm_token_{}_{}_{}", parent_payment_method_token, pma.payment_method, pm_metadata.0 ); redis_conn .set_key_with_expiry(&key.into(), pm_metadata.1, intent_fulfillment_time) .await .change_context(errors::StorageError::KVError) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add data in redis")?; } } } let mut response = api::CustomerPaymentMethodsListResponse { customer_payment_methods: customer_pms, is_guest_customer: payment_intent.as_ref().map(|_| false), //to return this key only when the request is tied to a payment intent }; Box::pin(perform_surcharge_ops( payment_intent, state, merchant_context, business_profile, &mut response, )) .await?; Ok(services::ApplicationResponse::Json(response)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 232, "total_crates": null }
fn_clm_router_filter_payment_methods_-3112188759941136735
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/cards pub async fn filter_payment_methods( graph: &cgraph::ConstraintGraph<dir::DirValue>, mca_id: id_type::MerchantConnectorAccountId, payment_methods: &[Secret<serde_json::Value>], req: &mut api::PaymentMethodListRequest, resp: &mut Vec<ResponsePaymentMethodIntermediate>, payment_intent: Option<&storage::PaymentIntent>, payment_attempt: Option<&storage::PaymentAttempt>, address: Option<&domain::Address>, connector: String, configs: &settings::Settings<RawSecret>, ) -> errors::CustomResult<(), errors::ApiErrorResponse> { for payment_method in payment_methods.iter() { let parse_result = serde_json::from_value::<PaymentMethodsEnabled>( payment_method.clone().expose().clone(), ); if let Ok(payment_methods_enabled) = parse_result { let payment_method = payment_methods_enabled.payment_method; let allowed_payment_method_types = payment_intent.and_then(|payment_intent| { payment_intent .allowed_payment_method_types .clone() .map(|val| val.parse_value("Vec<PaymentMethodType>")) .transpose() .unwrap_or_else(|error| { logger::error!( ?error, "Failed to deserialize PaymentIntent allowed_payment_method_types" ); None }) }); for payment_method_type_info in payment_methods_enabled .payment_method_types .unwrap_or_default() { if filter_recurring_based(&payment_method_type_info, req.recurring_enabled) && filter_installment_based( &payment_method_type_info, req.installment_payment_enabled, ) && filter_amount_based(&payment_method_type_info, req.amount) { let payment_method_object = payment_method_type_info.clone(); let pm_dir_value: dir::DirValue = (payment_method_type_info.payment_method_type, payment_method) .into_dir_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("pm_value_node not created")?; let connector_variant = api_enums::Connector::from_str(connector.as_str()) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| { format!("unable to parse connector name {connector:?}") })?; let mut context_values: Vec<dir::DirValue> = Vec::new(); context_values.push(pm_dir_value.clone()); payment_intent.map(|intent| { intent.currency.map(|currency| { context_values.push(dir::DirValue::PaymentCurrency(currency)) }) }); address.map(|address| { address.country.map(|country| { context_values.push(dir::DirValue::BillingCountry( common_enums::Country::from_alpha2(country), )) }) }); // Addition of Connector to context if let Ok(connector) = api_enums::RoutableConnectors::from_str( connector_variant.to_string().as_str(), ) { context_values.push(dir::DirValue::Connector(Box::new( api_models::routing::ast::ConnectorChoice { connector }, ))); }; let filter_pm_based_on_allowed_types = filter_pm_based_on_allowed_types( allowed_payment_method_types.as_ref(), payment_method_object.payment_method_type, ); // Filter logic for payment method types based on the below conditions // Case 1: If the payment method type support Zero Mandate flow, filter only payment method type that support it // Case 2: Whether the payment method type support Mandates or not, list all the payment method types if payment_attempt .and_then(|attempt| attempt.mandate_details.as_ref()) .is_some() || payment_intent .and_then(|intent| intent.setup_future_usage) .map(|future_usage| { future_usage == common_enums::FutureUsage::OffSession }) .unwrap_or(false) { payment_intent.map(|intent| intent.amount).map(|amount| { if amount == MinorUnit::zero() { if configs .zero_mandates .supported_payment_methods .0 .get(&payment_method) .and_then(|supported_pm_for_mandates| { supported_pm_for_mandates .0 .get(&payment_method_type_info.payment_method_type) .map(|supported_connector_for_mandates| { supported_connector_for_mandates .connector_list .contains(&connector_variant) }) }) .unwrap_or(false) { context_values.push(dir::DirValue::PaymentType( euclid::enums::PaymentType::SetupMandate, )); } } else if configs .mandates .supported_payment_methods .0 .get(&payment_method) .and_then(|supported_pm_for_mandates| { supported_pm_for_mandates .0 .get(&payment_method_type_info.payment_method_type) .map(|supported_connector_for_mandates| { supported_connector_for_mandates .connector_list .contains(&connector_variant) }) }) .unwrap_or(false) { context_values.push(dir::DirValue::PaymentType( euclid::enums::PaymentType::NewMandate, )); } else { context_values.push(dir::DirValue::PaymentType( euclid::enums::PaymentType::NonMandate, )); } }); } else { context_values.push(dir::DirValue::PaymentType( euclid::enums::PaymentType::NonMandate, )); } payment_attempt .and_then(|attempt| attempt.mandate_data.as_ref()) .map(|mandate_detail| { if mandate_detail.update_mandate_id.is_some() { context_values.push(dir::DirValue::PaymentType( euclid::enums::PaymentType::UpdateMandate, )); } }); payment_attempt .and_then(|inner| inner.capture_method) .map(|capture_method| { context_values.push(dir::DirValue::CaptureMethod(capture_method)); }); let filter_pm_card_network_based = filter_pm_card_network_based( payment_method_object.card_networks.as_ref(), req.card_networks.as_ref(), payment_method_object.payment_method_type, ); let saved_payment_methods_filter = req .client_secret .as_ref() .map(|cs| { if cs.starts_with("pm_") { configs .saved_payment_methods .sdk_eligible_payment_methods .contains(payment_method.to_string().as_str()) } else { true } }) .unwrap_or(true); let context = AnalysisContext::from_dir_values(context_values.clone()); logger::info!("Context created for List Payment method is {:?}", context); let domain_ident: &[String] = &[mca_id.clone().get_string_repr().to_string()]; let result = graph.key_value_analysis( pm_dir_value.clone(), &context, &mut cgraph::Memoization::new(), &mut cgraph::CycleCheck::new(), Some(domain_ident), ); if let Err(ref e) = result { logger::error!( "Error while performing Constraint graph's key value analysis for list payment methods {:?}", e ); } else if filter_pm_based_on_allowed_types && filter_pm_card_network_based && saved_payment_methods_filter && matches!(result, Ok(())) { let response_pm_type = ResponsePaymentMethodIntermediate::new( payment_method_object, connector.clone(), mca_id.get_string_repr().to_string(), payment_method, ); resp.push(response_pm_type); } else { logger::error!("Filtering Payment Methods Failed"); } } } } } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 231, "total_crates": null }
fn_clm_router_add_payment_method_-3112188759941136735
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/cards // Implementation of PmCards<'_> for PaymentMethodsController async fn add_payment_method( &self, req: &api::PaymentMethodCreate, ) -> errors::RouterResponse<api::PaymentMethodResponse> { req.validate()?; let db = &*self.state.store; let merchant_id = self.merchant_context.get_merchant_account().get_id(); let customer_id = req.customer_id.clone().get_required_value("customer_id")?; let payment_method = req.payment_method.get_required_value("payment_method")?; let key_manager_state = self.state.into(); let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() .async_map(|billing| { create_encrypted_data( &key_manager_state, self.merchant_context.get_merchant_key_store(), billing, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method billing address")?; let connector_mandate_details = req .connector_mandate_details .clone() .map(serde_json::to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError)?; let response = match payment_method { #[cfg(feature = "payouts")] api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() { Some(bank) => self .add_bank_to_locker( req.clone(), self.merchant_context.get_merchant_key_store(), &bank, &customer_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add PaymentMethod Failed"), _ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)), }, api_enums::PaymentMethod::Card => match req.card.clone() { Some(card) => { let mut card_details = card; card_details = helpers::populate_bin_details_for_payment_method_create( card_details.clone(), db.get_payment_methods_store(), ) .await; helpers::validate_card_expiry( &card_details.card_exp_month, &card_details.card_exp_year, )?; Box::pin(self.add_card_to_locker( req.clone(), &card_details, &customer_id, None, )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card Failed") } _ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)), }, _ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)), }; let (mut resp, duplication_check) = response?; match duplication_check { Some(duplication_check) => match duplication_check { payment_methods::DataDuplicationCheck::Duplicated => { let existing_pm = self .get_or_insert_payment_method( req.clone(), &mut resp, &customer_id, self.merchant_context.get_merchant_key_store(), ) .await?; resp.client_secret = existing_pm.client_secret; } payment_methods::DataDuplicationCheck::MetaDataChanged => { if let Some(card) = req.card.clone() { let existing_pm = self .get_or_insert_payment_method( req.clone(), &mut resp, &customer_id, self.merchant_context.get_merchant_key_store(), ) .await?; let client_secret = existing_pm.client_secret.clone(); self.delete_card_from_locker( &customer_id, merchant_id, existing_pm .locker_id .as_ref() .unwrap_or(&existing_pm.payment_method_id), ) .await?; let add_card_resp = self .add_card_hs( req.clone(), &card, &customer_id, api::enums::LockerChoice::HyperswitchCardVault, Some( existing_pm .locker_id .as_ref() .unwrap_or(&existing_pm.payment_method_id), ), ) .await; if let Err(err) = add_card_resp { logger::error!(vault_err=?err); db.delete_payment_method_by_merchant_id_payment_method_id( &(self.state.into()), self.merchant_context.get_merchant_key_store(), merchant_id, &resp.payment_method_id, ) .await .to_not_found_response( errors::ApiErrorResponse::PaymentMethodNotFound, )?; Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while updating card metadata changes"))? }; let existing_pm_data = self .get_card_details_without_locker_fallback(&existing_pm) .await?; let updated_card = Some(api::CardDetailFromLocker { scheme: existing_pm.scheme.clone(), last4_digits: Some(card.card_number.get_last4()), issuer_country: card .card_issuing_country .or(existing_pm_data.issuer_country), card_isin: Some(card.card_number.get_card_isin()), card_number: Some(card.card_number), expiry_month: Some(card.card_exp_month), expiry_year: Some(card.card_exp_year), card_token: None, card_fingerprint: None, card_holder_name: card .card_holder_name .or(existing_pm_data.card_holder_name), nick_name: card.nick_name.or(existing_pm_data.nick_name), card_network: card.card_network.or(existing_pm_data.card_network), card_issuer: card.card_issuer.or(existing_pm_data.card_issuer), card_type: card.card_type.or(existing_pm_data.card_type), saved_to_locker: true, }); let updated_pmd = updated_card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( card.clone(), None, ))) }); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd .async_map(|updated_pmd| { create_encrypted_data( &key_manager_state, self.merchant_context.get_merchant_key_store(), updated_pmd, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: pm_data_encrypted.map(Into::into), }; db.update_payment_method( &(self.state.into()), self.merchant_context.get_merchant_key_store(), existing_pm, pm_update, self.merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; resp.client_secret = client_secret; } } }, None => { let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card) || resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer) { Some(resp.payment_method_id) } else { None }; resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); let pm = self .insert_payment_method( &resp, req, self.merchant_context.get_merchant_key_store(), merchant_id, &customer_id, pm_metadata.cloned(), None, locker_id, connector_mandate_details, req.network_transaction_id.clone(), payment_method_billing_address, None, None, None, Default::default(), //Currently this method is used for adding payment method via PaymentMethodCreate API which doesn't support external vault. hence Default i.e. InternalVault is passed for vault source and type ) .await?; resp.client_secret = pm.client_secret; } } Ok(services::ApplicationResponse::Json(resp)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 204, "total_crates": null }
fn_clm_router_update_customer_payment_method_-3112188759941136735
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/cards pub async fn update_customer_payment_method( state: routes::SessionState, merchant_context: domain::MerchantContext, req: api::PaymentMethodUpdate, payment_method_id: &str, ) -> errors::RouterResponse<api::PaymentMethodResponse> { // Currently update is supported only for cards if let Some(card_update) = req.card.clone() { let db = state.store.as_ref(); let pm = db .find_payment_method( &((&state).into()), merchant_context.get_merchant_key_store(), payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; if let Some(cs) = &req.client_secret { let is_client_secret_expired = authenticate_pm_client_secret_and_check_expiry(cs, &pm)?; if is_client_secret_expired { return Err((errors::ApiErrorResponse::ClientSecretExpired).into()); }; }; if pm.status == enums::PaymentMethodStatus::AwaitingData { return Err(report!(errors::ApiErrorResponse::NotSupported { message: "Payment method is awaiting data so it cannot be updated".into() })); } if pm.payment_method_data.is_none() { return Err(report!(errors::ApiErrorResponse::GenericNotFoundError { message: "payment_method_data not found".to_string() })); } // Fetch the existing payment method data from db let existing_card_data = pm.payment_method_data .clone() .map(|x| x.into_inner().expose()) .map( |value| -> Result< PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>, > { value .parse_value::<PaymentMethodsData>("PaymentMethodsData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize payment methods data") }, ) .transpose()? .and_then(|pmd| match pmd { PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), _ => None, }) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to obtain decrypted card object from db")?; let is_card_updation_required = validate_payment_method_update(card_update.clone(), existing_card_data.clone()); let response = if is_card_updation_required { // Fetch the existing card data from locker for getting card number let card_data_from_locker = get_card_from_locker( &state, &pm.customer_id, &pm.merchant_id, pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await .attach_printable("Error getting card from locker")?; if card_update.card_exp_month.is_some() || card_update.card_exp_year.is_some() { helpers::validate_card_expiry( card_update .card_exp_month .as_ref() .unwrap_or(&card_data_from_locker.card_exp_month), card_update .card_exp_year .as_ref() .unwrap_or(&card_data_from_locker.card_exp_year), )?; } let updated_card_details = card_update.apply(card_data_from_locker.clone()); // Construct new payment method object from request let new_pm = api::PaymentMethodCreate { payment_method: pm.get_payment_method_type(), payment_method_type: pm.get_payment_method_subtype(), payment_method_issuer: pm.payment_method_issuer.clone(), payment_method_issuer_code: pm.payment_method_issuer_code, #[cfg(feature = "payouts")] bank_transfer: None, card: Some(updated_card_details.clone()), #[cfg(feature = "payouts")] wallet: None, metadata: None, customer_id: Some(pm.customer_id.clone()), client_secret: pm.client_secret.clone(), payment_method_data: None, card_network: None, billing: None, connector_mandate_details: None, network_transaction_id: None, }; new_pm.validate()?; let cards = PmCards { state: &state, merchant_context: &merchant_context, }; // Delete old payment method from locker cards .delete_card_from_locker( &pm.customer_id, &pm.merchant_id, pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await?; // Add the updated payment method data to locker let (mut add_card_resp, _) = Box::pin(cards.add_card_to_locker( new_pm.clone(), &updated_card_details, &pm.customer_id, Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)), )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add updated payment method to locker")?; // Construct new updated card object. Consider a field if passed in request or else populate it with the existing value from existing_card_data let updated_card = Some(api::CardDetailFromLocker { scheme: existing_card_data.scheme, last4_digits: Some(card_data_from_locker.card_number.get_last4()), issuer_country: existing_card_data.issuer_country, card_number: existing_card_data.card_number, expiry_month: card_update .card_exp_month .or(existing_card_data.expiry_month), expiry_year: card_update.card_exp_year.or(existing_card_data.expiry_year), card_token: existing_card_data.card_token, card_fingerprint: existing_card_data.card_fingerprint, card_holder_name: card_update .card_holder_name .or(existing_card_data.card_holder_name), nick_name: card_update.nick_name.or(existing_card_data.nick_name), card_network: existing_card_data.card_network, card_isin: existing_card_data.card_isin, card_issuer: existing_card_data.card_issuer, card_type: existing_card_data.card_type, saved_to_locker: true, }); let updated_pmd = updated_card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None))) }); let key_manager_state = (&state).into(); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd .async_map(|updated_pmd| { create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), updated_pmd, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: pm_data_encrypted.map(Into::into), }; add_card_resp .payment_method_id .clone_from(&pm.payment_method_id); db.update_payment_method( &((&state).into()), merchant_context.get_merchant_key_store(), pm, pm_update, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; add_card_resp } else { // Return existing payment method data as response without any changes api::PaymentMethodResponse { merchant_id: pm.merchant_id.to_owned(), customer_id: Some(pm.customer_id.clone()), payment_method_id: pm.payment_method_id.clone(), payment_method: pm.get_payment_method_type(), payment_method_type: pm.get_payment_method_subtype(), #[cfg(feature = "payouts")] bank_transfer: None, card: Some(existing_card_data), metadata: pm.metadata, created: Some(pm.created_at), recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), last_used_at: Some(common_utils::date_time::now()), client_secret: pm.client_secret.clone(), } }; Ok(services::ApplicationResponse::Json(response)) } else { Err(report!(errors::ApiErrorResponse::NotSupported { message: "Payment method update for the given payment method is not supported".into() })) } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 189, "total_crates": null }
fn_clm_router_try_from_-3311884311140864532
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/surcharge_decision_configs // Implementation of VirInterpreterBackendCacheWrapper for TryFrom<SurchargeDecisionManagerRecord> fn try_from(value: SurchargeDecisionManagerRecord) -> Result<Self, Self::Error> { let cached_algorithm = backend::VirInterpreterBackend::with_program(value.algorithm) .change_context(ConfigError::DslBackendInitError) .attach_printable("Error initializing DSL interpreter backend")?; let merchant_surcharge_configs = value.merchant_surcharge_configs; Ok(Self { cached_algorithm, merchant_surcharge_configs, }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2663, "total_crates": null }
fn_clm_router_perform_surcharge_decision_management_for_payment_method_list_-3311884311140864532
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/surcharge_decision_configs pub async fn perform_surcharge_decision_management_for_payment_method_list( state: &SessionState, algorithm_ref: routing::RoutingAlgorithmRef, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, billing_address: Option<hyperswitch_domain_models::address::Address>, response_payment_method_types: &mut [api_models::payment_methods::ResponsePaymentMethodsEnabled], ) -> ConditionalConfigResult<( types::SurchargeMetadata, surcharge_decision_configs::MerchantSurchargeConfigs, )> { let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone()); let (surcharge_source, merchant_surcharge_configs) = match ( payment_attempt.get_surcharge_details(), algorithm_ref.surcharge_config_algo_id, ) { (Some(request_surcharge_details), _) => ( SurchargeSource::Predetermined(request_surcharge_details), surcharge_decision_configs::MerchantSurchargeConfigs::default(), ), (None, Some(algorithm_id)) => { let cached_algo = ensure_algorithm_cached( &*state.store, &payment_attempt.merchant_id, algorithm_id.as_str(), ) .await?; let merchant_surcharge_config = cached_algo.merchant_surcharge_configs.clone(); ( SurchargeSource::Generate(cached_algo), merchant_surcharge_config, ) } (None, None) => { return Ok(( surcharge_metadata, surcharge_decision_configs::MerchantSurchargeConfigs::default(), )) } }; let surcharge_source_log_message = match &surcharge_source { SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules", SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request", }; logger::debug!(payment_method_list_surcharge_source = surcharge_source_log_message); let mut backend_input = make_dsl_input_for_surcharge(payment_attempt, payment_intent, billing_address) .change_context(ConfigError::InputConstructionError)?; for payment_methods_enabled in response_payment_method_types.iter_mut() { for payment_method_type_response in &mut payment_methods_enabled.payment_method_types.iter_mut() { let payment_method_type = payment_method_type_response.payment_method_type; backend_input.payment_method.payment_method_type = Some(payment_method_type); backend_input.payment_method.payment_method = Some(payment_methods_enabled.payment_method); if let Some(card_network_list) = &mut payment_method_type_response.card_networks { for card_network_type in card_network_list.iter_mut() { backend_input.payment_method.card_network = Some(card_network_type.card_network.clone()); let surcharge_details = surcharge_source .generate_surcharge_details_and_populate_surcharge_metadata( &backend_input, payment_attempt, ( &mut surcharge_metadata, types::SurchargeKey::PaymentMethodData( payment_methods_enabled.payment_method, payment_method_type_response.payment_method_type, Some(card_network_type.card_network.clone()), ), ), )?; card_network_type.surcharge_details = surcharge_details .map(|surcharge_details| { SurchargeDetailsResponse::foreign_try_from(( &surcharge_details, payment_attempt, )) .change_context(ConfigError::DslExecutionError) .attach_printable("Error while constructing Surcharge response type") }) .transpose()?; } } else { let surcharge_details = surcharge_source .generate_surcharge_details_and_populate_surcharge_metadata( &backend_input, payment_attempt, ( &mut surcharge_metadata, types::SurchargeKey::PaymentMethodData( payment_methods_enabled.payment_method, payment_method_type_response.payment_method_type, None, ), ), )?; payment_method_type_response.surcharge_details = surcharge_details .map(|surcharge_details| { SurchargeDetailsResponse::foreign_try_from(( &surcharge_details, payment_attempt, )) .change_context(ConfigError::DslExecutionError) .attach_printable("Error while constructing Surcharge response type") }) .transpose()?; } } } Ok((surcharge_metadata, merchant_surcharge_configs)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 75, "total_crates": null }
fn_clm_router_perform_surcharge_decision_management_for_saved_cards_-3311884311140864532
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/surcharge_decision_configs pub async fn perform_surcharge_decision_management_for_saved_cards( state: &SessionState, algorithm_ref: routing::RoutingAlgorithmRef, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, customer_payment_method_list: &mut [api_models::payment_methods::CustomerPaymentMethod], ) -> ConditionalConfigResult<types::SurchargeMetadata> { let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone()); let surcharge_source = match ( payment_attempt.get_surcharge_details(), algorithm_ref.surcharge_config_algo_id, ) { (Some(request_surcharge_details), _) => { SurchargeSource::Predetermined(request_surcharge_details) } (None, Some(algorithm_id)) => { let cached_algo = ensure_algorithm_cached( &*state.store, &payment_attempt.merchant_id, algorithm_id.as_str(), ) .await?; SurchargeSource::Generate(cached_algo) } (None, None) => return Ok(surcharge_metadata), }; let surcharge_source_log_message = match &surcharge_source { SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules", SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request", }; logger::debug!(customer_saved_card_list_surcharge_source = surcharge_source_log_message); let mut backend_input = make_dsl_input_for_surcharge(payment_attempt, payment_intent, None) .change_context(ConfigError::InputConstructionError)?; for customer_payment_method in customer_payment_method_list.iter_mut() { let payment_token = customer_payment_method.payment_token.clone(); backend_input.payment_method.payment_method = Some(customer_payment_method.payment_method); backend_input.payment_method.payment_method_type = customer_payment_method.payment_method_type; let card_network = customer_payment_method .card .as_ref() .and_then(|card| card.scheme.as_ref()) .map(|scheme| { scheme .clone() .parse_enum("CardNetwork") .change_context(ConfigError::DslExecutionError) }) .transpose()?; backend_input.payment_method.card_network = card_network; let surcharge_details = surcharge_source .generate_surcharge_details_and_populate_surcharge_metadata( &backend_input, payment_attempt, ( &mut surcharge_metadata, types::SurchargeKey::Token(payment_token), ), )?; customer_payment_method.surcharge_details = surcharge_details .map(|surcharge_details| { SurchargeDetailsResponse::foreign_try_from((&surcharge_details, payment_attempt)) .change_context(ConfigError::DslParsingError) }) .transpose()?; } Ok(surcharge_metadata) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 63, "total_crates": null }
fn_clm_router_ensure_algorithm_cached_-3311884311140864532
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/surcharge_decision_configs pub async fn ensure_algorithm_cached( store: &dyn StorageInterface, merchant_id: &common_utils::id_type::MerchantId, algorithm_id: &str, ) -> ConditionalConfigResult<VirInterpreterBackendCacheWrapper> { let key = merchant_id.get_surcharge_dsk_key(); let value_to_cache = || async { let config: diesel_models::Config = store.find_config_by_key(algorithm_id).await?; let record: SurchargeDecisionManagerRecord = config .config .parse_struct("Program") .change_context(errors::StorageError::DeserializationFailed) .attach_printable("Error parsing routing algorithm from configs")?; VirInterpreterBackendCacheWrapper::try_from(record) .change_context(errors::StorageError::ValueNotFound("Program".to_string())) .attach_printable("Error initializing DSL interpreter backend") }; let interpreter = cache::get_or_populate_in_memory( store.get_cache_store().as_ref(), &key, value_to_cache, &SURCHARGE_CACHE, ) .await .change_context(ConfigError::CacheMiss) .attach_printable("Unable to retrieve cached routing algorithm even after refresh")?; Ok(interpreter) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 49, "total_crates": null }
fn_clm_router_generate_surcharge_details_and_populate_surcharge_metadata_-3311884311140864532
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/surcharge_decision_configs // Inherent implementation for SurchargeSource pub fn generate_surcharge_details_and_populate_surcharge_metadata( &self, backend_input: &backend::BackendInput, payment_attempt: &storage::PaymentAttempt, surcharge_metadata_and_key: (&mut types::SurchargeMetadata, types::SurchargeKey), ) -> ConditionalConfigResult<Option<types::SurchargeDetails>> { match self { Self::Generate(interpreter) => { let surcharge_output = execute_dsl_and_get_conditional_config( backend_input.clone(), &interpreter.cached_algorithm, )?; Ok(surcharge_output .surcharge_details .map(|surcharge_details| { get_surcharge_details_from_surcharge_output( surcharge_details, payment_attempt, ) }) .transpose()? .inspect(|surcharge_details| { let (surcharge_metadata, surcharge_key) = surcharge_metadata_and_key; surcharge_metadata .insert_surcharge_details(surcharge_key, surcharge_details.clone()); })) } Self::Predetermined(request_surcharge_details) => Ok(Some( types::SurchargeDetails::from((request_surcharge_details, payment_attempt)), )), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 48, "total_crates": null }
fn_clm_router_foreign_try_from_-2351221721004183006
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/transformers // Implementation of PaymentMethodResponseItem for transformers::ForeignTryFrom<domain::PaymentMethod> fn foreign_try_from(item: domain::PaymentMethod) -> Result<Self, Self::Error> { // For payment methods that are active we should always have the payment method subtype let payment_method_subtype = item.payment_method_subtype .ok_or(errors::ValidationError::MissingRequiredField { field_name: "payment_method_subtype".to_string(), })?; // For payment methods that are active we should always have the payment method type let payment_method_type = item.payment_method_type .ok_or(errors::ValidationError::MissingRequiredField { field_name: "payment_method_type".to_string(), })?; let payment_method_data = item .payment_method_data .map(|payment_method_data| payment_method_data.into_inner()) .map(|payment_method_data| match payment_method_data { api_models::payment_methods::PaymentMethodsData::Card( card_details_payment_method, ) => { let card_details = api::CardDetailFromLocker::from(card_details_payment_method); api_models::payment_methods::PaymentMethodListData::Card(card_details) } api_models::payment_methods::PaymentMethodsData::BankDetails(..) => todo!(), api_models::payment_methods::PaymentMethodsData::WalletDetails(..) => { todo!() } }); let payment_method_billing = item .payment_method_billing_address .clone() .map(|billing| billing.into_inner()) .map(From::from); let network_token_pmd = item .network_token_payment_method_data .clone() .map(|data| data.into_inner()) .and_then(|data| match data { domain::PaymentMethodsData::NetworkToken(token) => { Some(api::NetworkTokenDetailsPaymentMethod::from(token)) } _ => None, }); let network_token_resp = network_token_pmd.map(|pmd| api::NetworkTokenResponse { payment_method_data: pmd, }); // TODO: check how we can get this field let recurring_enabled = Some(true); let psp_tokenization_enabled = item.connector_mandate_details.and_then(|details| { details.payments.map(|payments| { payments.values().any(|connector_token_reference| { connector_token_reference.connector_token_status == api_enums::ConnectorTokenStatus::Active }) }) }); Ok(Self { id: item.id, customer_id: item.customer_id, payment_method_type, payment_method_subtype, created: item.created_at, last_used_at: item.last_used_at, recurring_enabled, payment_method_data, bank: None, requires_cvv: true, is_default: false, billing: payment_method_billing, network_tokenization: network_token_resp, psp_tokenization_enabled: psp_tokenization_enabled.unwrap_or(false), }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 476, "total_crates": null }
fn_clm_router_foreign_from_-2351221721004183006
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/transformers // Implementation of api_models::payment_methods::ConnectorTokenDetails for transformers::ForeignFrom<&payment_method_data::SingleUsePaymentMethodToken> fn foreign_from(token: &payment_method_data::SingleUsePaymentMethodToken) -> Self { Self { connector_id: token.clone().merchant_connector_id, token_type: common_enums::TokenizationType::SingleUse, status: api_enums::ConnectorTokenStatus::Active, connector_token_request_reference_id: None, original_payment_authorized_amount: None, original_payment_authorized_currency: None, metadata: None, token: token.clone().token, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 216, "total_crates": null }
fn_clm_router_mk_basilisk_req_-2351221721004183006
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/transformers pub async fn mk_basilisk_req( jwekey: &settings::Jwekey, jws: &str, locker_choice: api_enums::LockerChoice, ) -> CustomResult<encryption::JweBody, errors::VaultError> { let jws_payload: Vec<&str> = jws.split('.').collect(); let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> { Some(encryption::JwsBody { header: payload.first()?.to_string(), payload: payload.get(1)?.to_string(), signature: payload.get(2)?.to_string(), }) }; let jws_body = generate_jws_body(jws_payload).ok_or(errors::VaultError::SaveCardFailed)?; let payload = jws_body .encode_to_vec() .change_context(errors::VaultError::SaveCardFailed)?; let public_key = match locker_choice { api_enums::LockerChoice::HyperswitchCardVault => { jwekey.vault_encryption_key.peek().as_bytes() } }; let jwe_encrypted = encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None) .await .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Error on jwe encrypt")?; let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect(); let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> { Some(encryption::JweBody { header: payload.first()?.to_string(), iv: payload.get(2)?.to_string(), encrypted_payload: payload.get(3)?.to_string(), tag: payload.get(4)?.to_string(), encrypted_key: payload.get(1)?.to_string(), }) }; let jwe_body = generate_jwe_body(jwe_payload).ok_or(errors::VaultError::SaveCardFailed)?; Ok(jwe_body) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 84, "total_crates": null }
fn_clm_router_generate_payment_method_response_-2351221721004183006
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/transformers pub fn generate_payment_method_response( payment_method: &domain::PaymentMethod, single_use_token: &Option<payment_method_data::SingleUsePaymentMethodToken>, ) -> errors::RouterResult<api::PaymentMethodResponse> { let pmd = payment_method .payment_method_data .clone() .map(|data| data.into_inner()) .and_then(|data| match data { api::PaymentMethodsData::Card(card) => { Some(api::PaymentMethodResponseData::Card(card.into())) } _ => None, }); let mut connector_tokens = payment_method .connector_mandate_details .as_ref() .and_then(|connector_token_details| connector_token_details.payments.clone()) .map(|payment_token_details| payment_token_details.0) .map(|payment_token_details| { payment_token_details .into_iter() .map(transformers::ForeignFrom::foreign_from) .collect::<Vec<_>>() }) .unwrap_or_default(); if let Some(token) = single_use_token { let connector_token_single_use = transformers::ForeignFrom::foreign_from(token); connector_tokens.push(connector_token_single_use); } let connector_tokens = if connector_tokens.is_empty() { None } else { Some(connector_tokens) }; let network_token_pmd = payment_method .network_token_payment_method_data .clone() .map(|data| data.into_inner()) .and_then(|data| match data { domain::PaymentMethodsData::NetworkToken(token) => { Some(api::NetworkTokenDetailsPaymentMethod::from(token)) } _ => None, }); let network_token = network_token_pmd.map(|pmd| api::NetworkTokenResponse { payment_method_data: pmd, }); let resp = api::PaymentMethodResponse { merchant_id: payment_method.merchant_id.to_owned(), customer_id: payment_method.customer_id.to_owned(), id: payment_method.id.to_owned(), payment_method_type: payment_method.get_payment_method_type(), payment_method_subtype: payment_method.get_payment_method_subtype(), created: Some(payment_method.created_at), recurring_enabled: Some(false), last_used_at: Some(payment_method.last_used_at), payment_method_data: pmd, connector_tokens, network_token, }; Ok(resp) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 81, "total_crates": null }
fn_clm_router_create_jwe_body_for_vault_-2351221721004183006
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/transformers pub async fn create_jwe_body_for_vault( jwekey: &settings::Jwekey, jws: &str, ) -> CustomResult<encryption::JweBody, errors::VaultError> { let jws_payload: Vec<&str> = jws.split('.').collect(); let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> { Some(encryption::JwsBody { header: payload.first()?.to_string(), payload: payload.get(1)?.to_string(), signature: payload.get(2)?.to_string(), }) }; let jws_body = generate_jws_body(jws_payload).ok_or(errors::VaultError::RequestEncryptionFailed)?; let payload = jws_body .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed)?; let public_key = jwekey.vault_encryption_key.peek().as_bytes(); let jwe_encrypted = encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None) .await .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Error on jwe encrypt")?; let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect(); let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> { Some(encryption::JweBody { header: payload.first()?.to_string(), iv: payload.get(2)?.to_string(), encrypted_payload: payload.get(3)?.to_string(), tag: payload.get(4)?.to_string(), encrypted_key: payload.get(1)?.to_string(), }) }; let jwe_body = generate_jwe_body(jwe_payload).ok_or(errors::VaultError::RequestEncodingFailed)?; Ok(jwe_body) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 75, "total_crates": null }
fn_clm_router_generate_network_token_-7727439329010854568
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/network_tokenization pub async fn generate_network_token( state: &routes::SessionState, payload_bytes: &[u8], customer_id: id_type::GlobalCustomerId, tokenization_service: &settings::NetworkTokenizationService, ) -> CustomResult< (pm_types::GenerateNetworkTokenResponsePayload, String), errors::NetworkTokenizationError, > { let enc_key = tokenization_service.public_key.peek().clone(); let key_id = tokenization_service.key_id.clone(); let jwt = encryption::encrypt_jwe( payload_bytes, enc_key, services::EncryptionAlgorithm::A128GCM, Some(key_id.as_str()), ) .await .change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed) .attach_printable("Error on jwe encrypt")?; let order_data = pm_types::OrderData { consent_id: uuid::Uuid::new_v4().to_string(), customer_id, }; let api_payload = pm_types::ApiPayload { service: NETWORK_TOKEN_SERVICE.to_string(), card_data: Secret::new(jwt), order_data, key_id, should_send_token: true, }; let mut request = services::Request::new( services::Method::Post, tokenization_service.generate_token_url.as_str(), ); request.add_header(headers::CONTENT_TYPE, "application/json".into()); request.add_header( headers::AUTHORIZATION, tokenization_service .token_service_api_key .peek() .clone() .into_masked(), ); request.add_default_headers(); request.set_body(RequestContent::Json(Box::new(api_payload))); logger::info!("Request to generate token: {:?}", request); let response = services::call_connector_api(state, request, "generate_token") .await .change_context(errors::NetworkTokenizationError::ApiError); let res = response .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { let parsed_error: pm_types::NetworkTokenErrorResponse = err_res .response .parse_struct("Card Network Tokenization Response") .change_context( errors::NetworkTokenizationError::ResponseDeserializationFailed, )?; logger::error!( error_code = %parsed_error.error_info.code, developer_message = %parsed_error.error_info.developer_message, "Network tokenization error: {}", parsed_error.error_message ); Err(errors::NetworkTokenizationError::ResponseDeserializationFailed) .attach_printable(format!("Response Deserialization Failed: {err_res:?}")) } Ok(res) => Ok(res), }) .inspect_err(|err| { logger::error!("Error while deserializing response: {:?}", err); })?; let network_response: pm_types::CardNetworkTokenResponse = res .response .parse_struct("Card Network Tokenization Response") .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; logger::debug!("Network Token Response: {:?}", network_response); let dec_key = tokenization_service.private_key.peek().clone(); let card_network_token_response = services::decrypt_jwe( network_response.payload.peek(), services::KeyIdCheck::SkipKeyIdCheck, dec_key, jwe::RSA_OAEP_256, ) .await .change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed) .attach_printable( "Failed to decrypt the tokenization response from the tokenization service", )?; let cn_response: pm_types::GenerateNetworkTokenResponsePayload = serde_json::from_str(&card_network_token_response) .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; Ok((cn_response.clone(), cn_response.card_reference)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 99, "total_crates": null }
fn_clm_router_mk_tokenization_req_-7727439329010854568
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/network_tokenization pub async fn mk_tokenization_req( state: &routes::SessionState, payload_bytes: &[u8], customer_id: id_type::CustomerId, tokenization_service: &settings::NetworkTokenizationService, ) -> CustomResult< (pm_types::CardNetworkTokenResponsePayload, Option<String>), errors::NetworkTokenizationError, > { let enc_key = tokenization_service.public_key.peek().clone(); let key_id = tokenization_service.key_id.clone(); let jwt = encryption::encrypt_jwe( payload_bytes, enc_key, services::EncryptionAlgorithm::A128GCM, Some(key_id.as_str()), ) .await .change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed) .attach_printable("Error on jwe encrypt")?; let order_data = pm_types::OrderData { consent_id: uuid::Uuid::new_v4().to_string(), customer_id, }; let api_payload = pm_types::ApiPayload { service: NETWORK_TOKEN_SERVICE.to_string(), card_data: Secret::new(jwt), order_data, key_id, should_send_token: true, }; let mut request = services::Request::new( services::Method::Post, tokenization_service.generate_token_url.as_str(), ); request.add_header(headers::CONTENT_TYPE, "application/json".into()); request.add_header( headers::AUTHORIZATION, tokenization_service .token_service_api_key .peek() .clone() .into_masked(), ); request.add_default_headers(); request.set_body(RequestContent::Json(Box::new(api_payload))); logger::info!("Request to generate token: {:?}", request); let response = services::call_connector_api(state, request, "generate_token") .await .change_context(errors::NetworkTokenizationError::ApiError); let res = response .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { let parsed_error: pm_types::NetworkTokenErrorResponse = err_res .response .parse_struct("Card Network Tokenization Response") .change_context( errors::NetworkTokenizationError::ResponseDeserializationFailed, )?; logger::error!( error_code = %parsed_error.error_info.code, developer_message = %parsed_error.error_info.developer_message, "Network tokenization error: {}", parsed_error.error_message ); Err(errors::NetworkTokenizationError::ResponseDeserializationFailed) .attach_printable(format!("Response Deserialization Failed: {err_res:?}")) } Ok(res) => Ok(res), }) .inspect_err(|err| { logger::error!("Error while deserializing response: {:?}", err); })?; let network_response: pm_types::CardNetworkTokenResponse = res .response .parse_struct("Card Network Tokenization Response") .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; let dec_key = tokenization_service.private_key.peek().clone(); let card_network_token_response = services::decrypt_jwe( network_response.payload.peek(), services::KeyIdCheck::SkipKeyIdCheck, dec_key, jwe::RSA_OAEP_256, ) .await .change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed) .attach_printable( "Failed to decrypt the tokenization response from the tokenization service", )?; let cn_response: pm_types::CardNetworkTokenResponsePayload = serde_json::from_str(&card_network_token_response) .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; Ok((cn_response.clone(), Some(cn_response.card_reference))) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 96, "total_crates": null }
fn_clm_router_delete_network_token_from_tokenization_service_-7727439329010854568
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/network_tokenization pub async fn delete_network_token_from_tokenization_service( state: &routes::SessionState, network_token_requestor_reference_id: String, customer_id: &id_type::CustomerId, tokenization_service: &settings::NetworkTokenizationService, ) -> CustomResult<bool, errors::NetworkTokenizationError> { let mut request = services::Request::new( services::Method::Post, tokenization_service.delete_token_url.as_str(), ); let payload = pm_types::DeleteCardToken { card_reference: network_token_requestor_reference_id, customer_id: customer_id.clone(), }; request.add_header(headers::CONTENT_TYPE, "application/json".into()); request.add_header( headers::AUTHORIZATION, tokenization_service .token_service_api_key .clone() .peek() .clone() .into_masked(), ); request.add_default_headers(); request.set_body(RequestContent::Json(Box::new(payload))); logger::info!("Request to delete network token: {:?}", request); // Send the request using `call_connector_api` let response = services::call_connector_api(state, request, "delete network token") .await .change_context(errors::NetworkTokenizationError::ApiError); let res = response .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { let parsed_error: pm_types::NetworkTokenErrorResponse = err_res .response .parse_struct("Delete Network Tokenization Response") .change_context( errors::NetworkTokenizationError::ResponseDeserializationFailed, )?; logger::error!( error_code = %parsed_error.error_info.code, developer_message = %parsed_error.error_info.developer_message, "Network tokenization error: {}", parsed_error.error_message ); Err(errors::NetworkTokenizationError::ResponseDeserializationFailed) .attach_printable(format!("Response Deserialization Failed: {err_res:?}")) } Ok(res) => Ok(res), }) .inspect_err(|err| { logger::error!("Error while deserializing response: {:?}", err); })?; let delete_token_response: pm_types::DeleteNetworkTokenResponse = res .response .parse_struct("Delete Network Tokenization Response") .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; logger::info!("Delete Network Token Response: {:?}", delete_token_response); if delete_token_response.status == pm_types::DeleteNetworkTokenStatus::Success { Ok(true) } else { Err(errors::NetworkTokenizationError::DeleteNetworkTokenFailed) .attach_printable("Delete Token at Token service failed") } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 68, "total_crates": null }
fn_clm_router_get_token_from_tokenization_service_-7727439329010854568
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/network_tokenization pub async fn get_token_from_tokenization_service( state: &routes::SessionState, network_token_requestor_ref_id: String, pm_data: &domain::PaymentMethod, ) -> errors::RouterResult<domain::NetworkTokenData> { let token_response = if let Some(network_tokenization_service) = &state.conf.network_tokenization_service { record_operation_time( async { get_network_token( state, &pm_data.customer_id, network_token_requestor_ref_id, network_tokenization_service.get_inner(), ) .await .inspect_err( |e| logger::error!(error=?e, "Error while fetching token from tokenization service") ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Fetch network token failed") }, &metrics::FETCH_NETWORK_TOKEN_TIME, &[], ) .await } else { Err(errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured) .inspect_err(|err| { logger::error!(error=? err); }) .change_context(errors::ApiErrorResponse::InternalServerError) }?; let token_decrypted = pm_data .network_token_payment_method_data .clone() .map(|value| value.into_inner()) .and_then(|payment_method_data| match payment_method_data { hyperswitch_domain_models::payment_method_data::PaymentMethodsData::NetworkToken( token, ) => Some(token), _ => None, }) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to obtain decrypted token object from db")?; let network_token_data = domain::NetworkTokenData { network_token: token_response.authentication_details.token, cryptogram: Some(token_response.authentication_details.cryptogram), network_token_exp_month: token_decrypted .network_token_expiry_month .unwrap_or(token_response.token_details.exp_month), network_token_exp_year: token_decrypted .network_token_expiry_year .unwrap_or(token_response.token_details.exp_year), card_holder_name: token_decrypted.card_holder_name, nick_name: token_decrypted.nick_name.or(token_response.nickname), card_issuer: token_decrypted.card_issuer.or(token_response.issuer), card_network: Some(token_response.network), card_type: token_decrypted .card_type .or(token_response.card_type) .as_ref() .map(|c| api_payment_methods::CardType::from_str(c)) .transpose() .ok() .flatten(), card_issuing_country: token_decrypted.issuer_country, bank_code: None, eci: token_response.eci, }; Ok(network_token_data) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 66, "total_crates": null }
fn_clm_router_get_network_token_-7727439329010854568
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/network_tokenization pub async fn get_network_token( state: &routes::SessionState, customer_id: &id_type::GlobalCustomerId, network_token_requestor_ref_id: String, tokenization_service: &settings::NetworkTokenizationService, ) -> CustomResult<pm_types::TokenResponse, errors::NetworkTokenizationError> { let mut request = services::Request::new( services::Method::Post, tokenization_service.fetch_token_url.as_str(), ); let payload = pm_types::GetCardToken { card_reference: network_token_requestor_ref_id, customer_id: customer_id.clone(), }; request.add_header(headers::CONTENT_TYPE, "application/json".into()); request.add_header( headers::AUTHORIZATION, tokenization_service .token_service_api_key .clone() .peek() .clone() .into_masked(), ); request.add_default_headers(); request.set_body(RequestContent::Json(Box::new(payload))); logger::info!("Request to fetch network token: {:?}", request); // Send the request using `call_connector_api` let response = services::call_connector_api(state, request, "get network token") .await .change_context(errors::NetworkTokenizationError::ApiError); let res = response .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { let parsed_error: pm_types::NetworkTokenErrorResponse = err_res .response .parse_struct("Card Network Tokenization Response") .change_context( errors::NetworkTokenizationError::ResponseDeserializationFailed, )?; logger::error!( error_code = %parsed_error.error_info.code, developer_message = %parsed_error.error_info.developer_message, "Network tokenization error: {}", parsed_error.error_message ); Err(errors::NetworkTokenizationError::ResponseDeserializationFailed) .attach_printable(format!("Response Deserialization Failed: {err_res:?}")) } Ok(res) => Ok(res), })?; let token_response: pm_types::TokenResponse = res .response .parse_struct("Get Network Token Response") .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; logger::info!("Fetch Network Token Response: {:?}", token_response); Ok(token_response) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 64, "total_crates": null }
fn_clm_router_validate_request_and_initiate_payment_method_collect_link_3722981865884112404
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/validator 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), }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 99, "total_crates": null }
fn_clm_router_new_8939278669962237059
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize // Implementation of CardNetworkTokenizeExecutor<'a, D> for NetworkTokenizationProcess<'a, D> fn new( state: &'a SessionState, merchant_context: &'a domain::MerchantContext, data: &'a D, customer: &'a domain_request_types::CustomerDetails, ) -> Self { Self { data, customer, state, merchant_account: merchant_context.get_merchant_account(), key_store: merchant_context.get_merchant_key_store(), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14457, "total_crates": null }
fn_clm_router_encrypt_card_8939278669962237059
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize // Implementation of CardNetworkTokenizeExecutor<'a, D> for NetworkTokenizationProcess<'a, D> async fn encrypt_card( &self, card_details: &domain::CardDetail, saved_to_locker: bool, ) -> RouterResult<Encryptable<Secret<serde_json::Value>>> { let pm_data = api::PaymentMethodsData::Card(api::CardDetailsPaymentMethod { last4_digits: Some(card_details.card_number.get_last4()), expiry_month: Some(card_details.card_exp_month.clone()), expiry_year: Some(card_details.card_exp_year.clone()), card_isin: Some(card_details.card_number.get_card_isin()), nick_name: card_details.nick_name.clone(), card_holder_name: card_details.card_holder_name.clone(), issuer_country: card_details.card_issuing_country.clone(), card_issuer: card_details.card_issuer.clone(), card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker, co_badged_card_data: card_details .co_badged_card_data .as_ref() .map(|data| data.into()), }); create_encrypted_data(&self.state.into(), self.key_store, pm_data) .await .inspect_err(|err| logger::info!("Error encrypting payment method data: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 47, "total_crates": null }
fn_clm_router_encrypt_network_token_8939278669962237059
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize // Implementation of CardNetworkTokenizeExecutor<'a, D> for NetworkTokenizationProcess<'a, D> async fn encrypt_network_token( &self, network_token_details: &NetworkTokenizationResponse, card_details: &domain::CardDetail, saved_to_locker: bool, ) -> RouterResult<Encryptable<Secret<serde_json::Value>>> { let network_token = &network_token_details.0; let token_data = api::PaymentMethodsData::Card(api::CardDetailsPaymentMethod { last4_digits: Some(network_token.token_last_four.clone()), expiry_month: Some(network_token.token_expiry_month.clone()), expiry_year: Some(network_token.token_expiry_year.clone()), card_isin: Some(network_token.token_isin.clone()), nick_name: card_details.nick_name.clone(), card_holder_name: card_details.card_holder_name.clone(), issuer_country: card_details.card_issuing_country.clone(), card_issuer: card_details.card_issuer.clone(), card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker, co_badged_card_data: None, }); create_encrypted_data(&self.state.into(), self.key_store, token_data) .await .inspect_err(|err| logger::info!("Error encrypting network token data: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 44, "total_crates": null }
fn_clm_router_tokenize_cards_8939278669962237059
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize pub async fn tokenize_cards( state: &SessionState, records: Vec<payment_methods_api::CardNetworkTokenizeRequest>, merchant_context: &domain::MerchantContext, ) -> errors::RouterResponse<Vec<payment_methods_api::CardNetworkTokenizeResponse>> { use futures::stream::StreamExt; // Process all records in parallel let responses = futures::stream::iter(records.into_iter()) .map(|record| async move { let tokenize_request = record.data.clone(); let customer = record.customer.clone(); Box::pin(tokenize_card_flow( state, domain::CardNetworkTokenizeRequest::foreign_from(record), merchant_context, )) .await .unwrap_or_else(|e| { let err = e.current_context(); payment_methods_api::CardNetworkTokenizeResponse { tokenization_data: Some(tokenize_request), error_code: Some(err.error_code()), error_message: Some(err.error_message()), card_tokenized: false, payment_method_response: None, customer: Some(customer), } }) }) .buffer_unordered(10) .collect() .await; // Return the final response Ok(services::ApplicationResponse::Json(responses)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 43, "total_crates": null }
fn_clm_router_store_network_token_in_locker_8939278669962237059
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize // Implementation of CardNetworkTokenizeExecutor<'a, D> for NetworkTokenizationProcess<'a, D> async fn store_network_token_in_locker( &self, network_token: &NetworkTokenizationResponse, customer_id: &id_type::CustomerId, card_holder_name: Option<Secret<String>>, nick_name: Option<Secret<String>>, ) -> RouterResult<pm_transformers::StoreCardRespPayload> { let network_token = &network_token.0; let merchant_id = self.merchant_account.get_id(); let locker_req = pm_transformers::StoreLockerReq::LockerCard(pm_transformers::StoreCardReq { merchant_id: merchant_id.clone(), merchant_customer_id: customer_id.clone(), card: payment_methods_api::Card { card_number: network_token.token.clone(), card_exp_month: network_token.token_expiry_month.clone(), card_exp_year: network_token.token_expiry_year.clone(), card_brand: Some(network_token.card_brand.to_string()), card_isin: Some(network_token.token_isin.clone()), name_on_card: card_holder_name, nick_name: nick_name.map(|nick_name| nick_name.expose()), }, requestor_card_reference: None, ttl: self.state.conf.locker.ttl_for_storage_in_secs, }); let stored_resp = add_card_to_hs_locker( self.state, &locker_req, customer_id, api_enums::LockerChoice::HyperswitchCardVault, ) .await .inspect_err(|err| logger::info!("Error adding card in locker: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(stored_resp) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 42, "total_crates": null }
fn_clm_router_update_payment_method_record_-8677727760589754800
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/migration pub async fn update_payment_method_record( state: &SessionState, req: pm_api::UpdatePaymentMethodRecord, merchant_id: &id_type::MerchantId, merchant_context: &merchant_context::MerchantContext, ) -> CustomResult< ApplicationResponse<pm_api::PaymentMethodRecordUpdateResponse>, errors::ApiErrorResponse, > { use std::collections::HashMap; use common_enums::enums; use common_utils::pii; use hyperswitch_domain_models::mandates::{ CommonMandateReference, PaymentsMandateReference, PaymentsMandateReferenceRecord, PayoutsMandateReference, PayoutsMandateReferenceRecord, }; let db = &*state.store; let payment_method_id = req.payment_method_id.clone(); let network_transaction_id = req.network_transaction_id.clone(); let status = req.status; let key_manager_state = state.into(); let mut updated_card_expiry = false; let payment_method = db .find_payment_method( &state.into(), merchant_context.get_merchant_key_store(), &payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; if payment_method.merchant_id != *merchant_id { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Merchant ID in the request does not match the Merchant ID in the payment method record.".to_string(), }.into()); } let updated_payment_method_data = match payment_method.payment_method_data.as_ref() { Some(data) => { match serde_json::from_value::<pm_api::PaymentMethodsData>( data.clone().into_inner().expose(), ) { Ok(pm_api::PaymentMethodsData::Card(mut card_data)) => { if let Some(new_month) = &req.card_expiry_month { card_data.expiry_month = Some(new_month.clone()); updated_card_expiry = true; } if let Some(new_year) = &req.card_expiry_year { card_data.expiry_year = Some(new_year.clone()); updated_card_expiry = true; } if updated_card_expiry { Some( create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), pm_api::PaymentMethodsData::Card(card_data), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data") .map(Into::into), ) } else { None } } _ => None, } } None => None, } .transpose()?; let mca_data_cache = if let Some(merchant_connector_ids) = &req.merchant_connector_ids { let parsed_mca_ids = MerchantConnectorValidator::parse_comma_separated_ids(merchant_connector_ids)?; let mut cache = HashMap::new(); for merchant_connector_id in parsed_mca_ids { let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &state.into(), merchant_context.get_merchant_account().get_id(), &merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, )?; cache.insert(merchant_connector_id, mca); } Some(cache) } else { None }; let (customer, updated_customer) = match (&req.connector_customer_id, &mca_data_cache) { (Some(connector_customer_id), Some(cache)) => { let customer = db .find_customer_by_customer_id_merchant_id( &state.into(), &payment_method.customer_id, merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; let customer_update = build_connector_customer_update(&customer, connector_customer_id, cache)?; (Some(customer), Some(customer_update)) } _ => (None, None), }; let pm_update = match (&req.payment_instrument_id, &mca_data_cache) { (Some(payment_instrument_id), Some(cache)) => { let mandate_details = payment_method .get_common_mandate_reference() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize to Payment Mandate Reference ")?; let mut existing_payments_mandate = mandate_details .payments .clone() .unwrap_or(PaymentsMandateReference(HashMap::new())); let mut existing_payouts_mandate = mandate_details .payouts .clone() .unwrap_or(PayoutsMandateReference(HashMap::new())); for (merchant_connector_id, mca) in cache.iter() { match mca.connector_type { enums::ConnectorType::PayoutProcessor => { let new_payout_record = PayoutsMandateReferenceRecord { transfer_method_id: Some(payment_instrument_id.peek().to_string()), }; if let Some(existing_record) = existing_payouts_mandate.0.get_mut(merchant_connector_id) { if let Some(transfer_method_id) = &new_payout_record.transfer_method_id { existing_record.transfer_method_id = Some(transfer_method_id.clone()); } } else { existing_payouts_mandate .0 .insert(merchant_connector_id.clone(), new_payout_record); } } _ => { if let Some(existing_record) = existing_payments_mandate.0.get_mut(merchant_connector_id) { existing_record.connector_mandate_id = payment_instrument_id.peek().to_string(); } else { existing_payments_mandate.0.insert( merchant_connector_id.clone(), PaymentsMandateReferenceRecord { connector_mandate_id: payment_instrument_id.peek().to_string(), payment_method_type: None, original_payment_authorized_amount: None, original_payment_authorized_currency: None, mandate_metadata: None, connector_mandate_status: None, connector_mandate_request_reference_id: None, }, ); } } } } let updated_connector_mandate_details = CommonMandateReference { payments: if !existing_payments_mandate.0.is_empty() { Some(existing_payments_mandate) } else { mandate_details.payments }, payouts: if !existing_payouts_mandate.0.is_empty() { Some(existing_payouts_mandate) } else { mandate_details.payouts }, }; let connector_mandate_details_value = updated_connector_mandate_details .get_mandate_details_value() .map_err(|err| { logger::error!("Failed to get get_mandate_details_value : {:?}", err); errors::ApiErrorResponse::MandateUpdateFailed })?; PaymentMethodUpdate::PaymentMethodBatchUpdate { connector_mandate_details: Some(pii::SecretSerdeValue::new( connector_mandate_details_value, )), network_transaction_id, status, payment_method_data: updated_payment_method_data.clone(), } } _ => { if updated_payment_method_data.is_some() { PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: updated_payment_method_data, } } else { PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, status, } } } }; let response = db .update_payment_method( &state.into(), merchant_context.get_merchant_key_store(), payment_method, pm_update, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( "Failed to update payment method for existing pm_id: {payment_method_id:?} in db", ))?; let connector_customer_response = if let (Some(customer_data), Some(customer_update)) = (customer, updated_customer) { let updated_customer = db .update_customer_by_customer_id_merchant_id( &state.into(), response.customer_id.clone(), merchant_id.clone(), customer_data, customer_update, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update customer connector data")?; updated_customer.connector_customer } else { None }; Ok(ApplicationResponse::Json( pm_api::PaymentMethodRecordUpdateResponse { payment_method_id: response.payment_method_id, status: response.status, network_transaction_id: response.network_transaction_id, connector_mandate_details: response .connector_mandate_details .map(pii::SecretSerdeValue::new), updated_payment_method_data: Some(updated_card_expiry), connector_customer: connector_customer_response, }, )) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 189, "total_crates": null }
fn_clm_router_build_connector_customer_update_-8677727760589754800
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/migration fn build_connector_customer_update( customer: &hyperswitch_domain_models::customer::Customer, connector_customer_id: &str, mca_cache: &std::collections::HashMap< id_type::MerchantConnectorAccountId, hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, >, ) -> CustomResult<hyperswitch_domain_models::customer::CustomerUpdate, errors::ApiErrorResponse> { use common_enums::enums; use common_utils::pii; let mut updated_connector_customer_data: std::collections::HashMap<String, serde_json::Value> = customer .connector_customer .as_ref() .and_then(|cc| serde_json::from_value(cc.peek().clone()).ok()) .unwrap_or_default(); for (_, mca) in mca_cache.iter() { let key = match mca.connector_type { enums::ConnectorType::PayoutProcessor => { format!( "{}_{}", mca.profile_id.get_string_repr(), mca.connector_name ) } _ => mca.merchant_connector_id.get_string_repr().to_string(), }; updated_connector_customer_data.insert( key, serde_json::Value::String(connector_customer_id.to_string()), ); } Ok( hyperswitch_domain_models::customer::CustomerUpdate::ConnectorCustomer { connector_customer: Some(pii::SecretSerdeValue::new( serde_json::to_value(updated_connector_customer_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize connector customer data")?, )), }, ) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 37, "total_crates": null }
fn_clm_router_validate_and_get_payment_method_records_-8677727760589754800
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/migration // Inherent implementation for PaymentMethodsUpdateForm pub fn validate_and_get_payment_method_records(self) -> UpdateValidationResult { let records = parse_update_csv(self.file.data.to_bytes()).map_err(|e| { errors::ApiErrorResponse::PreconditionFailed { message: e.to_string(), } })?; Ok((self.merchant_id.clone(), records)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 34, "total_crates": null }
fn_clm_router_update_payment_methods_-8677727760589754800
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/migration pub async fn update_payment_methods( state: &SessionState, payment_methods: Vec<pm_api::UpdatePaymentMethodRecord>, merchant_id: &id_type::MerchantId, merchant_context: &merchant_context::MerchantContext, ) -> PmMigrationResult<Vec<pm_api::PaymentMethodUpdateResponse>> { let mut result = Vec::with_capacity(payment_methods.len()); for record in payment_methods { let update_res = update_payment_method_record(state, record.clone(), merchant_id, merchant_context) .await; let res = match update_res { Ok(ApplicationResponse::Json(response)) => Ok(response), Err(e) => Err(e.to_string()), _ => Err("Failed to update payment method".to_string()), }; result.push(pm_api::PaymentMethodUpdateResponse::from((res, record))); } Ok(ApplicationResponse::Json(result)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 31, "total_crates": null }
fn_clm_router_parse_update_csv_-8677727760589754800
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/migration fn parse_update_csv(data: &[u8]) -> csv::Result<Vec<pm_api::UpdatePaymentMethodRecord>> { let mut csv_reader = Reader::from_reader(data); let mut records = Vec::new(); let mut id_counter = 0; for result in csv_reader.deserialize() { let mut record: pm_api::UpdatePaymentMethodRecord = result?; id_counter += 1; record.line_number = Some(id_counter); records.push(record); } Ok(records) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 11, "total_crates": null }
fn_clm_router_create_tokenize_-5139583331379506449
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/vault pub async fn create_tokenize( state: &routes::SessionState, value1: String, value2: Option<String>, lookup_key: String, encryption_key: &masking::Secret<Vec<u8>>, ) -> RouterResult<String> { let redis_key = get_redis_locker_key(lookup_key.as_str()); let func = || async { metrics::CREATED_TOKENIZED_CARD.add(1, &[]); let payload_to_be_encrypted = api::TokenizePayloadRequest { value1: value1.clone(), value2: value2.clone().unwrap_or_default(), lookup_key: lookup_key.clone(), service_name: VAULT_SERVICE_NAME.to_string(), }; let payload = payload_to_be_encrypted .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError)?; let encrypted_payload = GcmAes256 .encode_message(encryption_key.peek().as_ref(), payload.as_bytes()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode redis temp locker data")?; let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn .set_key_if_not_exists_with_expiry( &redis_key.as_str().into(), bytes::Bytes::from(encrypted_payload), Some(i64::from(consts::LOCKER_REDIS_EXPIRY_SECONDS)), ) .await .map(|_| lookup_key.clone()) .inspect_err(|error| { metrics::TEMP_LOCKER_FAILURES.add(1, &[]); logger::error!(?error, "Failed to store tokenized data in Redis"); }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error from redis locker") }; match func().await { Ok(s) => { logger::info!( "Insert payload in redis locker successful with lookup key: {:?}", redis_key ); Ok(s) } Err(err) => { logger::error!("Redis Temp locker Failed: {:?}", err); Err(err) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 96, "total_crates": null }
fn_clm_router_get_tokenized_data_-5139583331379506449
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/vault pub async fn get_tokenized_data( state: &routes::SessionState, lookup_key: &str, _should_get_value2: bool, encryption_key: &masking::Secret<Vec<u8>>, ) -> RouterResult<api::TokenizePayloadRequest> { let redis_key = get_redis_locker_key(lookup_key); let func = || async { metrics::GET_TOKENIZED_CARD.add(1, &[]); let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let response = redis_conn .get_key::<bytes::Bytes>(&redis_key.as_str().into()) .await; match response { Ok(resp) => { let decrypted_payload = GcmAes256 .decode_message( encryption_key.peek().as_ref(), masking::Secret::new(resp.into()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decode redis temp locker data")?; let get_response: api::TokenizePayloadRequest = bytes::Bytes::from(decrypted_payload) .parse_struct("TokenizePayloadRequest") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Error getting TokenizePayloadRequest from tokenize response", )?; Ok(get_response) } Err(err) => { metrics::TEMP_LOCKER_FAILURES.add(1, &[]); Err(err).change_context(errors::ApiErrorResponse::UnprocessableEntity { message: "Token is invalid or expired".into(), }) } } }; match func().await { Ok(s) => { logger::info!( "Fetch payload in redis locker successful with lookup key: {:?}", redis_key ); Ok(s) } Err(err) => { logger::error!("Redis Temp locker Failed: {:?}", err); Err(err) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 72, "total_crates": null }
fn_clm_router_insert_cvc_using_payment_token_-5139583331379506449
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/vault pub async fn insert_cvc_using_payment_token( state: &routes::SessionState, payment_token: &String, payment_method_data: api_models::payment_methods::PaymentMethodCreateData, payment_method: common_enums::PaymentMethod, fulfillment_time: i64, encryption_key: &masking::Secret<Vec<u8>>, ) -> RouterResult<()> { let card_cvc = domain::PaymentMethodVaultingData::try_from(payment_method_data)? .get_card() .and_then(|card| card.card_cvc.clone()); if let Some(card_cvc) = card_cvc { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = format!("pm_token_{payment_token}_{payment_method}_hyperswitch_cvc"); let payload_to_be_encrypted = TemporaryVaultCvc { card_cvc }; let payload = payload_to_be_encrypted .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError)?; // Encrypt the CVC and store it in Redis let encrypted_payload = GcmAes256 .encode_message(encryption_key.peek().as_ref(), payload.as_bytes()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode TemporaryVaultCvc for vault")?; redis_conn .set_key_if_not_exists_with_expiry( &key.as_str().into(), bytes::Bytes::from(encrypted_payload), Some(fulfillment_time), ) .await .change_context(errors::StorageError::KVError) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add token in redis")?; }; Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 57, "total_crates": null }
fn_clm_router_retrieve_and_delete_cvc_from_payment_token_-5139583331379506449
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/vault pub async fn retrieve_and_delete_cvc_from_payment_token( state: &routes::SessionState, payment_token: &String, payment_method: common_enums::PaymentMethod, encryption_key: &masking::Secret<Vec<u8>>, ) -> RouterResult<masking::Secret<String>> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = format!("pm_token_{payment_token}_{payment_method}_hyperswitch_cvc",); let data = redis_conn .get_key::<bytes::Bytes>(&key.clone().into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")?; // decrypt the cvc data let decrypted_payload = GcmAes256 .decode_message( encryption_key.peek().as_ref(), masking::Secret::new(data.into()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decode TemporaryVaultCvc from vault")?; let cvc_data: TemporaryVaultCvc = bytes::Bytes::from(decrypted_payload) .parse_struct("TemporaryVaultCvc") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize TemporaryVaultCvc")?; // delete key after retrieving the cvc redis_conn.delete_key(&key.into()).await.map_err(|err| { logger::error!("Failed to delete token from redis: {:?}", err); }); Ok(cvc_data.card_cvc) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 55, "total_crates": null }
fn_clm_router_retrieve_payment_method_from_vault_external_-5139583331379506449
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/vault pub async fn retrieve_payment_method_from_vault_external( state: &routes::SessionState, merchant_account: &domain::MerchantAccount, pm: &domain::PaymentMethod, merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, ) -> RouterResult<pm_types::VaultRetrieveResponse> { let connector_vault_id = pm .locker_id .clone() .map(|id| id.get_string_repr().to_owned()); let merchant_connector_account = match &merchant_connector_account { domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => { Ok(mca.as_ref()) } domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("MerchantConnectorDetails not supported for vault operations")) } }?; let router_data = core_utils::construct_vault_router_data( state, merchant_account.get_id(), merchant_connector_account, None, connector_vault_id, None, ) .await?; let mut old_router_data = VaultConnectorFlowData::to_old_router_data(router_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Cannot construct router data for making the external vault retrieve api call", )?; let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; let connector_integration: services::BoxedVaultConnectorIntegrationInterface< ExternalVaultRetrieveFlow, types::VaultRequestData, types::VaultResponseData, > = connector_data.connector.get_connector_integration(); let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &old_router_data, payments_core::CallConnectorAction::Trigger, None, None, ) .await .to_vault_failed_response()?; get_vault_response_for_retrieve_payment_method_data::<ExternalVaultRetrieveFlow>( router_data_resp, ) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 51, "total_crates": null }
fn_clm_router_construct_supported_connectors_for_update_mandate_node_4451841960619737810
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/utils fn construct_supported_connectors_for_update_mandate_node( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, domain_id: cgraph::DomainId, supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate, pmt: RequestPaymentMethodTypes, payment_method: enums::PaymentMethod, ) -> Result<Option<cgraph::NodeId>, KgraphError> { let card_value_node = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), None, None::<()>, ); let payment_type_value_node = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentType( euclid::enums::PaymentType::UpdateMandate, )), None, None::<()>, ); let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); let mut card_dir_values = Vec::new(); let mut non_card_dir_values = Vec::new(); if let Some(supported_pm_for_mandates) = supported_payment_methods_for_update_mandate .0 .get(&payment_method) { if payment_method == enums::PaymentMethod::Card { if let Some(credit_connector_list) = supported_pm_for_mandates .0 .get(&api_enums::PaymentMethodType::Credit) { card_dir_values.extend( credit_connector_list .connector_list .clone() .into_iter() .filter_map(|connector| { api_enums::RoutableConnectors::from_str(connector.to_string().as_str()) .ok() .map(|connector| { dir::DirValue::Connector(Box::new( api_models::routing::ast::ConnectorChoice { connector }, )) }) }), ); } if let Some(debit_connector_list) = supported_pm_for_mandates .0 .get(&api_enums::PaymentMethodType::Debit) { card_dir_values.extend( debit_connector_list .connector_list .clone() .into_iter() .filter_map(|connector| { api_enums::RoutableConnectors::from_str(connector.to_string().as_str()) .ok() .map(|connector| { dir::DirValue::Connector(Box::new( api_models::routing::ast::ConnectorChoice { connector }, )) }) }), ); } let card_in_node = builder .make_in_aggregator(card_dir_values, None, None::<()>) .map_err(KgraphError::GraphConstructionError)?; let card_and_node = builder .make_all_aggregator( &[ ( card_value_node, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ( payment_type_value_node, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ( card_in_node, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ], None, None::<()>, Some(domain_id), ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( card_and_node, cgraph::Relation::Positive, cgraph::Strength::Strong, )); } else if let Some(connector_list) = supported_pm_for_mandates.0.get(&pmt.payment_method_type) { non_card_dir_values.extend( connector_list .connector_list .clone() .into_iter() .filter_map(|connector| { api_enums::RoutableConnectors::from_str(connector.to_string().as_str()) .ok() .map(|connector| { dir::DirValue::Connector(Box::new( api_models::routing::ast::ConnectorChoice { connector }, )) }) }), ); let non_card_mandate_in_node = builder .make_in_aggregator(non_card_dir_values, None, None::<()>) .map_err(KgraphError::GraphConstructionError)?; let non_card_and_node = builder .make_all_aggregator( &[ ( card_value_node, cgraph::Relation::Negative, cgraph::Strength::Strong, ), ( payment_type_value_node, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ( non_card_mandate_in_node, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ], None, None::<()>, Some(domain_id), ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( non_card_and_node, cgraph::Relation::Positive, cgraph::Strength::Strong, )); } } if !agg_nodes.is_empty() { Ok(Some( builder .make_any_aggregator( &agg_nodes, Some("any node for card and non card pm"), None::<()>, Some(domain_id), ) .map_err(KgraphError::GraphConstructionError)?, )) } else { Ok(None) } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 121, "total_crates": null }
fn_clm_router_compile_accepted_countries_for_mca_4451841960619737810
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/utils fn compile_accepted_countries_for_mca( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, domain_id: cgraph::DomainId, payment_method_type: enums::PaymentMethodType, pm_countries: Option<admin::AcceptedCountries>, config: &settings::ConnectorFilters, connector: String, ) -> Result<Option<cgraph::NodeId>, KgraphError> { let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); // Country from the MCA if let Some(pm_obj_countries) = pm_countries { match pm_obj_countries { admin::AcceptedCountries::EnableOnly(countries) => { let pm_object_country_value_node = builder .make_in_aggregator( countries .into_iter() .map(|country| { dir::DirValue::BillingCountry(common_enums::Country::from_alpha2( country, )) }) .collect(), None, None::<()>, ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( pm_object_country_value_node, cgraph::Relation::Positive, cgraph::Strength::Weak, )); } admin::AcceptedCountries::DisableOnly(countries) => { let pm_object_country_value_node = builder .make_in_aggregator( countries .into_iter() .map(|country| { dir::DirValue::BillingCountry(common_enums::Country::from_alpha2( country, )) }) .collect(), None, None::<()>, ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( pm_object_country_value_node, cgraph::Relation::Negative, cgraph::Strength::Weak, )); } admin::AcceptedCountries::AllAccepted => return Ok(None), } } // country from config if let Some(derived_config) = config .0 .get(connector.as_str()) .or_else(|| config.0.get("default")) { if let Some(value) = derived_config .0 .get(&settings::PaymentMethodFilterKey::PaymentMethodType( payment_method_type, )) { if let Some(config_countries) = value.country.as_ref() { let config_countries: Vec<common_enums::Country> = Vec::from_iter(config_countries) .into_iter() .map(|country| common_enums::Country::from_alpha2(*country)) .collect(); let dir_countries: Vec<dir::DirValue> = config_countries .into_iter() .map(dir::DirValue::BillingCountry) .collect(); let config_country_agg_node = builder .make_in_aggregator(dir_countries, None, None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( config_country_agg_node, cgraph::Relation::Positive, cgraph::Strength::Weak, )); } } else if let Some(default_derived_config) = config.0.get("default") { if let Some(value) = default_derived_config .0 .get(&settings::PaymentMethodFilterKey::PaymentMethodType( payment_method_type, )) { if let Some(config_countries) = value.country.as_ref() { let config_countries: Vec<common_enums::Country> = Vec::from_iter(config_countries) .into_iter() .map(|country| common_enums::Country::from_alpha2(*country)) .collect(); let dir_countries: Vec<dir::DirValue> = config_countries .into_iter() .map(dir::DirValue::BillingCountry) .collect(); let config_country_agg_node = builder .make_in_aggregator(dir_countries, None, None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( config_country_agg_node, cgraph::Relation::Positive, cgraph::Strength::Weak, )); } } }; } Ok(Some( builder .make_all_aggregator(&agg_nodes, None, None::<()>, Some(domain_id)) .map_err(KgraphError::GraphConstructionError)?, )) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 107, "total_crates": null }
fn_clm_router_compile_accepted_currency_for_mca_4451841960619737810
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/utils fn compile_accepted_currency_for_mca( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, domain_id: cgraph::DomainId, payment_method_type: enums::PaymentMethodType, pm_currency: Option<admin::AcceptedCurrencies>, config: &settings::ConnectorFilters, connector: String, ) -> Result<Option<cgraph::NodeId>, KgraphError> { let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); // Currency from the MCA if let Some(pm_obj_currency) = pm_currency { match pm_obj_currency { admin::AcceptedCurrencies::EnableOnly(currency) => { let pm_object_currency_value_node = builder .make_in_aggregator( currency .into_iter() .map(dir::DirValue::PaymentCurrency) .collect(), None, None::<()>, ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( pm_object_currency_value_node, cgraph::Relation::Positive, cgraph::Strength::Weak, )); } admin::AcceptedCurrencies::DisableOnly(currency) => { let pm_object_currency_value_node = builder .make_in_aggregator( currency .into_iter() .map(dir::DirValue::PaymentCurrency) .collect(), None, None::<()>, ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( pm_object_currency_value_node, cgraph::Relation::Negative, cgraph::Strength::Weak, )); } admin::AcceptedCurrencies::AllAccepted => return Ok(None), } } // currency from config if let Some(derived_config) = config .0 .get(connector.as_str()) .or_else(|| config.0.get("default")) { if let Some(value) = derived_config .0 .get(&settings::PaymentMethodFilterKey::PaymentMethodType( payment_method_type, )) { if let Some(config_currencies) = value.currency.as_ref() { let config_currency: Vec<common_enums::Currency> = Vec::from_iter(config_currencies) .into_iter() .copied() .collect(); let dir_currencies: Vec<dir::DirValue> = config_currency .into_iter() .map(dir::DirValue::PaymentCurrency) .collect(); let config_currency_agg_node = builder .make_in_aggregator(dir_currencies, None, None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( config_currency_agg_node, cgraph::Relation::Positive, cgraph::Strength::Weak, )); } } else if let Some(default_derived_config) = config.0.get("default") { if let Some(value) = default_derived_config .0 .get(&settings::PaymentMethodFilterKey::PaymentMethodType( payment_method_type, )) { if let Some(config_currencies) = value.currency.as_ref() { let config_currency: Vec<common_enums::Currency> = Vec::from_iter(config_currencies) .into_iter() .copied() .collect(); let dir_currencies: Vec<dir::DirValue> = config_currency .into_iter() .map(dir::DirValue::PaymentCurrency) .collect(); let config_currency_agg_node = builder .make_in_aggregator(dir_currencies, None, None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( config_currency_agg_node, cgraph::Relation::Positive, cgraph::Strength::Weak, )) } } }; } Ok(Some( builder .make_all_aggregator(&agg_nodes, None, None::<()>, Some(domain_id)) .map_err(KgraphError::GraphConstructionError)?, )) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 95, "total_crates": null }
fn_clm_router_compile_pm_graph_4451841960619737810
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/utils fn compile_pm_graph( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, domain_id: cgraph::DomainId, pm_enabled: PaymentMethodsEnabled, connector: String, config: &settings::ConnectorFilters, supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate, supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate, ) -> Result<(), KgraphError> { if let Some(payment_method_types) = pm_enabled.payment_method_types { for pmt in payment_method_types { let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); let mut agg_or_nodes_for_mandate_filters: Vec<( cgraph::NodeId, cgraph::Relation, cgraph::Strength, )> = Vec::new(); // Connector supported for Update mandate filter let res = construct_supported_connectors_for_update_mandate_node( builder, domain_id, supported_payment_methods_for_update_mandate, pmt.clone(), pm_enabled.payment_method, ); if let Ok(Some(connector_eligible_for_update_mandates_node)) = res { agg_or_nodes_for_mandate_filters.push(( connector_eligible_for_update_mandates_node, cgraph::Relation::Positive, cgraph::Strength::Strong, )) } // Connector supported for mandates filter if let Some(supported_pm_for_mandates) = supported_payment_methods_for_mandate .0 .get(&pm_enabled.payment_method) { if let Some(supported_connector_for_mandates) = supported_pm_for_mandates.0.get(&pmt.payment_method_type) { let supported_connectors: Vec<api_enums::Connector> = supported_connector_for_mandates .connector_list .clone() .into_iter() .collect(); if let Ok(Some(connector_eligible_for_mandates_node)) = construct_supported_connectors_for_mandate_node( builder, domain_id, supported_connectors, ) { agg_or_nodes_for_mandate_filters.push(( connector_eligible_for_mandates_node, cgraph::Relation::Positive, cgraph::Strength::Strong, )) } } } // Non Prominent Mandate flows let payment_type_non_mandate_value_node = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentType( euclid::enums::PaymentType::NonMandate, )), None, None::<()>, ); let payment_type_setup_mandate_value_node = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentType( euclid::enums::PaymentType::SetupMandate, )), None, None::<()>, ); let non_major_mandate_any_node = builder .make_any_aggregator( &[ ( payment_type_non_mandate_value_node, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ( payment_type_setup_mandate_value_node, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ], None, None::<()>, Some(domain_id), ) .map_err(KgraphError::GraphConstructionError)?; agg_or_nodes_for_mandate_filters.push(( non_major_mandate_any_node, cgraph::Relation::Positive, cgraph::Strength::Strong, )); let agg_or_node = builder .make_any_aggregator( &agg_or_nodes_for_mandate_filters, None, None::<()>, Some(domain_id), ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( agg_or_node, cgraph::Relation::Positive, cgraph::Strength::Strong, )); // Capture Method filter config .0 .get(connector.as_str()) .or_else(|| config.0.get("default")) .map(|inner| { if let Ok(Some(capture_method_filter)) = construct_capture_method_node(builder, inner, pmt.payment_method_type) { agg_nodes.push(( capture_method_filter, cgraph::Relation::Negative, cgraph::Strength::Strong, )) } }); // Country filter if let Ok(Some(country_node)) = compile_accepted_countries_for_mca( builder, domain_id, pmt.payment_method_type, pmt.accepted_countries, config, connector.clone(), ) { agg_nodes.push(( country_node, cgraph::Relation::Positive, cgraph::Strength::Strong, )) } // Currency filter if let Ok(Some(currency_node)) = compile_accepted_currency_for_mca( builder, domain_id, pmt.payment_method_type, pmt.accepted_currencies, config, connector.clone(), ) { agg_nodes.push(( currency_node, cgraph::Relation::Positive, cgraph::Strength::Strong, )) } let and_node_for_all_the_filters = builder .make_all_aggregator(&agg_nodes, None, None::<()>, Some(domain_id)) .map_err(KgraphError::GraphConstructionError)?; // Making our output node let pmt_info = "PaymentMethodType"; let dir_node: cgraph::NodeValue<dir::DirValue> = (pmt.payment_method_type, pm_enabled.payment_method) .into_dir_value() .map(Into::into)?; let payment_method_type_value_node = builder.make_value_node(dir_node, Some(pmt_info), None::<()>); builder .make_edge( and_node_for_all_the_filters, payment_method_type_value_node, cgraph::Strength::Normal, cgraph::Relation::Positive, Some(domain_id), ) .map_err(KgraphError::GraphConstructionError)?; } } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 91, "total_crates": null }
fn_clm_router_retrieve_payment_token_data_4451841960619737810
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/utils pub(super) async fn retrieve_payment_token_data( state: &SessionState, token: String, payment_method: Option<&storage_enums::PaymentMethod>, ) -> errors::RouterResult<storage::PaymentTokenData> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = format!( "pm_token_{}_{}_hyperswitch", token, payment_method .get_required_value("payment_method") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment method is required")? ); let token_data_string = redis_conn .get_key::<Option<String>>(&key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")? .ok_or(error_stack::Report::new( errors::ApiErrorResponse::UnprocessableEntity { message: "Token is invalid or expired".to_owned(), }, ))?; token_data_string .clone() .parse_struct("PaymentTokenData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to deserialize hyperswitch token data") }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 54, "total_crates": null }
fn_clm_router_new_-3479942182546320888
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize/card_executor // Inherent implementation for NetworkTokenizationBuilder<'a, TokenizeWithCard> pub fn new() -> Self { Self { state: std::marker::PhantomData, customer: None, card: None, card_cvc: None, network_token: None, stored_card: None, stored_token: None, payment_method_response: None, card_tokenized: false, error_code: None, error_message: None, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14463, "total_crates": null }
fn_clm_router_default_-3479942182546320888
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize/card_executor // Implementation of NetworkTokenizationBuilder<'_, TokenizeWithCard> for Default fn default() -> Self { Self::new() }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 7705, "total_crates": null }
fn_clm_router_build_-3479942182546320888
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize/card_executor // Implementation of None for NetworkTokenizationBuilder<'_, PaymentMethodCreated> pub fn build(self) -> api::CardNetworkTokenizeResponse { api::CardNetworkTokenizeResponse { payment_method_response: self.payment_method_response, customer: self.customer.cloned(), card_tokenized: self.card_tokenized, error_code: self.error_code.cloned(), error_message: self.error_message.cloned(), // Below field is mutated by caller functions for batched API operations tokenization_data: None, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 588, "total_crates": null }
fn_clm_router_create_customer_-3479942182546320888
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize/card_executor // Implementation of None for CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> pub async fn create_customer(&self) -> RouterResult<api::CustomerDetails> { let db = &*self.state.store; let customer_id = self .customer .customer_id .as_ref() .get_required_value("customer_id") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "customer_id", })?; let key_manager_state: &KeyManagerState = &self.state.into(); let encrypted_data = crypto_operation( key_manager_state, type_name!(domain::Customer), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.customer.name.clone(), email: self .customer .email .clone() .map(|email| email.expose().switch_strategy()), phone: self.customer.phone.clone(), tax_registration_id: self.customer.tax_registration_id.clone(), }, )), Identifier::Merchant(self.merchant_account.get_id().clone()), self.key_store.key.get_inner().peek(), ) .await .inspect_err(|err| logger::info!("Error encrypting customer: {:?}", err)) .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt customer")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form EncryptableCustomer")?; let new_customer_id = generate_customer_id_of_default_length(); let domain_customer = domain::Customer { customer_id: new_customer_id.clone(), merchant_id: self.merchant_account.get_id().clone(), name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { utils::Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ) }), phone: encryptable_customer.phone, description: None, phone_country_code: self.customer.phone_country_code.to_owned(), metadata: None, connector_customer: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), address_id: None, default_payment_method_id: None, updated_by: None, version: common_types::consts::API_VERSION, tax_registration_id: encryptable_customer.tax_registration_id, }; db.insert_customer( domain_customer, key_manager_state, self.key_store, self.merchant_account.storage_scheme, ) .await .inspect_err(|err| logger::info!("Error creating a customer: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to insert customer [id - {:?}] for merchant [id - {:?}]", customer_id, self.merchant_account.get_id() ) })?; Ok(api::CustomerDetails { id: new_customer_id, name: self.customer.name.clone(), email: self.customer.email.clone(), phone: self.customer.phone.clone(), phone_country_code: self.customer.phone_country_code.clone(), tax_registration_id: self.customer.tax_registration_id.clone(), }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 128, "total_crates": null }
fn_clm_router_create_payment_method_-3479942182546320888
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize/card_executor // Implementation of None for CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> pub async fn create_payment_method( &self, stored_locker_resp: &StoreLockerResponse, network_token_details: &NetworkTokenizationResponse, card_details: &domain::CardDetail, customer_id: &id_type::CustomerId, ) -> RouterResult<domain::PaymentMethod> { let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); // Form encrypted PM data (original card) let enc_pm_data = self.encrypt_card(card_details, true).await?; // Form encrypted network token data let enc_token_data = self .encrypt_network_token(network_token_details, card_details, true) .await?; // Form PM create entry let payment_method_create = api::PaymentMethodCreate { payment_method: Some(api_enums::PaymentMethod::Card), payment_method_type: card_details .card_type .as_ref() .and_then(|card_type| api_enums::PaymentMethodType::from_str(card_type).ok()), payment_method_issuer: card_details.card_issuer.clone(), payment_method_issuer_code: None, card: Some(api::CardDetail { card_number: card_details.card_number.clone(), card_exp_month: card_details.card_exp_month.clone(), card_exp_year: card_details.card_exp_year.clone(), card_holder_name: card_details.card_holder_name.clone(), nick_name: card_details.nick_name.clone(), card_issuing_country: card_details.card_issuing_country.clone(), card_network: card_details.card_network.clone(), card_issuer: card_details.card_issuer.clone(), card_type: card_details.card_type.clone(), }), metadata: None, customer_id: Some(customer_id.clone()), card_network: card_details .card_network .as_ref() .map(|network| network.to_string()), bank_transfer: None, wallet: None, client_secret: None, payment_method_data: None, billing: None, connector_mandate_details: None, network_transaction_id: None, }; PmCards { state: self.state, merchant_context: &domain::MerchantContext::NormalMerchant(Box::new(domain::Context( self.merchant_account.clone(), self.key_store.clone(), ))), } .create_payment_method( &payment_method_create, customer_id, &payment_method_id, Some(stored_locker_resp.store_card_resp.card_reference.clone()), self.merchant_account.get_id(), None, None, Some(enc_pm_data), None, None, None, None, None, network_token_details.1.clone(), Some(stored_locker_resp.store_token_resp.card_reference.clone()), Some(enc_token_data), Default::default(), // this method is used only for card bulk tokenization, and currently external vault is not supported for this hence passing Default i.e. InternalVault ) .await }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 97, "total_crates": null }
fn_clm_router_new_-7955007745940417854
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize/payment_method_executor // Inherent implementation for NetworkTokenizationBuilder<'a, TokenizeWithPmId> pub fn new() -> Self { Self { state: std::marker::PhantomData, customer: None, card: None, card_cvc: None, network_token: None, stored_card: None, stored_token: None, payment_method_response: None, card_tokenized: false, error_code: None, error_message: None, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14463, "total_crates": null }
fn_clm_router_default_-7955007745940417854
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize/payment_method_executor // Implementation of NetworkTokenizationBuilder<'_, TokenizeWithPmId> for Default fn default() -> Self { Self::new() }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 7705, "total_crates": null }
fn_clm_router_build_-7955007745940417854
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize/payment_method_executor // Implementation of None for NetworkTokenizationBuilder<'_, PmTokenUpdated> pub fn build(self) -> api::CardNetworkTokenizeResponse { api::CardNetworkTokenizeResponse { payment_method_response: self.payment_method_response, customer: self.customer.cloned(), card_tokenized: self.card_tokenized, error_code: self.error_code.cloned(), error_message: self.error_message.cloned(), // Below field is mutated by caller functions for batched API operations tokenization_data: None, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 588, "total_crates": null }
fn_clm_router_update_payment_method_-7955007745940417854
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize/payment_method_executor // Implementation of None for CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest> pub async fn update_payment_method( &self, store_token_response: &pm_transformers::StoreCardRespPayload, payment_method: domain::PaymentMethod, network_token_details: &NetworkTokenizationResponse, card_details: &domain::CardDetail, ) -> RouterResult<domain::PaymentMethod> { // Form encrypted network token data let enc_token_data = self .encrypt_network_token(network_token_details, card_details, true) .await?; // Update payment method let payment_method_update = diesel_models::PaymentMethodUpdate::NetworkTokenDataUpdate { network_token_requestor_reference_id: network_token_details.1.clone(), network_token_locker_id: Some(store_token_response.card_reference.clone()), network_token_payment_method_data: Some(enc_token_data.into()), }; self.state .store .update_payment_method( &self.state.into(), self.key_store, payment_method, payment_method_update, self.merchant_account.storage_scheme, ) .await .inspect_err(|err| logger::info!("Error updating payment method: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 112, "total_crates": null }
fn_clm_router_validate_request_and_locker_reference_and_customer_-7955007745940417854
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payment_methods/tokenize/payment_method_executor // Implementation of None for CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest> pub async fn validate_request_and_locker_reference_and_customer( &self, payment_method: &domain::PaymentMethod, ) -> RouterResult<(String, api::CustomerDetails)> { // Ensure customer ID matches let customer_id_in_req = self .customer .customer_id .clone() .get_required_value("customer_id") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "customer", })?; when(payment_method.customer_id != customer_id_in_req, || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Payment method does not belong to the customer".to_string() })) })?; // Ensure payment method is card match payment_method.payment_method { Some(api_enums::PaymentMethod::Card) => Ok(()), Some(_) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Payment method is not card".to_string() })), None => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Payment method is empty".to_string() })), }?; // Ensure card is not tokenized already when( payment_method .network_token_requestor_reference_id .is_some(), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Card is already tokenized".to_string() })) }, )?; // Ensure locker reference is present let locker_id = payment_method.locker_id.clone().ok_or(report!( errors::ApiErrorResponse::InvalidRequestData { message: "locker_id not found for given payment_method_id".to_string() } ))?; // Fetch customer let db = &*self.state.store; let key_manager_state: &KeyManagerState = &self.state.into(); let customer = db .find_customer_by_customer_id_merchant_id( key_manager_state, &payment_method.customer_id, self.merchant_account.get_id(), self.key_store, self.merchant_account.storage_scheme, ) .await .inspect_err(|err| logger::info!("Error fetching customer: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError)?; let customer_details = api::CustomerDetails { id: customer.customer_id.clone(), name: customer.name.clone().map(|name| name.into_inner()), email: customer.email.clone().map(Email::from), phone: customer.phone.clone().map(|phone| phone.into_inner()), phone_country_code: customer.phone_country_code.clone(), tax_registration_id: customer .tax_registration_id .clone() .map(|tax_registration_id| tax_registration_id.into_inner()), }; Ok((locker_id, customer_details)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 73, "total_crates": null }
fn_clm_router_from_234044935447468778
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/pm_auth/transformers // Implementation of pm_auth_types::MerchantRecipientData for From<types::MerchantRecipientData> fn from(value: types::MerchantRecipientData) -> Self { match value { types::MerchantRecipientData::ConnectorRecipientId(id) => { Self::ConnectorRecipientId(id) } types::MerchantRecipientData::WalletId(id) => Self::WalletId(id), types::MerchantRecipientData::AccountData(data) => Self::AccountData(data.into()), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2608, "total_crates": null }
fn_clm_router_foreign_try_from_234044935447468778
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/pm_auth/transformers // Implementation of pm_auth_types::ConnectorAuthType for ForeignTryFrom<types::ConnectorAuthType> fn foreign_try_from(auth_type: types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => { Ok::<Self, errors::ConnectorError>(Self::BodyKey { client_id: api_key.to_owned(), secret: key1.to_owned(), }) } _ => Err(errors::ConnectorError::FailedToObtainAuthType), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 432, "total_crates": null }
fn_clm_router_get_connector_auth_type_-2188866655124961505
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/pm_auth/helpers pub fn get_connector_auth_type( merchant_connector_account: domain::MerchantConnectorAccount, ) -> errors::CustomResult<pm_auth_types::ConnectorAuthType, ApiErrorResponse> { let auth_type: types::ConnectorAuthType = merchant_connector_account .connector_account_details .parse_value("ConnectorAuthType") .change_context(ApiErrorResponse::MerchantConnectorAccountNotFound { id: "ConnectorAuthType".to_string(), })?; pm_auth_types::ConnectorAuthType::foreign_try_from(auth_type) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed while converting ConnectorAuthType") }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 28, "total_crates": null }
fn_clm_router_foreign_try_from_2737323014464080863
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication/types // Implementation of PreAuthenticationData for ForeignTryFrom<&storage::Authentication> fn foreign_try_from(authentication: &storage::Authentication) -> Result<Self, Self::Error> { let error_message = errors::ApiErrorResponse::UnprocessableEntity { message: "Pre Authentication must be completed successfully before Authentication can be performed".to_string() }; let threeds_server_transaction_id = authentication .threeds_server_transaction_id .clone() .get_required_value("threeds_server_transaction_id") .change_context(error_message)?; let message_version = authentication .message_version .clone() .get_required_value("message_version")?; Ok(Self { threeds_server_transaction_id, message_version, acquirer_bin: authentication.acquirer_bin.clone(), acquirer_merchant_id: authentication.acquirer_merchant_id.clone(), acquirer_country_code: authentication.acquirer_country_code.clone(), connector_metadata: authentication.connector_metadata.clone(), }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 448, "total_crates": null }
fn_clm_router_foreign_from_7624915177292741042
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication/transformers // Implementation of common_enums::AuthenticationStatus for ForeignFrom<common_enums::TransactionStatus> fn foreign_from(trans_status: common_enums::TransactionStatus) -> Self { match trans_status { common_enums::TransactionStatus::Success => Self::Success, common_enums::TransactionStatus::Failure | common_enums::TransactionStatus::Rejected | common_enums::TransactionStatus::VerificationNotPerformed | common_enums::TransactionStatus::NotVerified => Self::Failed, common_enums::TransactionStatus::ChallengeRequired | common_enums::TransactionStatus::ChallengeRequiredDecoupledAuthentication | common_enums::TransactionStatus::InformationOnly => Self::Pending, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 212, "total_crates": null }
fn_clm_router_construct_router_data_7624915177292741042
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication/transformers pub fn construct_router_data<F: Clone, Req, Res>( state: &SessionState, authentication_connector_name: String, payment_method: PaymentMethod, merchant_id: common_utils::id_type::MerchantId, address: types::PaymentAddress, request_data: Req, merchant_connector_account: &payments_helpers::MerchantConnectorAccountType, psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, payment_id: common_utils::id_type::PaymentId, ) -> RouterResult<types::RouterData<F, Req, Res>> { let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(types::RouterData { flow: PhantomData, merchant_id, customer_id: None, tenant_id: state.tenant.tenant_id.clone(), connector_customer: None, connector: authentication_connector_name, payment_id: payment_id.get_string_repr().to_owned(), attempt_id: IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW.to_owned(), status: common_enums::AttemptStatus::default(), payment_method, payment_method_type: None, connector_auth_type: auth_type, description: None, address, auth_type: common_enums::AuthenticationType::NoThreeDs, connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_api_version: None, request: request_data, response: Err(types::ErrorResponse::default()), connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW.to_owned(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, dispute_id: None, refund_id: None, payment_method_status: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 75, "total_crates": null }
fn_clm_router_construct_post_authentication_router_data_7624915177292741042
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication/transformers pub fn construct_post_authentication_router_data( state: &SessionState, authentication_connector: String, business_profile: domain::Profile, merchant_connector_account: payments_helpers::MerchantConnectorAccountType, authentication_data: &storage::Authentication, payment_id: &common_utils::id_type::PaymentId, ) -> RouterResult<types::authentication::ConnectorPostAuthenticationRouterData> { let threeds_server_transaction_id = authentication_data .threeds_server_transaction_id .clone() .get_required_value("threeds_server_transaction_id") .change_context(errors::ApiErrorResponse::InternalServerError)?; let router_request = types::authentication::ConnectorPostAuthenticationRequestData { threeds_server_transaction_id, }; construct_router_data( state, authentication_connector, PaymentMethod::default(), business_profile.merchant_id.clone(), types::PaymentAddress::default(), router_request, &merchant_connector_account, None, payment_id.clone(), ) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 29, "total_crates": null }
fn_clm_router_construct_authentication_router_data_7624915177292741042
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication/transformers pub fn construct_authentication_router_data( state: &SessionState, merchant_id: common_utils::id_type::MerchantId, authentication_connector: String, payment_method_data: domain::PaymentMethodData, payment_method: PaymentMethod, billing_address: hyperswitch_domain_models::address::Address, shipping_address: Option<hyperswitch_domain_models::address::Address>, browser_details: Option<types::BrowserInformation>, amount: Option<common_utils::types::MinorUnit>, currency: Option<common_enums::Currency>, message_category: types::api::authentication::MessageCategory, device_channel: payments::DeviceChannel, merchant_connector_account: payments_helpers::MerchantConnectorAccountType, authentication_data: storage::Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, three_ds_requestor_url: String, psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, payment_id: common_utils::id_type::PaymentId, force_3ds_challenge: bool, ) -> RouterResult<types::authentication::ConnectorAuthenticationRouterData> { let router_request = types::authentication::ConnectorAuthenticationRequestData { payment_method_data, billing_address, shipping_address, browser_details, amount: amount.map(|amt| amt.get_amount_as_i64()), currency, message_category, device_channel, pre_authentication_data: super::types::PreAuthenticationData::foreign_try_from( &authentication_data, )?, return_url, sdk_information, email, three_ds_requestor_url, threeds_method_comp_ind, webhook_url, force_3ds_challenge, }; construct_router_data( state, authentication_connector, payment_method, merchant_id.clone(), types::PaymentAddress::default(), router_request, &merchant_connector_account, psd2_sca_exemption_type, payment_id, ) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 25, "total_crates": null }
fn_clm_router_construct_pre_authentication_router_data_7624915177292741042
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication/transformers pub fn construct_pre_authentication_router_data<F: Clone>( state: &SessionState, authentication_connector: String, card: hyperswitch_domain_models::payment_method_data::Card, merchant_connector_account: &payments_helpers::MerchantConnectorAccountType, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResult< types::RouterData< F, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, >, > { let router_request = types::authentication::PreAuthNRequestData { card }; construct_router_data( state, authentication_connector, PaymentMethod::default(), merchant_id, types::PaymentAddress::default(), router_request, merchant_connector_account, None, payment_id, ) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 22, "total_crates": null }
fn_clm_router_foreign_from_6007123552527809569
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication/utils // Implementation of common_enums::AttemptStatus for ForeignFrom<common_enums::AuthenticationStatus> fn foreign_from(from: common_enums::AuthenticationStatus) -> Self { match from { common_enums::AuthenticationStatus::Started | common_enums::AuthenticationStatus::Pending => Self::AuthenticationPending, common_enums::AuthenticationStatus::Success => Self::AuthenticationSuccessful, common_enums::AuthenticationStatus::Failed => Self::AuthenticationFailed, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 212, "total_crates": null }
fn_clm_router_update_trackers_6007123552527809569
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication/utils pub async fn update_trackers<F: Clone, Req>( state: &SessionState, router_data: RouterData<F, Req, AuthenticationResponseData>, authentication: storage::Authentication, acquirer_details: Option<super::types::AcquirerDetails>, merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> RouterResult<storage::Authentication> { let authentication_update = match router_data.response { Ok(response) => match response { AuthenticationResponseData::PreAuthNResponse { threeds_server_transaction_id, maximum_supported_3ds_version, connector_authentication_id, three_ds_method_data, three_ds_method_url, message_version, connector_metadata, directory_server_id, } => storage::AuthenticationUpdate::PreAuthenticationUpdate { threeds_server_transaction_id, maximum_supported_3ds_version, connector_authentication_id, three_ds_method_data, three_ds_method_url, message_version, connector_metadata, authentication_status: common_enums::AuthenticationStatus::Pending, acquirer_bin: acquirer_details .as_ref() .map(|acquirer_details| acquirer_details.acquirer_bin.clone()), acquirer_merchant_id: acquirer_details .as_ref() .map(|acquirer_details| acquirer_details.acquirer_merchant_id.clone()), acquirer_country_code: acquirer_details .and_then(|acquirer_details| acquirer_details.acquirer_country_code), directory_server_id, billing_address: None, shipping_address: None, browser_info: Box::new(None), email: None, }, AuthenticationResponseData::AuthNResponse { authn_flow_type, authentication_value, trans_status, connector_metadata, ds_trans_id, eci, challenge_code, challenge_cancel, challenge_code_reason, message_extension, } => { authentication_value .async_map(|auth_val| { crate::core::payment_methods::vault::create_tokenize( state, auth_val.expose(), None, authentication .authentication_id .get_string_repr() .to_string(), merchant_key_store.key.get_inner(), ) }) .await .transpose()?; let authentication_status = common_enums::AuthenticationStatus::foreign_from(trans_status.clone()); storage::AuthenticationUpdate::AuthenticationUpdate { trans_status, acs_url: authn_flow_type.get_acs_url(), challenge_request: authn_flow_type.get_challenge_request(), challenge_request_key: authn_flow_type.get_challenge_request_key(), acs_reference_number: authn_flow_type.get_acs_reference_number(), acs_trans_id: authn_flow_type.get_acs_trans_id(), acs_signed_content: authn_flow_type.get_acs_signed_content(), authentication_type: authn_flow_type.get_decoupled_authentication_type(), authentication_status, connector_metadata, ds_trans_id, eci, challenge_code, challenge_cancel, challenge_code_reason, message_extension, } } AuthenticationResponseData::PostAuthNResponse { trans_status, authentication_value, eci, challenge_cancel, challenge_code_reason, } => { authentication_value .async_map(|auth_val| { crate::core::payment_methods::vault::create_tokenize( state, auth_val.expose(), None, authentication .authentication_id .get_string_repr() .to_string(), merchant_key_store.key.get_inner(), ) }) .await .transpose()?; storage::AuthenticationUpdate::PostAuthenticationUpdate { authentication_status: common_enums::AuthenticationStatus::foreign_from( trans_status.clone(), ), trans_status, eci, challenge_cancel, challenge_code_reason, } } AuthenticationResponseData::PreAuthVersionCallResponse { maximum_supported_3ds_version, } => storage::AuthenticationUpdate::PreAuthenticationVersionCallUpdate { message_version: maximum_supported_3ds_version.clone(), maximum_supported_3ds_version, }, AuthenticationResponseData::PreAuthThreeDsMethodCallResponse { threeds_server_transaction_id, three_ds_method_data, three_ds_method_url, connector_metadata, } => storage::AuthenticationUpdate::PreAuthenticationThreeDsMethodCall { threeds_server_transaction_id, three_ds_method_data, three_ds_method_url, connector_metadata, acquirer_bin: acquirer_details .as_ref() .map(|acquirer_details| acquirer_details.acquirer_bin.clone()), acquirer_merchant_id: acquirer_details .map(|acquirer_details| acquirer_details.acquirer_merchant_id), }, }, Err(error) => storage::AuthenticationUpdate::ErrorUpdate { connector_authentication_id: error.connector_transaction_id, authentication_status: common_enums::AuthenticationStatus::Failed, error_message: error .reason .map(|reason| format!("message: {}, reason: {}", error.message, reason)) .or(Some(error.message)), error_code: Some(error.code), }, }; state .store .update_authentication_by_merchant_id_authentication_id( authentication, authentication_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while updating authentication") }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 147, "total_crates": null }
fn_clm_router_get_authentication_connector_data_6007123552527809569
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication/utils pub async fn get_authentication_connector_data( state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, authentication_connector: Option<String>, ) -> RouterResult<( common_enums::AuthenticationConnectors, payments::helpers::MerchantConnectorAccountType, )> { let authentication_connector = if let Some(authentication_connector) = authentication_connector { api_models::enums::convert_authentication_connector(&authentication_connector).ok_or( errors::ApiErrorResponse::UnprocessableEntity { message: format!( "Invalid authentication_connector found in request : {authentication_connector}", ), }, )? } else { let authentication_details = business_profile .authentication_connector_details .clone() .get_required_value("authentication_details") .change_context(errors::ApiErrorResponse::UnprocessableEntity { message: "authentication_connector_details is not available in business profile" .into(), }) .attach_printable("authentication_connector_details not configured by the merchant")?; authentication_details .authentication_connectors .first() .ok_or(errors::ApiErrorResponse::UnprocessableEntity { message: format!( "No authentication_connector found for profile_id {:?}", business_profile.get_id() ), }) .attach_printable( "No authentication_connector found from merchant_account.authentication_details", )? .to_owned() }; let profile_id = business_profile.get_id(); let authentication_connector_mca = payments::helpers::get_merchant_connector_account( state, &business_profile.merchant_id, None, key_store, profile_id, authentication_connector.to_string().as_str(), None, ) .await?; Ok((authentication_connector, authentication_connector_mca)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 64, "total_crates": null }
fn_clm_router_do_auth_connector_call_6007123552527809569
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication/utils pub async fn do_auth_connector_call<F, Req, Res>( state: &SessionState, authentication_connector_name: String, router_data: RouterData<F, Req, Res>, ) -> RouterResult<RouterData<F, Req, Res>> where Req: std::fmt::Debug + Clone + 'static, Res: std::fmt::Debug + Clone + 'static, F: std::fmt::Debug + Clone + 'static, dyn api::Connector + Sync: services::api::ConnectorIntegration<F, Req, Res>, dyn api::ConnectorV2 + Sync: services::api::ConnectorIntegrationV2<F, ExternalAuthenticationFlowData, Req, Res>, { let connector_data = api::AuthenticationConnectorData::get_connector_by_name(&authentication_connector_name)?; let connector_integration: services::BoxedExternalAuthenticationConnectorIntegrationInterface< F, Req, Res, > = connector_data.connector.get_connector_integration(); let router_data = execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payment_failed_response()?; Ok(router_data) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 42, "total_crates": null }
fn_clm_router_create_new_authentication_6007123552527809569
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/authentication/utils pub async fn create_new_authentication( state: &SessionState, merchant_id: common_utils::id_type::MerchantId, authentication_connector: String, token: String, profile_id: common_utils::id_type::ProfileId, payment_id: common_utils::id_type::PaymentId, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, organization_id: common_utils::id_type::OrganizationId, force_3ds_challenge: Option<bool>, psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, ) -> RouterResult<storage::Authentication> { let authentication_id = common_utils::id_type::AuthenticationId::generate_authentication_id( consts::AUTHENTICATION_ID_PREFIX, ); let authentication_client_secret = Some(common_utils::generate_id_with_default_len(&format!( "{}_secret", authentication_id.get_string_repr() ))); let new_authorization = storage::AuthenticationNew { authentication_id: authentication_id.clone(), merchant_id, authentication_connector: Some(authentication_connector), connector_authentication_id: None, payment_method_id: format!("eph_{token}"), authentication_type: None, authentication_status: common_enums::AuthenticationStatus::Started, authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused, error_message: None, error_code: None, connector_metadata: None, maximum_supported_version: None, threeds_server_transaction_id: None, cavv: None, authentication_flow_type: None, message_version: None, eci: None, trans_status: None, acquirer_bin: None, acquirer_merchant_id: None, three_ds_method_data: None, three_ds_method_url: None, acs_url: None, challenge_request: None, challenge_request_key: None, acs_reference_number: None, acs_trans_id: None, acs_signed_content: None, profile_id, payment_id: Some(payment_id), merchant_connector_id: Some(merchant_connector_id), ds_trans_id: None, directory_server_id: None, acquirer_country_code: None, service_details: None, organization_id, authentication_client_secret, force_3ds_challenge, psd2_sca_exemption_type, return_url: None, amount: None, currency: None, billing_address: None, shipping_address: None, browser_info: None, email: None, profile_acquirer_id: None, challenge_code: None, challenge_cancel: None, challenge_code_reason: None, message_extension: None, }; state .store .insert_authentication(new_authorization) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Authentication with authentication_id {} already exists", authentication_id.get_string_repr() ), }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 32, "total_crates": null }
fn_clm_router_foreign_from_7781009401758495064
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/transformers // Implementation of Vec<api::PayoutEnabledPaymentMethodsInfo> for ForeignFrom<( &PayoutRequiredFields, Vec<EnabledPaymentMethod>, api::RequiredFieldsOverrideRequest, )> fn foreign_from( (payout_required_fields, enabled_payout_methods, value_overrides): ( &PayoutRequiredFields, Vec<EnabledPaymentMethod>, api::RequiredFieldsOverrideRequest, ), ) -> Self { let value_overrides = value_overrides.flat_struct(); enabled_payout_methods .into_iter() .map(|enabled_payout_method| { let payment_method = enabled_payout_method.payment_method; let payment_method_types_info = enabled_payout_method .payment_method_types .into_iter() .filter_map(|pmt| { payout_required_fields .0 .get(&payment_method) .and_then(|pmt_info| { pmt_info.0.get(&pmt).map(|connector_fields| { let mut required_fields = HashMap::new(); for required_field_final in connector_fields.fields.values() { required_fields.extend(required_field_final.common.clone()); } for (key, value) in &value_overrides { required_fields.entry(key.to_string()).and_modify( |required_field| { required_field.value = Some(masking::Secret::new(value.to_string())); }, ); } api::PaymentMethodTypeInfo { payment_method_type: pmt, required_fields: if required_fields.is_empty() { None } else { Some(required_fields) }, } }) }) .or(Some(api::PaymentMethodTypeInfo { payment_method_type: pmt, required_fields: None, })) }) .collect(); api::PayoutEnabledPaymentMethodsInfo { payment_method, payment_method_types_info, } }) .collect() }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 256, "total_crates": null }
fn_clm_router_validate_create_request_-6772169996726593413
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/validator pub async fn validate_create_request( state: &SessionState, merchant_context: &domain::MerchantContext, req: &payouts::PayoutCreateRequest, ) -> RouterResult<( id_type::PayoutId, Option<payouts::PayoutMethodData>, id_type::ProfileId, Option<domain::Customer>, Option<PaymentMethod>, )> { if req.payout_method_id.is_some() && req.confirm != Some(true) { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Confirm must be true for recurring payouts".to_string(), })); } let merchant_id = merchant_context.get_merchant_account().get_id(); if let Some(payout_link) = &req.payout_link { if *payout_link { validate_payout_link_request(req)?; } }; // Merchant ID let predicate = req.merchant_id.as_ref().map(|mid| mid != merchant_id); utils::when(predicate.unwrap_or(false), || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), }) .attach_printable("invalid merchant_id in request")) })?; // Payout ID let db: &dyn StorageInterface = &*state.store; let payout_id = match req.payout_id.as_ref() { Some(provided_payout_id) => provided_payout_id.clone(), None => id_type::PayoutId::generate(), }; match validate_uniqueness_of_payout_id_against_merchant_id( db, &payout_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await .attach_printable_lazy(|| { format!( "Unique violation while checking payout_id: {payout_id:?} against merchant_id: {merchant_id:?}" ) })? { Some(_) => Err(report!(errors::ApiErrorResponse::DuplicatePayout { payout_id: payout_id.clone() })), None => Ok(()), }?; // Fetch customer details (merge of loose fields + customer object) and create DB entry let customer_in_request = helpers::get_customer_details_from_request(req); let customer = if customer_in_request.customer_id.is_some() || customer_in_request.name.is_some() || customer_in_request.email.is_some() || customer_in_request.phone.is_some() || customer_in_request.phone_country_code.is_some() { helpers::get_or_create_customer_details(state, &customer_in_request, merchant_context) .await? } else { None }; #[cfg(feature = "v1")] let profile_id = core_utils::get_profile_id_from_business_details( &state.into(), req.business_country, req.business_label.as_ref(), merchant_context, req.profile_id.as_ref(), &*state.store, false, ) .await?; #[cfg(feature = "v2")] // Profile id will be mandatory in v2 in the request / headers let profile_id = req .profile_id .clone() .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id", }) .attach_printable("Profile id is a mandatory parameter")?; let payment_method: Option<PaymentMethod> = match (req.payout_token.as_ref(), req.payout_method_id.clone()) { (Some(_), Some(_)) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Only one of payout_method_id or payout_token should be provided." .to_string(), })), (None, Some(payment_method_id)) => match customer.as_ref() { Some(customer) => { let payment_method = db .find_payment_method( &state.into(), merchant_context.get_merchant_key_store(), &payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("Unable to find payment method")?; utils::when(payment_method.customer_id != customer.customer_id, || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Payment method does not belong to this customer_id".to_string(), }) .attach_printable( "customer_id in payment_method does not match with customer_id in request", )) })?; Ok(Some(payment_method)) } None => Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "customer_id when payment_method_id is passed", })), }, _ => Ok(None), }?; // payout_token let payout_method_data = match ( req.payout_token.as_ref(), customer.as_ref(), payment_method.as_ref(), ) { (Some(_), None, _) => Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "customer or customer_id when payout_token is provided" })), (Some(payout_token), Some(customer), _) => { helpers::make_payout_method_data( state, req.payout_method_data.as_ref(), Some(payout_token), &customer.customer_id, merchant_context.get_merchant_account().get_id(), req.payout_type, merchant_context.get_merchant_key_store(), None, merchant_context.get_merchant_account().storage_scheme, ) .await } (_, Some(_), Some(payment_method)) => { // Check if we have a stored transfer_method_id first if payment_method .get_common_mandate_reference() .ok() .and_then(|common_mandate_ref| common_mandate_ref.payouts) .map(|payouts_mandate_ref| !payouts_mandate_ref.0.is_empty()) .unwrap_or(false) { Ok(None) } else { // No transfer_method_id available, proceed with vault fetch for raw card details match get_pm_list_context( state, payment_method .payment_method .as_ref() .get_required_value("payment_method_id")?, merchant_context.get_merchant_key_store(), payment_method, None, false, true, merchant_context, ) .await? { Some(pm) => match (pm.card_details, pm.bank_transfer_details) { (Some(card), _) => Ok(Some(payouts::PayoutMethodData::Card( api_models::payouts::CardPayout { card_number: card.card_number.get_required_value("card_number")?, card_holder_name: card.card_holder_name, expiry_month: card .expiry_month .get_required_value("expiry_month")?, expiry_year: card.expiry_year.get_required_value("expiry_year")?, }, ))), (_, Some(bank)) => Ok(Some(payouts::PayoutMethodData::Bank(bank))), _ => Ok(None), }, None => Ok(None), } } } _ => Ok(None), }?; Ok(( payout_id, payout_method_data, profile_id, customer, payment_method, )) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 141, "total_crates": null }
fn_clm_router_validate_payout_link_render_request_and_get_allowed_domains_-6772169996726593413
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/validator pub fn validate_payout_link_render_request_and_get_allowed_domains( request_headers: &header::HeaderMap, payout_link: &PayoutLink, ) -> RouterResult<HashSet<String>> { let link_id = payout_link.link_id.to_owned(); let link_data = payout_link.link_data.to_owned(); let is_test_mode_enabled = link_data.test_mode.unwrap_or(false); match (router_env_which(), is_test_mode_enabled) { // Throw error in case test_mode was enabled in production (Env::Production, true) => Err(report!(errors::ApiErrorResponse::LinkConfigurationError { message: "test_mode cannot be true for rendering payout_links in production" .to_string() })), // Skip all validations when test mode is enabled in non prod env (_, true) => Ok(HashSet::new()), // Otherwise, perform validations (_, false) => { // Fetch destination is "iframe" match request_headers.get("sec-fetch-dest").and_then(|v| v.to_str().ok()) { Some("iframe") => Ok(()), Some(requestor) => Err(report!(errors::ApiErrorResponse::AccessForbidden { resource: "payout_link".to_string(), })) .attach_printable_lazy(|| { format!( "Access to payout_link [{link_id}] is forbidden when requested through {requestor}", ) }), None => Err(report!(errors::ApiErrorResponse::AccessForbidden { resource: "payout_link".to_string(), })) .attach_printable_lazy(|| { format!( "Access to payout_link [{link_id}] is forbidden when sec-fetch-dest is not present in request headers", ) }), }?; // Validate origin / referer let domain_in_req = { let origin_or_referer = request_headers .get("origin") .or_else(|| request_headers.get("referer")) .and_then(|v| v.to_str().ok()) .ok_or_else(|| { report!(errors::ApiErrorResponse::AccessForbidden { resource: "payout_link".to_string(), }) }) .attach_printable_lazy(|| { format!( "Access to payout_link [{link_id}] is forbidden when origin or referer is not present in request headers", ) })?; let url = Url::parse(origin_or_referer) .map_err(|_| { report!(errors::ApiErrorResponse::AccessForbidden { resource: "payout_link".to_string(), }) }) .attach_printable_lazy(|| { format!("Invalid URL found in request headers {origin_or_referer}") })?; url.host_str() .and_then(|host| url.port().map(|port| format!("{host}:{port}"))) .or_else(|| url.host_str().map(String::from)) .ok_or_else(|| { report!(errors::ApiErrorResponse::AccessForbidden { resource: "payout_link".to_string(), }) }) .attach_printable_lazy(|| { format!("host or port not found in request headers {url:?}") })? }; if validate_domain_against_allowed_domains( &domain_in_req, link_data.allowed_domains.clone(), ) { Ok(link_data.allowed_domains) } else { Err(report!(errors::ApiErrorResponse::AccessForbidden { resource: "payout_link".to_string(), })) .attach_printable_lazy(|| { format!( "Access to payout_link [{link_id}] is forbidden from requestor - {domain_in_req}", ) }) } } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 81, "total_crates": null }
fn_clm_router_validate_uniqueness_of_payout_id_against_merchant_id_-6772169996726593413
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/validator pub async fn validate_uniqueness_of_payout_id_against_merchant_id( db: &dyn StorageInterface, payout_id: &id_type::PayoutId, merchant_id: &id_type::MerchantId, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<Option<storage::Payouts>> { let maybe_payouts = db .find_optional_payout_by_merchant_id_payout_id(merchant_id, payout_id, storage_scheme) .await; match maybe_payouts { Err(err) => { let storage_err = err.current_context(); match storage_err { StorageError::ValueNotFound(_) => Ok(None), _ => Err(err .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while finding payout_attempt, database error")), } } Ok(payout) => Ok(payout), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 21, "total_crates": null }
fn_clm_router_validate_payout_link_request_-6772169996726593413
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/validator pub fn validate_payout_link_request( req: &payouts::PayoutCreateRequest, ) -> Result<(), errors::ApiErrorResponse> { if req.confirm.unwrap_or(false) { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "cannot confirm a payout while creating a payout link".to_string(), }); } if req.customer_id.is_none() { return Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "customer or customer_id when payout_link is true", }); } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 19, "total_crates": null }
fn_clm_router_validate_payout_list_request_for_joins_-6772169996726593413
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/validator pub(super) fn validate_payout_list_request_for_joins( limit: u32, ) -> CustomResult<(), errors::ApiErrorResponse> { use common_utils::consts::PAYOUTS_LIST_MAX_LIMIT_POST; utils::when(!(1..=PAYOUTS_LIST_MAX_LIMIT_POST).contains(&limit), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("limit should be in between 1 and {PAYOUTS_LIST_MAX_LIMIT_POST}"), }) })?; Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 17, "total_crates": null }
fn_clm_router_add_access_token_for_payout_-4040006156366539849
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/access_token pub async fn add_access_token_for_payout<F: Clone + 'static>( state: &SessionState, connector: &api_types::ConnectorData, merchant_context: &domain::MerchantContext, router_data: &types::PayoutsRouterData<F>, payout_type: Option<enums::PayoutType>, ) -> RouterResult<types::AddAccessTokenResult> { use crate::types::api::ConnectorCommon; if connector .connector_name .supports_access_token_for_payout(payout_type) { let merchant_id = merchant_context.get_merchant_account().get_id(); let store = &*state.store; let old_access_token = store .get_access_token(merchant_id, connector.connector.id()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("DB error when accessing the access token")?; let res = match old_access_token { Some(access_token) => Ok(Some(access_token)), None => { let cloned_router_data = router_data.clone(); let refresh_token_request_data = types::AccessTokenRequestData::try_from( router_data.connector_auth_type.clone(), ) .attach_printable( "Could not create access token request, invalid connector account credentials", )?; let refresh_token_response_data: Result<types::AccessToken, types::ErrorResponse> = Err(types::ErrorResponse::default()); let refresh_token_router_data = payments::helpers::router_data_type_conversion::< _, api_types::AccessTokenAuth, _, _, _, _, >( cloned_router_data, refresh_token_request_data, refresh_token_response_data, ); refresh_connector_auth( state, connector, merchant_context, &refresh_token_router_data, ) .await? .async_map(|access_token| async { //Store the access token in db let store = &*state.store; // This error should not be propagated, we don't want payments to fail once we have // the access token, the next request will create new access token let _ = store .set_access_token( merchant_id, connector.connector.id(), access_token.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("DB error when setting the access token"); Some(access_token) }) .await } }; Ok(types::AddAccessTokenResult { access_token_result: res, connector_supports_access_token: true, }) } else { Ok(types::AddAccessTokenResult { access_token_result: Err(types::ErrorResponse::default()), connector_supports_access_token: false, }) } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 53, "total_crates": null }
fn_clm_router_refresh_connector_auth_-4040006156366539849
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/access_token pub async fn refresh_connector_auth( state: &SessionState, connector: &api_types::ConnectorData, _merchant_context: &domain::MerchantContext, router_data: &types::RouterData< api_types::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken, >, ) -> RouterResult<Result<types::AccessToken, types::ErrorResponse>> { let connector_integration: services::BoxedAccessTokenConnectorIntegrationInterface< api_types::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken, > = connector.connector.get_connector_integration(); let access_token_router_data_result = services::execute_connector_processing_step( state, connector_integration, router_data, payments::CallConnectorAction::Trigger, None, None, ) .await; let access_token_router_data = match access_token_router_data_result { Ok(router_data) => Ok(router_data.response), Err(connector_error) => { // If we receive a timeout error from the connector, then // the error has to be handled gracefully by updating the payment status to failed. // further payment flow will not be continued if connector_error.current_context().is_connector_timeout() { let error_response = types::ErrorResponse { code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(), message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(), reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()), status_code: 504, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }; Ok(Err(error_response)) } else { Err(connector_error .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not refresh access token")) } } }?; metrics::ACCESS_TOKEN_CREATION.add( 1, router_env::metric_attributes!(("connector", connector.connector_name.to_string())), ); Ok(access_token_router_data) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 36, "total_crates": null }
fn_clm_router_create_access_token_-4040006156366539849
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/access_token pub async fn create_access_token<F: Clone + 'static>( state: &SessionState, connector_data: &api_types::ConnectorData, merchant_context: &domain::MerchantContext, router_data: &mut types::PayoutsRouterData<F>, payout_type: Option<enums::PayoutType>, ) -> RouterResult<()> { let connector_access_token = add_access_token_for_payout( state, connector_data, merchant_context, router_data, payout_type, ) .await?; if connector_access_token.connector_supports_access_token { match connector_access_token.access_token_result { Ok(access_token) => { router_data.access_token = access_token; } Err(connector_error) => { router_data.response = Err(connector_error); } } } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 21, "total_crates": null }
fn_clm_router_update_payouts_and_payout_attempt_969660559739756258
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/helpers pub async fn update_payouts_and_payout_attempt( payout_data: &mut PayoutData, merchant_context: &domain::MerchantContext, req: &payouts::PayoutCreateRequest, state: &SessionState, ) -> CustomResult<(), errors::ApiErrorResponse> { let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; let payout_id = payout_attempt.payout_id.clone(); // Verify update feasibility if is_payout_terminal_state(status) || is_payout_initiated(status) { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Payout {} cannot be updated for status {status}", payout_id.get_string_repr() ), })); } // Fetch customer details from request and create new or else use existing customer that was attached let customer = get_customer_details_from_request(req); let customer_id = if customer.customer_id.is_some() || customer.name.is_some() || customer.email.is_some() || customer.phone.is_some() || customer.phone_country_code.is_some() { payout_data.customer_details = get_or_create_customer_details(state, &customer, merchant_context).await?; payout_data .customer_details .as_ref() .map(|customer| customer.customer_id.clone()) } else { payout_data.payouts.customer_id.clone() }; let (billing_address, address_id) = resolve_billing_address_for_payout( state, req.billing.as_ref(), payout_data.payouts.address_id.as_ref(), payout_data.payment_method.as_ref(), merchant_context, customer_id.as_ref(), &payout_id, ) .await?; // Update payout state with resolved billing address payout_data.billing_address = billing_address; // Update DB with new data let payouts = payout_data.payouts.to_owned(); let amount = MinorUnit::from(req.amount.unwrap_or(payouts.amount.into())); let updated_payouts = storage::PayoutsUpdate::Update { amount, destination_currency: req .currency .to_owned() .unwrap_or(payouts.destination_currency), source_currency: req.currency.to_owned().unwrap_or(payouts.source_currency), description: req .description .to_owned() .clone() .or(payouts.description.clone()), recurring: req.recurring.to_owned().unwrap_or(payouts.recurring), auto_fulfill: req.auto_fulfill.to_owned().unwrap_or(payouts.auto_fulfill), return_url: req .return_url .to_owned() .clone() .or(payouts.return_url.clone()), entity_type: req.entity_type.to_owned().unwrap_or(payouts.entity_type), metadata: req.metadata.clone().or(payouts.metadata.clone()), status: Some(status), profile_id: Some(payout_attempt.profile_id.clone()), confirm: req.confirm.to_owned(), payout_type: req .payout_type .to_owned() .or(payouts.payout_type.to_owned()), address_id: address_id.clone(), customer_id: customer_id.clone(), }; let db = &*state.store; payout_data.payouts = db .update_payout( &payouts, updated_payouts, &payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts")?; let updated_business_country = payout_attempt .business_country .map_or(req.business_country.to_owned(), |c| { req.business_country .to_owned() .and_then(|nc| if nc != c { Some(nc) } else { None }) }); let updated_business_label = payout_attempt .business_label .map_or(req.business_label.to_owned(), |l| { req.business_label .to_owned() .and_then(|nl| if nl != l { Some(nl) } else { None }) }); if updated_business_country.is_some() || updated_business_label.is_some() || customer_id.is_some() || address_id.is_some() { let payout_attempt = &payout_data.payout_attempt; let updated_payout_attempt = storage::PayoutAttemptUpdate::BusinessUpdate { business_country: updated_business_country, business_label: updated_business_label, address_id, customer_id, }; payout_data.payout_attempt = db .update_payout_attempt( payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt")?; } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 160, "total_crates": null }
fn_clm_router_decide_payout_connector_969660559739756258
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/helpers pub async fn decide_payout_connector( state: &SessionState, merchant_context: &domain::MerchantContext, request_straight_through: Option<api::routing::StraightThroughAlgorithm>, routing_data: &mut storage::RoutingData, payout_data: &mut PayoutData, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, ) -> RouterResult<api::ConnectorCallType> { // 1. For existing attempts, use stored connector let payout_attempt = &payout_data.payout_attempt; if let Some(connector_name) = payout_attempt.connector.clone() { // Connector was already decided previously, use the same connector let connector_data = api::ConnectorData::get_payout_connector_by_name( &state.conf.connectors, &connector_name, api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received in 'routed_through'")?; routing_data.routed_through = Some(connector_name.clone()); return Ok(api::ConnectorCallType::PreDetermined(connector_data.into())); } // Validate and get the business_profile from payout_attempt let business_profile = core_utils::validate_and_get_business_profile( state.store.as_ref(), &(state).into(), merchant_context.get_merchant_key_store(), Some(&payout_attempt.profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile")?; // 2. Check routing algorithm passed in the request if let Some(routing_algorithm) = request_straight_through { let (mut connectors, check_eligibility) = routing::perform_straight_through_routing(&routing_algorithm, None) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed execution of straight through routing")?; if check_eligibility { connectors = routing::perform_eligibility_analysis_with_fallback( state, merchant_context.get_merchant_key_store(), connectors, &TransactionData::Payout(payout_data), eligible_connectors, &business_profile, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; } let first_connector_choice = connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("Empty connector list returned")? .clone(); let connector_data = connectors .into_iter() .map(|conn| { api::ConnectorData::get_payout_connector_by_name( &state.conf.connectors, &conn.connector.to_string(), api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) .map(|connector_data| connector_data.into()) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; routing_data.routed_through = Some(first_connector_choice.connector.to_string()); routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id; routing_data.routing_info.algorithm = Some(routing_algorithm); return Ok(api::ConnectorCallType::Retryable(connector_data)); } // 3. Check algorithm passed in routing data if let Some(ref routing_algorithm) = routing_data.algorithm { let (mut connectors, check_eligibility) = routing::perform_straight_through_routing(routing_algorithm, None) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed execution of straight through routing")?; if check_eligibility { connectors = routing::perform_eligibility_analysis_with_fallback( state, merchant_context.get_merchant_key_store(), connectors, &TransactionData::Payout(payout_data), eligible_connectors, &business_profile, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; } let first_connector_choice = connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("Empty connector list returned")? .clone(); connectors.remove(0); let connector_data = connectors .into_iter() .map(|conn| { api::ConnectorData::get_payout_connector_by_name( &state.conf.connectors, &conn.connector.to_string(), api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) .map(|connector_data| connector_data.into()) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; routing_data.routed_through = Some(first_connector_choice.connector.to_string()); routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id; return Ok(api::ConnectorCallType::Retryable(connector_data)); } // 4. Route connector route_connector_v1_for_payouts( state, merchant_context, &payout_data.business_profile, payout_data, routing_data, eligible_connectors, ) .await }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 142, "total_crates": null }
fn_clm_router_get_or_create_customer_details_969660559739756258
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/helpers pub(super) async fn get_or_create_customer_details( state: &SessionState, customer_details: &CustomerDetails, merchant_context: &domain::MerchantContext, ) -> RouterResult<Option<domain::Customer>> { let db: &dyn StorageInterface = &*state.store; // Create customer_id if not passed in request let customer_id = customer_details .customer_id .clone() .unwrap_or_else(generate_customer_id_of_default_length); let merchant_id = merchant_context.get_merchant_account().get_id(); let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let key_manager_state = &state.into(); match db .find_customer_optional_by_customer_id_merchant_id( key_manager_state, &customer_id, merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)? { // Customer found Some(customer) => Ok(Some(customer)), // Customer not found // create only if atleast one of the fields were provided for customer creation or else throw error None => { if customer_details.name.is_some() || customer_details.email.is_some() || customer_details.phone.is_some() || customer_details.phone_country_code.is_some() { let encrypted_data = crypto_operation( &state.into(), type_name!(domain::Customer), CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: customer_details.name.clone(), email: customer_details .email .clone() .map(|a| a.expose().switch_strategy()), phone: customer_details.phone.clone(), tax_registration_id: customer_details.tax_registration_id.clone(), }, ), ), Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key, ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt customer")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form EncryptableCustomer")?; let customer = domain::Customer { customer_id: customer_id.clone(), merchant_id: merchant_id.to_owned().clone(), name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, description: None, phone_country_code: customer_details.phone_country_code.to_owned(), metadata: None, connector_customer: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), address_id: None, default_payment_method_id: None, updated_by: None, version: common_types::consts::API_VERSION, tax_registration_id: encryptable_customer.tax_registration_id, }; Ok(Some( db.insert_customer( customer, key_manager_state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to insert customer [id - {customer_id:?}] for merchant [id - {merchant_id:?}]", ) })?, )) } else { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!("customer for id - {customer_id:?} not found"), })) } } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 127, "total_crates": null }
fn_clm_router_make_payout_method_data_969660559739756258
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/helpers pub async fn make_payout_method_data( state: &SessionState, payout_method_data: Option<&api::PayoutMethodData>, payout_token: Option<&str>, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, payout_type: Option<api_enums::PayoutType>, merchant_key_store: &domain::MerchantKeyStore, payout_data: Option<&mut PayoutData>, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<Option<api::PayoutMethodData>> { let db = &*state.store; let hyperswitch_token = if let Some(payout_token) = payout_token { if payout_token.starts_with("temporary_token_") { Some(payout_token.to_string()) } else { let certain_payout_type = payout_type.get_required_value("payout_type")?.to_owned(); let key = format!( "pm_token_{}_{}_hyperswitch", payout_token, api_enums::PaymentMethod::foreign_from(certain_payout_type) ); let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let hyperswitch_token = redis_conn .get_key::<Option<String>>(&key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")? .ok_or(error_stack::Report::new( errors::ApiErrorResponse::UnprocessableEntity { message: "Token is invalid or expired".to_owned(), }, ))?; let payment_token_data = hyperswitch_token .clone() .parse_struct("PaymentTokenData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to deserialize hyperswitch token data")?; let payment_token = match payment_token_data { storage::PaymentTokenData::PermanentCard(storage::CardTokenData { locker_id, token, .. }) => locker_id.or(Some(token)), storage::PaymentTokenData::TemporaryGeneric(storage::GenericTokenData { token, }) => Some(token), _ => None, }; payment_token.or(Some(payout_token.to_string())) } } else { None }; match ( payout_method_data.to_owned(), hyperswitch_token, payout_data, ) { // Get operation (None, Some(payout_token), _) => { if payout_token.starts_with("temporary_token_") || payout_type == Some(api_enums::PayoutType::Bank) { let (pm, supplementary_data) = vault::Vault::get_payout_method_data_from_temporary_locker( state, &payout_token, merchant_key_store, ) .await .attach_printable( "Payout method for given token not found or there was a problem fetching it", )?; utils::when( supplementary_data .customer_id .ne(&Some(customer_id.to_owned())), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer associated with payout method and customer passed in payout are not same".into() }) }, )?; Ok(pm) } else { let resp = cards::get_card_from_locker( state, customer_id, merchant_id, payout_token.as_ref(), ) .await .attach_printable("Payout method [card] could not be fetched from HS locker")?; Ok(Some({ api::PayoutMethodData::Card(api::CardPayout { card_number: resp.card_number, expiry_month: resp.card_exp_month, expiry_year: resp.card_exp_year, card_holder_name: resp.name_on_card, }) })) } } // Create / Update operation (Some(payout_method), payout_token, Some(payout_data)) => { let lookup_key = vault::Vault::store_payout_method_data_in_locker( state, payout_token.to_owned(), payout_method, Some(customer_id.to_owned()), merchant_key_store, ) .await?; // Update payout_token in payout_attempt table if payout_token.is_none() { let updated_payout_attempt = storage::PayoutAttemptUpdate::PayoutTokenUpdate { payout_token: lookup_key, }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating token in payout attempt")?; } Ok(Some(payout_method.clone())) } // Ignore if nothing is passed _ => Ok(None), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 105, "total_crates": null }
fn_clm_router_get_additional_payout_data_969660559739756258
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/helpers pub async fn get_additional_payout_data( pm_data: &api::PayoutMethodData, db: &dyn StorageInterface, profile_id: &id_type::ProfileId, ) -> Option<payout_additional::AdditionalPayoutMethodData> { match pm_data { api::PayoutMethodData::Card(card_data) => { let card_isin = Some(card_data.card_number.get_card_isin()); let enable_extended_bin =db .find_config_by_key_unwrap_or( format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(), Some("false".to_string())) .await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok(); let card_extended_bin = match enable_extended_bin { Some(config) if config.config == "true" => { Some(card_data.card_number.get_extended_card_bin()) } _ => None, }; let last4 = Some(card_data.card_number.get_last4()); let card_info = card_isin .clone() .async_and_then(|card_isin| async move { db.get_card_info(&card_isin) .await .map_err(|error| services::logger::warn!(card_info_error=?error)) .ok() }) .await .flatten() .map(|card_info| { payout_additional::AdditionalPayoutMethodData::Card(Box::new( payout_additional::CardAdditionalData { card_issuer: card_info.card_issuer, card_network: card_info.card_network.clone(), bank_code: card_info.bank_code, card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, last4: last4.clone(), card_isin: card_isin.clone(), card_extended_bin: card_extended_bin.clone(), card_exp_month: Some(card_data.expiry_month.clone()), card_exp_year: Some(card_data.expiry_year.clone()), card_holder_name: card_data.card_holder_name.clone(), }, )) }); Some(card_info.unwrap_or_else(|| { payout_additional::AdditionalPayoutMethodData::Card(Box::new( payout_additional::CardAdditionalData { card_issuer: None, card_network: None, bank_code: None, card_type: None, card_issuing_country: None, last4, card_isin, card_extended_bin, card_exp_month: Some(card_data.expiry_month.clone()), card_exp_year: Some(card_data.expiry_year.clone()), card_holder_name: card_data.card_holder_name.clone(), }, )) })) } api::PayoutMethodData::Bank(bank_data) => { Some(payout_additional::AdditionalPayoutMethodData::Bank( Box::new(bank_data.to_owned().into()), )) } api::PayoutMethodData::Wallet(wallet_data) => { Some(payout_additional::AdditionalPayoutMethodData::Wallet( Box::new(wallet_data.to_owned().into()), )) } api::PayoutMethodData::BankRedirect(bank_redirect_data) => { Some(payout_additional::AdditionalPayoutMethodData::BankRedirect( Box::new(bank_redirect_data.to_owned().into()), )) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 100, "total_crates": null }
fn_clm_router_modify_trackers_4417491592573016356
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/retry pub async fn modify_trackers( state: &routes::SessionState, connector: &api::ConnectorData, merchant_context: &domain::MerchantContext, payout_data: &mut PayoutData, ) -> RouterResult<()> { let new_attempt_count = payout_data.payouts.attempt_count + 1; let db = &*state.store; // update payout table's attempt count let payouts = payout_data.payouts.to_owned(); let updated_payouts = storage::PayoutsUpdate::AttemptCountUpdate { attempt_count: new_attempt_count, }; let payout_id = payouts.payout_id.clone(); payout_data.payouts = db .update_payout( &payout_data.payouts, updated_payouts, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts")?; let payout_attempt_id = utils::get_payout_attempt_id( payout_id.get_string_repr(), payout_data.payouts.attempt_count, ); let payout_attempt_req = storage::PayoutAttemptNew { payout_attempt_id: payout_attempt_id.to_string(), payout_id: payout_id.to_owned(), merchant_order_reference_id: payout_data .payout_attempt .merchant_order_reference_id .clone(), customer_id: payout_data.payout_attempt.customer_id.to_owned(), connector: Some(connector.connector_name.to_string()), merchant_id: payout_data.payout_attempt.merchant_id.to_owned(), address_id: payout_data.payout_attempt.address_id.to_owned(), business_country: payout_data.payout_attempt.business_country.to_owned(), business_label: payout_data.payout_attempt.business_label.to_owned(), payout_token: payout_data.payout_attempt.payout_token.to_owned(), profile_id: payout_data.payout_attempt.profile_id.to_owned(), connector_payout_id: None, status: common_enums::PayoutStatus::default(), is_eligible: None, error_message: None, error_code: None, created_at: common_utils::date_time::now(), last_modified_at: common_utils::date_time::now(), merchant_connector_id: None, routing_info: None, unified_code: None, unified_message: None, additional_payout_method_data: payout_data .payout_attempt .additional_payout_method_data .to_owned(), payout_connector_metadata: None, }; payout_data.payout_attempt = db .insert_payout_attempt( payout_attempt_req, &payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayout { payout_id }) .attach_printable("Error inserting payouts in db")?; payout_data.merchant_connector_account = None; Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 70, "total_crates": null }
fn_clm_router_do_gsm_multiple_connector_actions_4417491592573016356
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/retry pub async fn do_gsm_multiple_connector_actions( state: &app::SessionState, mut connectors_routing_data: IntoIter<api::ConnectorRoutingData>, original_connector_data: api::ConnectorData, payout_data: &mut PayoutData, merchant_context: &domain::MerchantContext, ) -> RouterResult<()> { let mut retries = None; metrics::AUTO_PAYOUT_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]); let mut connector = original_connector_data; loop { let gsm = get_gsm(state, &connector, payout_data).await?; match get_gsm_decision(gsm) { common_enums::GsmDecision::Retry => { retries = get_retries( state, retries, merchant_context.get_merchant_account().get_id(), PayoutRetryType::MultiConnector, ) .await; if retries.is_none() || retries == Some(0) { metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]); logger::info!("retries exhausted for auto_retry payout"); break; } if connectors_routing_data.len() == 0 { logger::info!("connectors exhausted for auto_retry payout"); metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]); break; } connector = super::get_next_connector(&mut connectors_routing_data)?.connector_data; Box::pin(do_retry( &state.clone(), connector.to_owned(), merchant_context, payout_data, )) .await?; retries = retries.map(|i| i - 1); } common_enums::GsmDecision::DoDefault => break, } } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 45, "total_crates": null }
fn_clm_router_do_gsm_single_connector_actions_4417491592573016356
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/retry pub async fn do_gsm_single_connector_actions( state: &app::SessionState, original_connector_data: api::ConnectorData, payout_data: &mut PayoutData, merchant_context: &domain::MerchantContext, ) -> RouterResult<()> { let mut retries = None; metrics::AUTO_PAYOUT_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]); let mut previous_gsm = None; // to compare previous status loop { let gsm = get_gsm(state, &original_connector_data, payout_data).await?; // if the error config is same as previous, we break out of the loop if gsm == previous_gsm { break; } previous_gsm.clone_from(&gsm); match get_gsm_decision(gsm) { common_enums::GsmDecision::Retry => { retries = get_retries( state, retries, merchant_context.get_merchant_account().get_id(), PayoutRetryType::SingleConnector, ) .await; if retries.is_none() || retries == Some(0) { metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]); logger::info!("retries exhausted for auto_retry payment"); break; } Box::pin(do_retry( &state.clone(), original_connector_data.to_owned(), merchant_context, payout_data, )) .await?; retries = retries.map(|i| i - 1); } common_enums::GsmDecision::DoDefault => break, } } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 44, "total_crates": null }
fn_clm_router_get_gsm_4417491592573016356
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/retry pub async fn get_gsm( state: &app::SessionState, original_connector_data: &api::ConnectorData, payout_data: &PayoutData, ) -> RouterResult<Option<hyperswitch_domain_models::gsm::GatewayStatusMap>> { let error_code = payout_data.payout_attempt.error_code.to_owned(); let error_message = payout_data.payout_attempt.error_message.to_owned(); let connector_name = Some(original_connector_data.connector_name.to_string()); Ok(payouts::helpers::get_gsm_record( state, error_code, error_message, connector_name, common_utils::consts::PAYOUT_FLOW_STR, ) .await) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 39, "total_crates": null }
fn_clm_router_get_retries_4417491592573016356
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/core/payouts/retry pub async fn get_retries( state: &app::SessionState, retries: Option<i32>, merchant_id: &common_utils::id_type::MerchantId, retry_type: PayoutRetryType, ) -> Option<i32> { match retries { Some(retries) => Some(retries), None => { let key = merchant_id.get_max_auto_single_connector_payout_retries_enabled(retry_type); let db = &*state.store; db.find_config_by_key(key.as_str()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .and_then(|retries_config| { retries_config .config .parse::<i32>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Retries config parsing failed") }) .map_err(|err| { logger::error!(retries_error=?err); None::<i32> }) .ok() } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 37, "total_crates": null }
fn_clm_router_main_635691510048765676
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/bin/router async fn main() -> ApplicationResult<()> { // get commandline config before initializing config let cmd_line = <CmdLineConf as clap::Parser>::parse(); #[allow(clippy::expect_used)] let conf = Settings::with_config_path(cmd_line.config_path) .expect("Unable to construct application configuration"); #[allow(clippy::expect_used)] conf.validate() .expect("Failed to validate router configuration"); #[allow(clippy::print_stdout)] // The logger has not yet been initialized #[cfg(feature = "vergen")] { println!("Starting router (Version: {})", router_env::git_tag!()); } let _guard = router_env::setup( &conf.log, router_env::service_name!(), [router_env::service_name!(), "actix_server"], ) .change_context(ApplicationError::ConfigurationError)?; logger::info!("Application started [{:?}] [{:?}]", conf.server, conf.log); // Spawn a thread for collecting metrics at fixed intervals metrics::bg_metrics_collector::spawn_metrics_collector( conf.log.telemetry.bg_metrics_collection_interval_in_secs, ); #[allow(clippy::expect_used)] let server = Box::pin(router::start_server(conf)) .await .expect("Failed to create the server"); let _ = server.await; Err(error_stack::Report::from(ApplicationError::from( std::io::Error::other("Server shut down"), ))) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 22, "total_crates": null }
fn_clm_router_server_-3018535655044962742
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/bin/scheduler // Inherent implementation for Health pub fn server(state: routes::AppState, service: String) -> Scope { web::scope("health") .app_data(web::Data::new(state)) .app_data(web::Data::new(service)) .service(web::resource("").route(web::get().to(health))) .service(web::resource("/ready").route(web::get().to(deep_health_check))) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 234, "total_crates": null }
fn_clm_router_trigger_workflow_-3018535655044962742
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/bin/scheduler // Implementation of WorkflowRunner for ProcessTrackerWorkflows<routes::SessionState> async fn trigger_workflow<'a>( &'a self, state: &'a routes::SessionState, process: storage::ProcessTracker, ) -> CustomResult<(), ProcessTrackerError> { let runner = process .runner .clone() .get_required_value("runner") .change_context(ProcessTrackerError::MissingRequiredField) .attach_printable("Missing runner field in process information")?; let runner: storage::ProcessTrackerRunner = runner .parse_enum("ProcessTrackerRunner") .change_context(ProcessTrackerError::UnexpectedFlow) .attach_printable("Failed to parse workflow runner name")?; let get_operation = |runner: storage::ProcessTrackerRunner| -> CustomResult< Box<dyn ProcessTrackerWorkflow<routes::SessionState>>, ProcessTrackerError, > { match runner { storage::ProcessTrackerRunner::PaymentsSyncWorkflow => { Ok(Box::new(workflows::payment_sync::PaymentsSyncWorkflow)) } storage::ProcessTrackerRunner::RefundWorkflowRouter => { Ok(Box::new(workflows::refund_router::RefundWorkflowRouter)) } storage::ProcessTrackerRunner::ProcessDisputeWorkflow => { Ok(Box::new(workflows::process_dispute::ProcessDisputeWorkflow)) } storage::ProcessTrackerRunner::DisputeListWorkflow => { Ok(Box::new(workflows::dispute_list::DisputeListWorkflow)) } storage::ProcessTrackerRunner::InvoiceSyncflow => { Ok(Box::new(workflows::invoice_sync::InvoiceSyncWorkflow)) } storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow => Ok(Box::new( workflows::tokenized_data::DeleteTokenizeDataWorkflow, )), storage::ProcessTrackerRunner::ApiKeyExpiryWorkflow => { #[cfg(feature = "email")] { Ok(Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow)) } #[cfg(not(feature = "email"))] { Err(error_stack::report!(ProcessTrackerError::UnexpectedFlow)) .attach_printable( "Cannot run API key expiry workflow when email feature is disabled", ) } } storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow => Ok(Box::new( workflows::outgoing_webhook_retry::OutgoingWebhookRetryWorkflow, )), storage::ProcessTrackerRunner::AttachPayoutAccountWorkflow => { #[cfg(feature = "payouts")] { Ok(Box::new( workflows::attach_payout_account_workflow::AttachPayoutAccountWorkflow, )) } #[cfg(not(feature = "payouts"))] { Err( error_stack::report!(ProcessTrackerError::UnexpectedFlow), ) .attach_printable( "Cannot run Stripe external account workflow when payouts feature is disabled", ) } } storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow => Ok(Box::new( workflows::payment_method_status_update::PaymentMethodStatusUpdateWorkflow, )), storage::ProcessTrackerRunner::PassiveRecoveryWorkflow => { Ok(Box::new(workflows::revenue_recovery::ExecutePcrWorkflow)) } } }; let operation = get_operation(runner)?; let app_state = &state.clone(); let output = operation.execute_workflow(state, process.clone()).await; match output { Ok(_) => operation.success_handler(app_state, process).await, Err(error) => match operation .error_handler(app_state, process.clone(), error) .await { Ok(_) => (), Err(error) => { logger::error!(?error, "Failed while handling error"); let status = state .get_db() .as_scheduler() .finish_process_with_business_status( process, business_status::GLOBAL_FAILURE, ) .await; if let Err(error) = status { logger::error!( ?error, "Failed while performing database operation: {}", business_status::GLOBAL_FAILURE ); } } }, }; Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 71, "total_crates": null }
fn_clm_router_deep_health_check_-3018535655044962742
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/bin/scheduler pub async fn deep_health_check( state: web::Data<routes::AppState>, service: web::Data<String>, ) -> impl actix_web::Responder { let mut checks = HashMap::new(); let stores = state.stores.clone(); let app_state = Arc::clone(&state.into_inner()); let service_name = service.into_inner(); for (tenant, _) in stores { let session_state_res = app_state.clone().get_session_state(&tenant, None, || { errors::ApiErrorResponse::MissingRequiredField { field_name: "tenant_id", } .into() }); let session_state = match session_state_res { Ok(state) => state, Err(err) => { return api::log_and_return_error_response(err); } }; let report = deep_health_check_func(session_state, &service_name).await; match report { Ok(response) => { checks.insert( tenant, serde_json::to_string(&response) .map_err(|err| { logger::error!(serialization_error=?err); }) .unwrap_or_default(), ); } Err(err) => { return api::log_and_return_error_response(err); } } } services::http_response_json( serde_json::to_string(&checks) .map_err(|err| { logger::error!(serialization_error=?err); }) .unwrap_or_default(), ) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 69, "total_crates": null }
fn_clm_router_start_web_server_-3018535655044962742
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/bin/scheduler pub async fn start_web_server( state: routes::AppState, service: String, ) -> errors::ApplicationResult<Server> { let server = state .conf .scheduler .as_ref() .ok_or(ApplicationError::InvalidConfigurationValueError( "Scheduler server is invalidly configured".into(), ))? .server .clone(); let web_server = actix_web::HttpServer::new(move || { actix_web::App::new().service(Health::server(state.clone(), service.clone())) }) .bind((server.host.as_str(), server.port)) .change_context(ApplicationError::ConfigurationError)? .workers(server.workers) .run(); let _ = web_server.handle(); Ok(web_server) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 50, "total_crates": null }
fn_clm_router_deep_health_check_func_-3018535655044962742
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/bin/scheduler pub async fn deep_health_check_func( state: routes::SessionState, service: &str, ) -> errors::RouterResult<SchedulerHealthCheckResponse> { logger::info!("{} deep health check was called", service); logger::debug!("Database health check begin"); let db_status = state .health_check_db() .await .map(|_| true) .map_err(|error| { let message = error.to_string(); error.change_context(errors::ApiErrorResponse::HealthCheckError { component: "Database", message, }) })?; logger::debug!("Database health check end"); logger::debug!("Redis health check begin"); let redis_status = state .health_check_redis() .await .map(|_| true) .map_err(|error| { let message = error.to_string(); error.change_context(errors::ApiErrorResponse::HealthCheckError { component: "Redis", message, }) })?; let outgoing_req_check = state .health_check_outgoing() .await .map(|_| true) .map_err(|error| { let message = error.to_string(); error.change_context(errors::ApiErrorResponse::HealthCheckError { component: "Outgoing Request", message, }) })?; logger::debug!("Redis health check end"); let response = SchedulerHealthCheckResponse { database: db_status, redis: redis_status, outgoing_request: outgoing_req_check, }; Ok(response) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 49, "total_crates": null }
fn_clm_router_error_handler_4690911191646960160
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/tokenized_data // Implementation of DeleteTokenizeDataWorkflow for ProcessTrackerWorkflow<SessionState> async fn error_handler<'a>( &'a self, _state: &'a SessionState, process: storage::ProcessTracker, _error: errors::ProcessTrackerError, ) -> errors::CustomResult<(), errors::ProcessTrackerError> { error!(%process.id, "Failed while executing workflow"); Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14, "total_crates": null }
fn_clm_router_execute_workflow_4690911191646960160
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/tokenized_data // Implementation of DeleteTokenizeDataWorkflow for ProcessTrackerWorkflow<SessionState> async fn execute_workflow<'a>( &'a self, _state: &'a SessionState, _process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { todo!() }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 11, "total_crates": null }
fn_clm_router_error_handler_3232750204786826196
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/invoice_sync // Implementation of InvoiceSyncWorkflow for ProcessTrackerWorkflow<SessionState> async fn error_handler<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, error: errors::ProcessTrackerError, ) -> CustomResult<(), errors::ProcessTrackerError> { logger::error!("Encountered error"); consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 18, "total_crates": null }
fn_clm_router_execute_workflow_3232750204786826196
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/invoice_sync // Implementation of InvoiceSyncWorkflow for ProcessTrackerWorkflow<SessionState> async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 11, "total_crates": null }
fn_clm_router_execute_workflow_-8828535211125747946
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/process_dispute // Implementation of ProcessDisputeWorkflow for ProcessTrackerWorkflow<SessionState> async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), sch_errors::ProcessTrackerError> { let db: &dyn StorageInterface = &*state.store; let tracking_data: api::ProcessDisputePTData = process .tracking_data .clone() .parse_value("ProcessDisputePTData")?; let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &tracking_data.merchant_id, &db.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &tracking_data.merchant_id, &key_store, ) .await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); let payment_attempt = get_payment_attempt_from_object_reference_id( state, tracking_data.dispute_payload.object_reference_id.clone(), &merchant_context, ) .await?; let business_profile = state .store .find_business_profile_by_profile_id( &(state).into(), merchant_context.get_merchant_key_store(), &payment_attempt.profile_id, ) .await?; // Check if the dispute already exists let dispute = state .store .find_by_merchant_id_payment_id_connector_dispute_id( merchant_context.get_merchant_account().get_id(), &payment_attempt.payment_id, &tracking_data.dispute_payload.connector_dispute_id, ) .await .ok() .flatten(); if dispute.is_some() { // Dispute already exists — mark the process as complete state .store .as_scheduler() .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT) .await?; } else { // Update dispute data let response = disputes::update_dispute_data( state, merchant_context, business_profile, dispute, tracking_data.dispute_payload, payment_attempt, tracking_data.connector_name.as_str(), ) .await .map_err(|error| logger::error!("Dispute update failed: {error}")); match response { Ok(_) => { state .store .as_scheduler() .finish_process_with_business_status( process, business_status::COMPLETED_BY_PT, ) .await?; } Err(_) => { retry_sync_task( db, tracking_data.connector_name, tracking_data.merchant_id, process, ) .await?; } } } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 77, "total_crates": null }
fn_clm_router_t_sync_process_schedule_time( _-8828535211125747946
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/process_dispute b async fn get_sync_process_schedule_time( db: &dyn StorageInterface, connector: &str, merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let mapping: common_utils::errors::CustomResult< process_data::ConnectorPTMapping, errors::StorageError, > = db .find_config_by_key(&format!("pt_mapping_{connector}")) .await .map(|value| value.config) .and_then(|config| { config .parse_struct("ConnectorPTMapping") .change_context(errors::StorageError::DeserializationFailed) }); let mapping = match mapping { Ok(x) => x, Err(error) => { logger::info!(?error, "Redis Mapping Error"); process_data::ConnectorPTMapping::default() } }; let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count); Ok(scheduler_utils::get_time_from_delta(time_delta)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 18, "total_crates": null }
fn_clm_router_try_sync_task( _-8828535211125747946
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/process_dispute b async fn retry_sync_task( db: &dyn StorageInterface, connector: String, merchant_id: common_utils::id_type::MerchantId, pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError> { let schedule_time = get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?; match schedule_time { Some(s_time) => { db.as_scheduler().retry_process(pt, s_time).await?; Ok(false) } None => { db.as_scheduler() .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) .await?; Ok(true) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 17, "total_crates": null }
fn_clm_router_ror_handler<'_-8828535211125747946
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/process_dispute // Implementation of ProcessDisputeWorkflow for ProcessTrackerWorkflow<SessionState> ync fn error_handler<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, error: sch_errors::ProcessTrackerError, ) -> errors::CustomResult<(), sch_errors::ProcessTrackerError> { consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 12, "total_crates": null }
fn_clm_router_execute_workflow_3210603694367187153
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/api_key_expiry // Implementation of ApiKeyExpiryWorkflow for ProcessTrackerWorkflow<SessionState> async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let db = &*state.store; let tracking_data: ApiKeyExpiryTrackingData = process .tracking_data .clone() .parse_value("ApiKeyExpiryTrackingData")?; let key_manager_satte = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_satte, &tracking_data.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_satte, &tracking_data.merchant_id, &key_store, ) .await?; let email_id = merchant_account .merchant_details .clone() .parse_value::<api::MerchantDetails>("MerchantDetails")? .primary_email .ok_or(errors::ProcessTrackerError::EValidationError( ValidationError::MissingRequiredField { field_name: "email".to_string(), } .into(), ))?; let task_id = process.id.clone(); let retry_count = process.retry_count; let api_key_name = tracking_data.api_key_name.clone(); let prefix = tracking_data.prefix.clone(); let expires_in = tracking_data .expiry_reminder_days .get( usize::try_from(retry_count) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)?, ) .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; let theme = theme_utils::get_most_specific_theme_using_lineage( state, ThemeLineage::Merchant { tenant_id: state.tenant.tenant_id.clone(), org_id: merchant_account.get_org_id().clone(), merchant_id: merchant_account.get_id().clone(), }, ) .await .map_err(|err| { logger::error!(?err, "Failed to get theme"); errors::ProcessTrackerError::EApiErrorResponse })?; let email_contents = ApiKeyExpiryReminder { recipient_email: UserEmail::from_pii_email(email_id).map_err(|error| { logger::error!( ?error, "Failed to convert recipient's email to UserEmail from pii::Email" ); errors::ProcessTrackerError::EApiErrorResponse })?, subject: consts::EMAIL_SUBJECT_API_KEY_EXPIRY, expires_in: *expires_in, api_key_name, prefix, theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; state .email_client .clone() .compose_and_send_email( user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .map_err(errors::ProcessTrackerError::EEmailError)?; // If all the mails have been sent, then retry_count would be equal to length of the expiry_reminder_days vector if retry_count == i32::try_from(tracking_data.expiry_reminder_days.len() - 1) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)? { state .get_db() .as_scheduler() .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT) .await? } // If tasks are remaining that has to be scheduled else { let expiry_reminder_day = tracking_data .expiry_reminder_days .get( usize::try_from(retry_count + 1) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)?, ) .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; let updated_schedule_time = tracking_data.api_key_expiry.map(|api_key_expiry| { api_key_expiry.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) }); let updated_process_tracker_data = storage::ProcessTrackerUpdate::Update { name: None, retry_count: Some(retry_count + 1), schedule_time: updated_schedule_time, tracking_data: None, business_status: None, status: Some(storage_enums::ProcessTrackerStatus::New), updated_at: Some(common_utils::date_time::now()), }; let task_ids = vec![task_id]; db.process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data) .await?; // Remaining tasks are re-scheduled, so will be resetting the added count metrics::TASKS_RESET_COUNT .add(1, router_env::metric_attributes!(("flow", "ApiKeyExpiry"))); } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 129, "total_crates": null }
fn_clm_router_error_handler_3210603694367187153
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/api_key_expiry // Implementation of ApiKeyExpiryWorkflow for ProcessTrackerWorkflow<SessionState> async fn error_handler<'a>( &'a self, _state: &'a SessionState, process: storage::ProcessTracker, _error: errors::ProcessTrackerError, ) -> errors::CustomResult<(), errors::ProcessTrackerError> { error!(%process.id, "Failed while executing workflow"); Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14, "total_crates": null }