text
string
file_path
string
module
string
type
string
tokens
int64
language
string
struct_name
string
type_name
string
trait_name
string
impl_type
string
function_name
string
source
string
section
string
keys
list
macro_type
string
url
string
title
string
chunk_index
int64
impl std::ops::DerefMut for PaymentsMandateReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
crates/hyperswitch_domain_models/src/mandates.rs
hyperswitch_domain_models
impl_block
41
rust
null
PaymentsMandateReference
std::ops::DerefMut for
impl std::ops::DerefMut for for PaymentsMandateReference
null
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.TouchNGoRedirection { "type": "object" }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
23
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "TouchNGoRedirection" ]
null
null
null
null
pub fn is_four_decimal_currency(self) -> bool { match self { Self::CLF => true, Self::AED | Self::AFN | Self::ALL | Self::AMD | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN | Self::BAM | Self::BBD | Self::BDT | Self::BGN | Self::BHD | Self::BIF | Self::BMD | Self::BND | Self::BOB | Self::BRL | Self::BSD | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD | Self::CDF | Self::CHF | Self::CLP | Self::CNY | Self::COP | Self::CRC | Self::CUC | Self::CUP | Self::CVE | Self::CZK | Self::DJF | Self::DKK | Self::DOP | Self::DZD | Self::EGP | Self::ERN | Self::ETB | Self::EUR | Self::FJD | Self::FKP | Self::GBP | Self::GEL | Self::GHS | Self::GIP | Self::GMD | Self::GNF | Self::GTQ | Self::GYD | Self::HKD | Self::HNL | Self::HRK | Self::HTG | Self::HUF | Self::IDR | Self::ILS | Self::INR | Self::IQD | Self::IRR | Self::ISK | Self::JMD | Self::JOD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF | Self::KPW | Self::KRW | Self::KWD | Self::KYD | Self::KZT | Self::LAK | Self::LBP | Self::LKR | Self::LRD | Self::LSL | Self::LYD | Self::MAD | Self::MDL | Self::MGA | Self::MKD | Self::MMK | Self::MNT | Self::MOP | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD | Self::OMR | Self::PAB | Self::PEN | Self::PGK | Self::PHP | Self::PKR | Self::PLN | Self::PYG | Self::QAR | Self::RON | Self::RSD | Self::RUB | Self::RWF | Self::SAR | Self::SBD | Self::SCR | Self::SDG | Self::SEK | Self::SGD | Self::SHP | Self::SLE | Self::SLL | Self::SOS | Self::SRD | Self::SSP | Self::STD | Self::STN | Self::SVC | Self::SYP | Self::SZL | Self::THB | Self::TJS | Self::TMT | Self::TND | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS | Self::VES | Self::VND | Self::VUV | Self::WST | Self::XAF | Self::XCD | Self::XPF | Self::XOF | Self::YER | Self::ZAR | Self::ZMW | Self::ZWL => false, } }
crates/common_enums/src/enums.rs
common_enums
function_signature
1,121
rust
null
null
null
null
is_four_decimal_currency
null
null
null
null
null
null
null
impl api::RefundSync for Barclaycard {}
crates/hyperswitch_connectors/src/connectors/barclaycard.rs
hyperswitch_connectors
impl_block
11
rust
null
Barclaycard
api::RefundSync for
impl api::RefundSync for for Barclaycard
null
null
null
null
null
null
null
null
impl api::Payment for Checkout {}
crates/hyperswitch_connectors/src/connectors/checkout.rs
hyperswitch_connectors
impl_block
7
rust
null
Checkout
api::Payment for
impl api::Payment for for Checkout
null
null
null
null
null
null
null
null
pub struct RedirectUrl { pub return_url: Option<String>, pub url: Option<String>, }
crates/router/src/compatibility/stripe/payment_intents/types.rs
router
struct_definition
21
rust
RedirectUrl
null
null
null
null
null
null
null
null
null
null
null
pub struct GetSsoAuthUrlRequest { pub id: String, }
crates/api_models/src/user.rs
api_models
struct_definition
16
rust
GetSsoAuthUrlRequest
null
null
null
null
null
null
null
null
null
null
null
let business_profile_new = admin::create_profile_from_merchant_account(state, merchant_account, request, key_store) .await?; let profile_name = business_profile_new.profile_name.clone(); state .store .insert_business_profile(&state.into(), key_store, business_profile_new) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Business Profile with the profile_name {profile_name} already exists" ), }) .attach_printable("Failed to insert Business profile because of duplication error") } #[cfg(feature = "olap")] #[async_trait::async_trait] trait ProfileCreateBridge { #[cfg(feature = "v1")] async fn create_domain_model_from_request( self, state: &SessionState, merchant_context: &domain::MerchantContext, ) -> RouterResult<domain::Profile>; #[cfg(feature = "v2")] async fn create_domain_model_from_request( self, state: &SessionState, key: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, ) -> RouterResult<domain::Profile>; } #[cfg(feature = "olap")] #[async_trait::async_trait] impl ProfileCreateBridge for api::ProfileCreate { #[cfg(feature = "v1")] async fn create_domain_model_from_request( self, state: &SessionState, merchant_context: &domain::MerchantContext, ) -> RouterResult<domain::Profile> { use common_utils::ext_traits::AsyncExt; if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } if let Some(intent_fulfillment_expiry) = self.intent_fulfillment_time { helpers::validate_intent_fulfillment_expiry(intent_fulfillment_expiry)?; } if let Some(ref routing_algorithm) = self.routing_algorithm { let _: api_models::routing::StaticRoutingAlgorithm = routing_algorithm .clone() .parse_value("RoutingAlgorithm") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; } // Generate a unique profile id let profile_id = common_utils::generate_profile_id_of_default_length(); let profile_name = self.profile_name.unwrap_or("default".to_string()); let current_time = date_time::now(); let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let payment_response_hash_key = self .payment_response_hash_key .or(merchant_context .get_merchant_account() .payment_response_hash_key .clone()) .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), headers, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(error_stack::report!( errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() } )), }) .transpose()?; let key = merchant_context .get_merchant_key_store() .key .clone() .into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); let card_testing_guard_config = self .card_testing_guard_config .map(CardTestingGuardConfig::foreign_from) .or(Some(CardTestingGuardConfig::default())); let mut dynamic_routing_algorithm_ref = routing_types::DynamicRoutingAlgorithmRef::default(); if self.is_debit_routing_enabled == Some(true) { routing::helpers::create_merchant_in_decision_engine_if_not_exists( state, &profile_id, &mut dynamic_routing_algorithm_ref, ) .await; } let dynamic_routing_algorithm = serde_json::to_value(dynamic_routing_algorithm_ref) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error serializing dynamic_routing_algorithm_ref to JSON Value")?; self.merchant_country_code .as_ref() .map(|country_code| country_code.validate_and_get_country_from_merchant_country_code()) .transpose() .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid merchant country code".to_string(), })?; Ok(domain::Profile::from(domain::ProfileSetter { profile_id, merchant_id: merchant_context.get_merchant_account().get_id().clone(), profile_name, created_at: current_time, modified_at: current_time, return_url: self .return_url .map(|return_url| return_url.to_string()) .or(merchant_context.get_merchant_account().return_url.clone()), enable_payment_response_hash: self.enable_payment_response_hash.unwrap_or( merchant_context .get_merchant_account() .enable_payment_response_hash, ), payment_response_hash_key: Some(payment_response_hash_key), redirect_to_merchant_with_http_post: self .redirect_to_merchant_with_http_post .unwrap_or( merchant_context .get_merchant_account() .redirect_to_merchant_with_http_post, ), webhook_details: webhook_details.or(merchant_context .get_merchant_account() .webhook_details .clone()), metadata: self.metadata, routing_algorithm: None, intent_fulfillment_time: self .intent_fulfillment_time .map(i64::from) .or(merchant_context .get_merchant_account() .intent_fulfillment_time) .or(Some(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME)), frm_routing_algorithm: self.frm_routing_algorithm.or(merchant_context .get_merchant_account() .frm_routing_algorithm .clone()), #[cfg(feature = "payouts")] payout_routing_algorithm: self.payout_routing_algorithm.or(merchant_context .get_merchant_account() .payout_routing_algorithm .clone()), #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, is_recon_enabled: merchant_context.get_merchant_account().is_recon_enabled, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self .session_expiry .map(i64::from) .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, is_extended_card_info_enabled: None, extended_card_info_config: None, use_billing_as_payment_method_billing: self .use_billing_as_payment_method_billing .or(Some(true)), collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector .or(Some(false)), collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector .or(Some(false)), outgoing_webhook_custom_http_headers, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: self.is_tax_connector_enabled, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, dynamic_routing_algorithm: Some(dynamic_routing_algorithm), is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_auto_retries_enabled: self.is_auto_retries_enabled.unwrap_or_default(), max_auto_retries_enabled: self.max_auto_retries_enabled.map(i16::from), always_request_extended_authorization: self.always_request_extended_authorization, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, card_testing_guard_config, card_testing_secret_key: card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")?, is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled.unwrap_or_default(), force_3ds_challenge: self.force_3ds_challenge.unwrap_or_default(), is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, is_pre_network_tokenization_enabled: self .is_pre_network_tokenization_enabled .unwrap_or_default(), merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, dispute_polling_interval: self.dispute_polling_interval, is_manual_retry_enabled: self.is_manual_retry_enabled, })) } #[cfg(feature = "v2")] async fn create_domain_model_from_request( self, state: &SessionState, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, ) -> RouterResult<domain::Profile> { if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } // Generate a unique profile id // TODO: the profile_id should be generated from the profile_name let profile_id = common_utils::generate_profile_id_of_default_length(); let profile_name = self.profile_name; let current_time = date_time::now(); let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let payment_response_hash_key = self .payment_response_hash_key .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data(&key_manager_state, key_store, headers) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(error_stack::report!( errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() } )), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); let card_testing_guard_config = self .card_testing_guard_config .map(CardTestingGuardConfig::foreign_from) .or(Some(CardTestingGuardConfig::default())); Ok(domain::Profile::from(domain::ProfileSetter { id: profile_id, merchant_id: merchant_id.clone(), profile_name, created_at: current_time, modified_at: current_time, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash.unwrap_or(true), payment_response_hash_key: Some(payment_response_hash_key), redirect_to_merchant_with_http_post: self .redirect_to_merchant_with_http_post .unwrap_or(true), webhook_details, metadata: self.metadata, is_recon_enabled: false, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self .session_expiry .map(i64::from) .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, is_extended_card_info_enabled: None, extended_card_info_config: None, use_billing_as_payment_method_billing: self .use_billing_as_payment_method_billing .or(Some(true)), collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector_if_required .or(Some(false)), collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector_if_required .or(Some(false)), outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, routing_algorithm_id: None, frm_routing_algorithm_id: None, payout_routing_algorithm_id: None, order_fulfillment_time: self .order_fulfillment_time .map(|order_fulfillment_time| order_fulfillment_time.into_inner()) .or(Some(common_utils::consts::DEFAULT_ORDER_FULFILLMENT_TIME)), order_fulfillment_time_origin: self.order_fulfillment_time_origin, default_fallback_routing: None, should_collect_cvv_during_payment: None, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: self.is_tax_connector_enabled, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, three_ds_decision_manager_config: None, card_testing_guard_config, card_testing_secret_key: card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")?, is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled.unwrap_or_default(), is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: self.merchant_business_country, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, is_iframe_redirection_enabled: None, is_external_vault_enabled: self.is_external_vault_enabled, external_vault_connector_details: self .external_vault_connector_details .map(ForeignInto::foreign_into), merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, split_txns_enabled: self.split_txns_enabled.unwrap_or_default(), })) } } #[cfg(feature = "olap")] pub async fn create_profile( state: SessionState, request: api::ProfileCreate, merchant_context: domain::MerchantContext, ) -> RouterResponse<api_models::admin::ProfileResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); #[cfg(feature = "v1")] let business_profile = request .create_domain_model_from_request(&state, &merchant_context) .await?; #[cfg(feature = "v2")] let business_profile = request .create_domain_model_from_request( &state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().get_id(), ) .await?; let profile_id = business_profile.get_id().to_owned(); let business_profile = db .insert_business_profile( key_manager_state, merchant_context.get_merchant_key_store(), business_profile, ) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Business Profile with the profile_id {} already exists", profile_id.get_string_repr() ), }) .attach_printable("Failed to insert Business profile because of duplication error")?; #[cfg(feature = "v1")] if merchant_context .get_merchant_account() .default_profile .is_some() { let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile; db.update_merchant( key_manager_state, merchant_context.get_merchant_account().clone(), unset_default_profile, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; } Ok(service_api::ApplicationResponse::Json( api_models::admin::ProfileResponse::foreign_try_from(business_profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?, )) } #[cfg(feature = "olap")] pub async fn list_profile( state: SessionState, merchant_id: id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, ) -> RouterResponse<Vec<api_models::admin::ProfileResponse>> { let db = state.store.as_ref(); let key_store = db .get_merchant_key_store_by_merchant_id( &(&state).into(), &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let profiles = db .list_profile_by_merchant_id(&(&state).into(), &key_store, &merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)? .clone(); let profiles = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, profiles); let mut business_profiles = Vec::new(); for profile in profiles { let business_profile = api_models::admin::ProfileResponse::foreign_try_from(profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?; business_profiles.push(business_profile); } Ok(service_api::ApplicationResponse::Json(business_profiles)) } pub async fn retrieve_profile( state: SessionState, profile_id: id_type::ProfileId, key_store: domain::MerchantKeyStore, ) -> RouterResponse<api_models::admin::ProfileResponse> { let db = state.store.as_ref(); let business_profile = db .find_business_profile_by_profile_id(&(&state).into(), &key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(service_api::ApplicationResponse::Json( api_models::admin::ProfileResponse::foreign_try_from(business_profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?, )) } pub async fn delete_profile( state: SessionState, profile_id: id_type::ProfileId, merchant_id: &id_type::MerchantId, ) -> RouterResponse<bool> { let db = state.store.as_ref(); let delete_result = db .delete_profile_by_profile_id_merchant_id(&profile_id, merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(service_api::ApplicationResponse::Json(delete_result)) } #[cfg(feature = "olap")] #[async_trait::async_trait] trait ProfileUpdateBridge { async fn get_update_profile_object( self, state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, ) -> RouterResult<domain::ProfileUpdate>; } #[cfg(all(feature = "olap", feature = "v1"))] #[async_trait::async_trait] impl ProfileUpdateBridge for api::ProfileUpdate { async fn get_update_profile_object( self, state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, ) -> RouterResult<domain::ProfileUpdate> { if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } if let Some(intent_fulfillment_expiry) = self.intent_fulfillment_time { helpers::validate_intent_fulfillment_expiry(intent_fulfillment_expiry)?; } let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); if let Some(ref routing_algorithm) = self.routing_algorithm { let _: api_models::routing::StaticRoutingAlgorithm = routing_algorithm .clone() .parse_value("RoutingAlgorithm") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; } let payment_link_config = self .payment_link_config .map(|payment_link_conf| match payment_link_conf.validate() { Ok(_) => Ok(payment_link_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let extended_card_info_config = self .extended_card_info_config .as_ref() .map(|config| { config.encode_to_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "extended_card_info_config", }, ) }) .transpose()? .map(Secret::new); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data(&key_manager_state, key_store, headers) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = match business_profile.card_testing_secret_key { Some(_) => None, None => { let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")? } }; let dynamic_routing_algo_ref = if self.is_debit_routing_enabled == Some(true) { let mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile .dynamic_routing_algorithm .clone() .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize dynamic routing algorithm ref from business profile", )? .unwrap_or_default(); routing::helpers::create_merchant_in_decision_engine_if_not_exists( state, business_profile.get_id(), &mut dynamic_routing_algo_ref, ) .await; let dynamic_routing_algo_ref_value = serde_json::to_value(dynamic_routing_algo_ref) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "error serializing dynamic_routing_algorithm_ref to JSON Value", )?; Some(dynamic_routing_algo_ref_value) } else { self.dynamic_routing_algorithm }; self.merchant_country_code .as_ref() .map(|country_code| country_code.validate_and_get_country_from_merchant_country_code()) .transpose() .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid merchant country code".to_string(), })?; Ok(domain::ProfileUpdate::Update(Box::new( domain::ProfileGeneralUpdate { profile_name: self.profile_name, return_url: self.return_url.map(|return_url| return_url.to_string()), enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, webhook_details, metadata: self.metadata, routing_algorithm: self.routing_algorithm, intent_fulfillment_time: self.intent_fulfillment_time.map(i64::from), frm_routing_algorithm: self.frm_routing_algorithm, #[cfg(feature = "payouts")] payout_routing_algorithm: self.payout_routing_algorithm, #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self.session_expiry.map(i64::from), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, extended_card_info_config, use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, always_request_extended_authorization: self.always_request_extended_authorization, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: self.is_tax_connector_enabled, dynamic_routing_algorithm: dynamic_routing_algo_ref, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_auto_retries_enabled: self.is_auto_retries_enabled, max_auto_retries_enabled: self.max_auto_retries_enabled.map(i16::from), is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, card_testing_guard_config: self .card_testing_guard_config .map(ForeignInto::foreign_into), card_testing_secret_key, is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled, force_3ds_challenge: self.force_3ds_challenge, // is_debit_routing_enabled: self.is_debit_routing_enabled, merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, is_pre_network_tokenization_enabled: self.is_pre_network_tokenization_enabled, merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, dispute_polling_interval: self.dispute_polling_interval, is_manual_retry_enabled: self.is_manual_retry_enabled, }, ))) } } #[cfg(all(feature = "olap", feature = "v2"))] #[async_trait::async_trait] impl ProfileUpdateBridge for api::ProfileUpdate { async fn get_update_profile_object( self, state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, ) -> RouterResult<domain::ProfileUpdate> { if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let payment_link_config = self .payment_link_config .map(|payment_link_conf| match payment_link_conf.validate() { Ok(_) => Ok(payment_link_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let extended_card_info_config = self .extended_card_info_config .as_ref() .map(|config| { config.encode_to_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "extended_card_info_config", }, ) }) .transpose()? .map(Secret::new); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data(&key_manager_state, key_store, headers) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = match business_profile.card_testing_secret_key { Some(_) => None, None => { let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")? } }; let revenue_recovery_retry_algorithm_type = self.revenue_recovery_retry_algorithm_type; Ok(domain::ProfileUpdate::Update(Box::new( domain::ProfileGeneralUpdate { profile_name: self.profile_name, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, webhook_details, metadata: self.metadata, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self.session_expiry.map(i64::from), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, extended_card_info_config, use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector_if_required, collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector_if_required, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers, order_fulfillment_time: self .order_fulfillment_time .map(|order_fulfillment_time| order_fulfillment_time.into_inner()), order_fulfillment_time_origin: self.order_fulfillment_time_origin, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, three_ds_decision_manager_config: None, card_testing_guard_config: self .card_testing_guard_config .map(ForeignInto::foreign_into), card_testing_secret_key, is_debit_routing_enabled: self.is_debit_routing_enabled, merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: None, is_external_vault_enabled: self.is_external_vault_enabled, external_vault_connector_details: self .external_vault_connector_details .map(ForeignInto::foreign_into), merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, revenue_recovery_retry_algorithm_type, split_txns_enabled: self.split_txns_enabled, }, ))) } } #[cfg(feature = "olap")] pub async fn update_profile( state: SessionState, profile_id: &id_type::ProfileId, key_store: domain::MerchantKeyStore, request: api::ProfileUpdate, ) -> RouterResponse<api::ProfileResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let profile_update = request .get_update_profile_object(&state, &key_store, &business_profile) .await?; let updated_business_profile = db .update_profile_by_profile_id( key_manager_state, &key_store, business_profile, profile_update, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(service_api::ApplicationResponse::Json( api_models::admin::ProfileResponse::foreign_try_from(updated_business_profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?, )) } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct ProfileWrapper { pub profile: domain::Profile, } #[cfg(feature = "v2")] impl ProfileWrapper { pub fn new(profile: domain::Profile) -> Self { Self { profile } } fn get_routing_config_cache_key(self) -> storage_impl::redis::cache::CacheKind<'static> { let merchant_id = self.profile.merchant_id.clone(); let profile_id = self.profile.get_id().to_owned(); storage_impl::redis::cache::CacheKind::Routing( format!( "routing_config_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr() ) .into(), ) } pub async fn update_profile_and_invalidate_routing_config_for_active_algorithm_id_update( self, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, algorithm_id: id_type::RoutingId, transaction_type: &storage::enums::TransactionType, ) -> RouterResult<()> { let routing_cache_key = self.clone().get_routing_config_cache_key(); let (routing_algorithm_id, payout_routing_algorithm_id) = match transaction_type { storage::enums::TransactionType::Payment => (Some(algorithm_id), None), #[cfg(feature = "payouts")] storage::enums::TransactionType::Payout => (None, Some(algorithm_id)), //TODO: Handle ThreeDsAuthentication Transaction Type for Three DS Decision Rule Algorithm configuration storage::enums::TransactionType::ThreeDsAuthentication => todo!(), }; let profile_update = domain::ProfileUpdate::RoutingAlgorithmUpdate { routing_algorithm_id, payout_routing_algorithm_id, };
crates/router/src/core/admin.rs#chunk3
router
chunk
8,192
null
null
null
null
null
null
null
null
null
null
null
null
null
/// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() }
crates/common_utils/src/id_type/global_id/refunds.rs
common_utils
function_signature
31
rust
null
null
null
null
get_string_repr
null
null
null
null
null
null
null
pub struct SetupMandate;
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
hyperswitch_domain_models
struct_definition
7
rust
SetupMandate
null
null
null
null
null
null
null
null
null
null
null
pub async fn get_auth_events_filter_for_dimension<T>( dimension: AuthEventDimensions, auth: &AuthInfo, time_range: &TimeRange, pool: &T, ) -> FiltersResult<Vec<AuthEventFilterRow>> where T: AnalyticsDataSource + AuthEventFilterAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); query_builder.add_select_column(dimension).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; query_builder.set_distinct(); auth.set_filter_clause(&mut query_builder).switch()?; query_builder .execute_query::<AuthEventFilterRow, _>(pool) .await .change_context(FiltersError::QueryBuildingError)? .change_context(FiltersError::QueryExecutionFailure) }
crates/analytics/src/auth_events/filters.rs
analytics
function_signature
243
rust
null
null
null
null
get_auth_events_filter_for_dimension
null
null
null
null
null
null
null
impl api::PaymentVoid for Klarna {}
crates/hyperswitch_connectors/src/connectors/klarna.rs
hyperswitch_connectors
impl_block
9
rust
null
Klarna
api::PaymentVoid for
impl api::PaymentVoid for for Klarna
null
null
null
null
null
null
null
null
Documentation: config/deployments/README.md # Type: Doc File # Configs for deployments ## Introduction This directory contains the configs for deployments of Hyperswitch in different hosted environments. Hyperswitch has **3** components namely, - router - drainer - scheduler - consumer - producer We maintain configs for the `router` component for 3 different environments, namely, - Integration Test - Sandbox - Production To learn about what "router", "drainer" and "scheduler" is, please refer to the [Hyperswitch architecture][architecture] documentation. ### Tree structure ```text config/deployments # Root directory for the deployment configs ├── README.md # This file ├── drainer.toml # Config specific to drainer ├── env_specific.toml # Config for environment specific values which are meant to be sensitive (to be set by the user) ├── integration_test.toml # Config specific to integration_test environment ├── production.toml # Config specific to production environment ├── sandbox.toml # Config specific to sandbox environment └── scheduler # Directory for scheduler configs ├── consumer.toml # Config specific to consumer └── producer.toml # Config specific to producer ``` ## Router The `integration_test.toml`, `sandbox.toml`, and `production.toml` files are configuration files for the environments `integration_test`, `sandbox`, and `production`, respectively. These files maintain a 1:1 mapping with the environment names, and it is recommended to use the same name for the environment throughout this document. ### Generating a Config File for the Router The `env_specific.toml` file contains values that are specific to the environment. This file is kept separate because the values in it are sensitive and are meant to be set by the user. The `env_specific.toml` file is merged with the `integration_test.toml`, `sandbox.toml`, or `production.toml` file to create the final configuration file for the router. For example, to build and deploy Hyperswitch in the **sandbox environment**, you can duplicate the `env_specific.toml` file and rename it as `sandbox_config.toml`. Then, update the values in the file with the proper values for the sandbox environment. The environment-specific `sandbox.toml` file, which contains the Hyperswitch recommended defaults, is merged with the `sandbox_config.toml` file to create the final configuration file called `sandbox_release.toml`. This file is marked as ready for deploying on the sandbox environment. 1. Duplicate the `env_specific.toml` file and rename it as `sandbox_config.toml`: ```shell cp config/deployments/env_specific.toml config/deployments/sandbox_config.toml ``` 2. Update the values in the `sandbox_config.toml` file with the proper values for the sandbox environment: ```shell vi config/deployments/sandbox_config.toml ``` 3. To merge the files you can use `cat`: ```shell cat config/deployments/sandbox.toml config/deployments/sandbox_config.toml > config/deployments/sandbox_release.toml ``` > [!NOTE] > You can refer to the [`config.example.toml`][config_example] file to understand the variables that used are in the `env_specific.toml` file. ## Scheduler The scheduler has two components, namely `consumer` and `producer`. The `consumer.toml` and `producer.toml` files are the configuration files for the `consumer` and `producer`, respectively. These files contain the default values recommended by Hyperswitch. ### Generating a Config File for the Scheduler Scheduler configuration files are built on top of the router configuration files. So, the `sandbox_release.toml` file is merged with the `consumer.toml` or `producer.toml` file to create the final configuration file for the scheduler. You can use `cat` to merge the files in the terminal. - Below is an example for consumer in sandbox environment: ```shell cat config/deployments/scheduler/consumer.toml config/deployments/sandbox_release.toml > config/deployments/consumer_sandbox_release.toml ``` - Below is an example for producer in sandbox environment: ```shell cat config/deployments/scheduler/producer.toml config/deployments/sandbox_release.toml > config/deployments/producer_sandbox_release.toml ``` ## Drainer Drainer is an independent component, and hence, the drainer configs can be used directly provided that the user updates the `drainer.toml` file with proper values before using. ## Running Hyperswitch through Docker Compose To run the router, you can use the following snippet in the `docker-compose.yml` file: ```yaml ### Application services hyperswitch-server: image: docker.juspay.io/juspaydotin/hyperswitch-router:latest # This pulls the latest image from Docker Hub. If you wish to use a version without added features (like KMS), you can replace `latest` with `standalone`. However, please note that the standalone version is not recommended for production use. command: /local/bin/router --config-path /local/config/deployments/sandbox_release.toml # <--- Change this to the config file that is generated for the environment. ports: - "8080:8080" volumes: - ./config:/local/config ``` To run the producer, you can use the following snippet in the `docker-compose.yml` file: ```yaml hyperswitch-producer: image: docker.juspay.io/juspaydotin/hyperswitch-producer:latest command: /local/bin/scheduler --config-path /local/config/deployments/producer_sandbox_release.toml # <--- Change this to the config file that is generated for the environment. volumes: - ./config:/local/config environment: - SCHEDULER_FLOW=producer ``` To run the consumer, you can use the following snippet in the `docker-compose.yml` file: ```yaml hyperswitch-consumer: image: docker.juspay.io/juspaydotin/hyperswitch-consumer:latest command: /local/bin/scheduler --config-path /local/config/deployments/consumer_sandbox_release.toml # <--- Change this to the config file that is generated for the environment volumes: - ./config:/local/config environment: - SCHEDULER_FLOW=consumer ``` To run the drainer, you can use the following snippet in the `docker-compose.yml` file: ```yaml hyperswitch-drainer: image: docker.juspay.io/juspaydotin/hyperswitch-drainer:latest command: /local/bin/drainer --config-path /local/config/deployments/drainer.toml volumes: - ./config:/local/config ``` > [!NOTE] > You can replace the term `sandbox` with the environment name that you are deploying to (e.g., `production`, `integration_test`, etc.) with respective changes (optional) and use the same steps to generate the final configuration file for the environment. You can verify that the server is up and running by hitting the health check endpoint: ```shell curl --head --request GET 'http://localhost:8080/health' ``` [architecture]: /docs/architecture.md [config_example]: /config/config.example.toml
config/deployments/README.md
null
doc_file
1,616
doc
null
null
null
null
null
null
null
null
null
null
null
null
pub struct JpmorganCancelResponse { transaction_id: String, request_id: String, response_status: JpmorganResponseStatus, response_code: String, response_message: String, payment_method_type: JpmorganPaymentMethodTypeCancelResponse, }
crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
hyperswitch_connectors
struct_definition
56
rust
JpmorganCancelResponse
null
null
null
null
null
null
null
null
null
null
null
pub async fn get_sankey_data( clickhouse_client: &ClickhouseClient, auth: &AuthInfo, time_range: &TimeRange, ) -> MetricsResult<Vec<SankeyRow>> { let mut query_builder = QueryBuilder::<ClickhouseClient>::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::<String>::Count { field: None, alias: Some("count"), }) .change_context(MetricsError::QueryBuildingError)?; query_builder .add_select_column("exemption_requested") .change_context(MetricsError::QueryBuildingError)?; query_builder .add_select_column("exemption_accepted") .change_context(MetricsError::QueryBuildingError)?; query_builder .add_select_column("authentication_status") .change_context(MetricsError::QueryBuildingError)?; auth.set_filter_clause(&mut query_builder) .change_context(MetricsError::QueryBuildingError)?; time_range .set_filter_clause(&mut query_builder) .change_context(MetricsError::QueryBuildingError)?; query_builder .add_group_by_clause("exemption_requested") .change_context(MetricsError::QueryBuildingError)?; query_builder .add_group_by_clause("exemption_accepted") .change_context(MetricsError::QueryBuildingError)?; query_builder .add_group_by_clause("authentication_status") .change_context(MetricsError::QueryBuildingError)?; query_builder .execute_query::<SankeyRow, _>(clickhouse_client) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(Ok) .collect() }
crates/analytics/src/auth_events/sankey.rs
analytics
function_signature
378
rust
null
null
null
null
get_sankey_data
null
null
null
null
null
null
null
impl Paystack { pub fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } }
crates/hyperswitch_connectors/src/connectors/paystack.rs
hyperswitch_connectors
impl_block
33
rust
null
Paystack
null
impl Paystack
null
null
null
null
null
null
null
null
pub struct CalGlobalSuccessRateEventRequest { pub entity_id: String, pub entity_params: String, pub entity_labels: Vec<String>, pub global_labels: Vec<String>, pub config: Option<CalGlobalSuccessRateConfigEventRequest>, }
crates/router/src/core/payments/routing/utils.rs
router
struct_definition
54
rust
CalGlobalSuccessRateEventRequest
null
null
null
null
null
null
null
null
null
null
null
pub struct ZenCustomerDetails { email: pii::Email, ip: Secret<String, pii::IpAddress>, }
crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
hyperswitch_connectors
struct_definition
24
rust
ZenCustomerDetails
null
null
null
null
null
null
null
null
null
null
null
impl ConnectorValidation for Gocardless { fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([ PaymentMethodDataType::SepaBankDebit, PaymentMethodDataType::AchBankDebit, PaymentMethodDataType::BecsBankDebit, PaymentMethodDataType::BacsBankDebit, ]); is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } }
crates/hyperswitch_connectors/src/connectors/gocardless.rs
hyperswitch_connectors
impl_block
136
rust
null
Gocardless
ConnectorValidation for
impl ConnectorValidation for for Gocardless
null
null
null
null
null
null
null
null
impl 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))) } }
crates/router/src/bin/scheduler.rs
router
impl_block
88
rust
null
Health
null
impl Health
null
null
null
null
null
null
null
null
impl AuthEventMetricAccumulator for CountAccumulator { type MetricOutput = Option<u64>; #[inline] fn add_metrics_bucket(&mut self, metrics: &AuthEventMetricRow) { self.count = match (self.count, metrics.count) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), } } #[inline] fn collect(self) -> Self::MetricOutput { self.count.and_then(|i| u64::try_from(i).ok()) } }
crates/analytics/src/auth_events/accumulator.rs
analytics
impl_block
142
rust
null
CountAccumulator
AuthEventMetricAccumulator for
impl AuthEventMetricAccumulator for for CountAccumulator
null
null
null
null
null
null
null
null
Documentation: api-reference/v1/payouts/payouts--filter.mdx # Type: Doc File --- openapi: post /payouts/list ---
api-reference/v1/payouts/payouts--filter.mdx
null
doc_file
35
doc
null
null
null
null
null
null
null
null
null
null
null
null
pub async fn payment_method_update_api() {}
crates/openapi/src/routes/payment_method.rs
openapi
function_signature
9
rust
null
null
null
null
payment_method_update_api
null
null
null
null
null
null
null
impl Responder { let flow = Flow::CustomersDelete; let customer_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, customer_id, |state, auth: auth::AuthenticationData, customer_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); delete_customer(state, merchant_context, customer_id) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantCustomerWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/customers.rs
router
impl_block
181
rust
null
Responder
null
impl Responder
null
null
null
null
null
null
null
null
impl Responder { let flow = Flow::ApiKeyUpdate; let api_key_id = key_id.into_inner(); let mut payload = json_payload.into_inner(); payload.key_id = api_key_id; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth::AuthenticationDataWithoutProfile { merchant_account, .. }, mut payload, _| { payload.merchant_id = merchant_account.get_id().to_owned(); api_keys::update_api_key(state, payload) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantApiKeyRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/api_keys.rs
router
impl_block
184
rust
null
Responder
null
impl Responder
null
null
null
null
null
null
null
null
pub struct StaxChildCapture { id: String, }
crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
hyperswitch_connectors
struct_definition
13
rust
StaxChildCapture
null
null
null
null
null
null
null
null
null
null
null
File: crates/diesel_models/src/query/connector_response.rs Public functions: 3 use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use router_env::{instrument, logger, tracing}; use super::generics; use crate::{ connector_response::{ ConnectorResponse, ConnectorResponseNew, ConnectorResponseUpdate, ConnectorResponseUpdateInternal, }, errors, payment_attempt::{PaymentAttempt, PaymentAttemptUpdate, PaymentAttemptUpdateInternal}, schema::{connector_response::dsl, payment_attempt::dsl as pa_dsl}, PgPooledConn, StorageResult, }; impl ConnectorResponseNew { #[instrument(skip(conn))] pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ConnectorResponse> { let payment_attempt_update = PaymentAttemptUpdate::ConnectorResponse { authentication_data: self.authentication_data.clone(), encoded_data: self.encoded_data.clone(), connector_transaction_id: self.connector_transaction_id.clone(), connector: self.connector_name.clone(), updated_by: self.updated_by.clone(), charge_id: self.charge_id.clone(), }; let _payment_attempt: Result<PaymentAttempt, _> = generics::generic_update_with_unique_predicate_get_result::< <PaymentAttempt as HasTable>::Table, _, _, _, >( conn, pa_dsl::attempt_id .eq(self.attempt_id.to_owned()) .and(pa_dsl::merchant_id.eq(self.merchant_id.to_owned())), PaymentAttemptUpdateInternal::from(payment_attempt_update), ) .await .inspect_err(|err| { logger::error!( "Error while updating payment attempt in connector_response flow {:?}", err ); }); generics::generic_insert(conn, self).await } } impl ConnectorResponse { #[instrument(skip(conn))] pub async fn update( self, conn: &PgPooledConn, connector_response: ConnectorResponseUpdate, ) -> StorageResult<Self> { let payment_attempt_update = match connector_response.clone() { ConnectorResponseUpdate::ResponseUpdate { connector_transaction_id, authentication_data, encoded_data, connector_name, charge_id, updated_by, } => PaymentAttemptUpdate::ConnectorResponse { authentication_data, encoded_data, connector_transaction_id, connector: connector_name, charge_id, updated_by, }, ConnectorResponseUpdate::ErrorUpdate { connector_name, updated_by, } => PaymentAttemptUpdate::ConnectorResponse { authentication_data: None, encoded_data: None, connector_transaction_id: None, connector: connector_name, charge_id: None, updated_by, }, }; let _payment_attempt: Result<PaymentAttempt, _> = generics::generic_update_with_unique_predicate_get_result::< <PaymentAttempt as HasTable>::Table, _, _, _, >( conn, pa_dsl::attempt_id .eq(self.attempt_id.to_owned()) .and(pa_dsl::merchant_id.eq(self.merchant_id.to_owned())), PaymentAttemptUpdateInternal::from(payment_attempt_update), ) .await .inspect_err(|err| { logger::error!( "Error while updating payment attempt in connector_response flow {:?}", err ); }); let connector_response_result = match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id .eq(self.merchant_id.clone()) .and(dsl::payment_id.eq(self.payment_id.clone())) .and(dsl::attempt_id.eq(self.attempt_id.clone())), ConnectorResponseUpdateInternal::from(connector_response), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, }; connector_response_result } #[instrument(skip(conn))] pub async fn find_by_payment_id_merchant_id_attempt_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, ) -> StorageResult<Self> { let connector_response: Self = generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()).and( dsl::payment_id .eq(payment_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), ), ) .await?; match generics::generic_find_one::<<PaymentAttempt as HasTable>::Table, _, _>( conn, pa_dsl::payment_id.eq(payment_id.to_owned()).and( pa_dsl::merchant_id .eq(merchant_id.to_owned()) .and(pa_dsl::attempt_id.eq(attempt_id.to_owned())), ), ) .await { Ok::<PaymentAttempt, _>(payment_attempt) => { if payment_attempt.authentication_data != connector_response.authentication_data { logger::error!( "Not Equal pa_authentication_data : {:?}, cr_authentication_data: {:?} ", payment_attempt.authentication_data, connector_response.authentication_data ); } if payment_attempt.encoded_data != connector_response.encoded_data { logger::error!( "Not Equal pa_encoded_data : {:?}, cr_encoded_data: {:?} ", payment_attempt.encoded_data, connector_response.encoded_data ); } if payment_attempt.connector_transaction_id != connector_response.connector_transaction_id { logger::error!( "Not Equal pa_connector_transaction_id : {:?}, cr_connector_transaction_id: {:?} ", payment_attempt.connector_transaction_id, connector_response.connector_transaction_id ); } if payment_attempt.connector != connector_response.connector_name { logger::error!( "Not Equal pa_connector : {:?}, cr_connector_name: {:?} ", payment_attempt.connector, connector_response.connector_name ); } } Err(err) => { logger::error!( "Error while finding payment attempt in connector_response flow {:?}", err ); } } Ok(connector_response) } }
crates/diesel_models/src/query/connector_response.rs
diesel_models
full_file
1,375
null
null
null
null
null
null
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.RevolutPayData { "type": "object" }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
23
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "RevolutPayData" ]
null
null
null
null
pub struct GetCard<'a> { merchant_id: &'a str, card_id: &'a str, }
crates/router/src/core/payment_methods/transformers.rs
router
struct_definition
25
rust
GetCard
null
null
null
null
null
null
null
null
null
null
null
pub struct CloneConnectorDestination { pub connector_label: Option<String>, pub profile_id: id_type::ProfileId, pub merchant_id: id_type::MerchantId, }
crates/api_models/src/user.rs
api_models
struct_definition
37
rust
CloneConnectorDestination
null
null
null
null
null
null
null
null
null
null
null
impl PaymentMethodsEnabled { /// Get payment_method_type #[cfg(feature = "v2")] pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> { Some(self.payment_method_type) } /// Get payment_method_subtypes #[cfg(feature = "v2")] pub fn get_payment_method_type(&self) -> Option<&Vec<RequestPaymentMethodTypes>> { self.payment_method_subtypes.as_ref() } }
crates/common_types/src/payment_methods.rs
common_types
impl_block
100
rust
null
PaymentMethodsEnabled
null
impl PaymentMethodsEnabled
null
null
null
null
null
null
null
null
pub fn new( token: auth::UserFromSinglePurposeToken, current_flow: UserFlow, ) -> UserResult<Self> { let flows = token.origin.get_flows(); let index = flows .iter() .position(|flow| flow == &current_flow) .ok_or(UserErrors::InternalServerError)?; let mut path = token.path; path.push(current_flow.into()); Ok(Self { origin: token.origin, current_flow_index: index, path, tenant_id: token.tenant_id, }) }
crates/router/src/types/domain/user/decision_manager.rs
router
function_signature
119
rust
null
null
null
null
new
null
null
null
null
null
null
null
pub async fn increment_blocked_count_in_cache( state: &SessionState, card_testing_guard_data: Option<CardTestingGuardData>, ) -> RouterResult<()> { if let Some(card_testing_guard_data) = card_testing_guard_data.clone() { if card_testing_guard_data.is_card_ip_blocking_enabled && !card_testing_guard_data .card_ip_blocking_cache_key .is_empty() { let _ = services::card_testing_guard::increment_blocked_count_in_cache( state, &card_testing_guard_data.card_ip_blocking_cache_key, card_testing_guard_data.card_testing_guard_expiry.into(), ) .await; } if card_testing_guard_data.is_guest_user_card_blocking_enabled && !card_testing_guard_data .guest_user_card_blocking_cache_key .is_empty() { let _ = services::card_testing_guard::increment_blocked_count_in_cache( state, &card_testing_guard_data.guest_user_card_blocking_cache_key, card_testing_guard_data.card_testing_guard_expiry.into(), ) .await; } if card_testing_guard_data.is_customer_id_blocking_enabled && !card_testing_guard_data .customer_id_blocking_cache_key .is_empty() { let _ = services::card_testing_guard::increment_blocked_count_in_cache( state, &card_testing_guard_data.customer_id_blocking_cache_key, card_testing_guard_data.card_testing_guard_expiry.into(), ) .await; } } Ok(()) }
crates/router/src/core/card_testing_guard/utils.rs
router
function_signature
316
rust
null
null
null
null
increment_blocked_count_in_cache
null
null
null
null
null
null
null
#[cfg(feature = "v2")] //List Payment Method #[derive(Debug, Clone, serde::Serialize, Default, ToSchema)] #[serde(deny_unknown_fields)] pub struct ListMethodsForPaymentMethodsRequest { /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, /// The two-letter ISO currency code #[schema(value_type = Option<Vec<CountryAlpha2>>, example = json!(["US", "UK", "IN"]))] pub accepted_countries: Option<Vec<api_enums::CountryAlpha2>>, /// Filter by amount #[schema(example = 60)] pub amount: Option<MinorUnit>, /// The three-letter ISO currency code #[schema(value_type = Option<Vec<Currency>>,example = json!(["USD", "EUR"]))] pub accepted_currencies: Option<Vec<api_enums::Currency>>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for card netwotks #[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// Indicates the limit of last used payment methods #[schema(example = 1)] pub limit: Option<i64>, } #[cfg(feature = "v2")] impl<'de> serde::Deserialize<'de> for ListMethodsForPaymentMethodsRequest { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct FieldVisitor; impl<'de> de::Visitor<'de> for FieldVisitor { type Value = ListMethodsForPaymentMethodsRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = ListMethodsForPaymentMethodsRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } } deserializer.deserialize_identifier(FieldVisitor) } } // Try to set the provided value to the data otherwise throw an error fn set_or_reject_duplicate<T, E: de::Error>( data: &mut Option<T>, name: &'static str, value: T, ) -> Result<(), E> { match data { Some(_inner) => Err(de::Error::duplicate_field(name)), None => { *data = Some(value); Ok(()) } } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponse { /// Redirect URL of the merchant #[schema(example = "https://www.google.com")] pub redirect_url: Option<String>, /// currency of the Payment to be done #[schema(example = "USD", value_type = Currency)] pub currency: Option<api_enums::Currency>, /// Information about the payment method pub payment_methods: Vec<ResponsePaymentMethodsEnabled>, /// Value indicating if the current payment is a mandate payment #[schema(value_type = MandateType)] pub mandate_payment: Option<payments::MandateType>, #[schema(value_type = Option<String>)] pub merchant_name: OptionalEncryptableName, /// flag to indicate if surcharge and tax breakup screen should be shown or not #[schema(value_type = bool)] pub show_surcharge_breakup_screen: bool, #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, /// flag to indicate whether to perform external 3ds authentication #[schema(example = true)] pub request_external_three_ds_authentication: bool, /// flag that indicates whether to collect shipping details from wallets or from the customer pub collect_shipping_details_from_wallets: Option<bool>, /// flag that indicates whether to collect billing details from wallets or from the customer pub collect_billing_details_from_wallets: Option<bool>, /// flag that indicates whether to calculate tax on the order amount pub is_tax_calculation_enabled: bool, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodsListResponse { /// List of payment methods for customer pub customer_payment_methods: Vec<CustomerPaymentMethod>, /// Returns whether a customer id is not tied to a payment intent (only when the request is made against a client secret) pub is_guest_customer: Option<bool>, } // OLAP PML Response #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodsListResponse { /// List of payment methods for customer pub customer_payment_methods: Vec<PaymentMethodResponseItem>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct GetTokenDataRequest { /// Indicates the type of token to be fetched pub token_type: api_enums::TokenDataType, } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for GetTokenDataRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct TokenDataResponse { /// The unique identifier of the payment method. #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: id_type::GlobalPaymentMethodId, /// token type of the payment method #[schema(value_type = TokenDataType)] pub token_type: api_enums::TokenDataType, /// token details of the payment method pub token_details: TokenDetailsResponse, } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for TokenDataResponse {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum TokenDetailsResponse { NetworkTokenDetails(NetworkTokenDetailsResponse), } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct NetworkTokenDetailsResponse { /// Network token generated against the Card Number #[schema(value_type = String)] pub network_token: cards::NetworkToken, /// Expiry month of the network token #[schema(value_type = String)] pub network_token_exp_month: masking::Secret<String>, /// Expiry year of the network token #[schema(value_type = String)] pub network_token_exp_year: masking::Secret<String>, /// Cryptogram generated by the Network #[schema(value_type = Option<String>)] pub cryptogram: Option<masking::Secret<String>>, /// Issuer of the card pub card_issuer: Option<String>, /// Card network of the token #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<common_enums::CardNetwork>, /// Card type of the token pub card_type: Option<CardType>, /// Issuing country of the card #[schema(value_type = Option<CountryAlpha2>)] pub card_issuing_country: Option<common_enums::CountryAlpha2>, /// Bank code of the card pub bank_code: Option<String>, /// Name of the card holder #[schema(value_type = Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, /// Nick name of the card holder #[schema(value_type = Option<String>)] pub nick_name: Option<masking::Secret<String>>, /// ECI indicator of the card pub eci: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct TotalPaymentMethodCountResponse { /// total count of payment methods under the merchant pub total_count: i64, } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for TotalPaymentMethodCountResponse {} #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodDeleteResponse { /// The unique identifier of the Payment method #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")] pub payment_method_id: String, /// Whether payment method was deleted or not #[schema(example = true)] pub deleted: bool, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodDeleteResponse { /// The unique identifier of the Payment method #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerDefaultPaymentMethodResponse { /// The unique identifier of the Payment method #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")] pub default_payment_method_id: Option<String>, /// The unique identifier of the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>,example = "credit")] pub payment_method_type: Option<api_enums::PaymentMethodType>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentMethodResponseItem { /// The unique identifier of the payment method. #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "credit")] pub payment_method_subtype: api_enums::PaymentMethodType, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// PaymentMethod Data from locker pub payment_method_data: Option<PaymentMethodListData>, /// Masked bank details from PM auth services #[schema(example = json!({"mask": "0000"}))] pub bank: Option<MaskedBankDetails>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: time::PrimitiveDateTime, /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601")] pub last_used_at: time::PrimitiveDateTime, /// Indicates if the payment method has been set to default or not #[schema(example = true)] pub is_default: bool, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, ///The network token details for the payment method pub network_tokenization: Option<NetworkTokenResponse>, /// Whether psp_tokenization is enabled for the payment_method, this will be true when at least /// one multi-use token with status `Active` is available for the payment method pub psp_tokenization_enabled: bool, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodResponseItem { /// The unique identifier of the payment method. #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, /// Temporary Token for payment method in vault which gets refreshed for every payment #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")] pub payment_token: String, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "credit")] pub payment_method_subtype: api_enums::PaymentMethodType, /// Indicates whether the payment method is eligible for recurring payments #[schema(example = true)] pub recurring_enabled: bool, /// PaymentMethod Data from locker pub payment_method_data: Option<PaymentMethodListData>, /// Masked bank details from PM auth services #[schema(example = json!({"mask": "0000"}))] pub bank: Option<MaskedBankDetails>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: time::PrimitiveDateTime, /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub last_used_at: time::PrimitiveDateTime, /// Indicates if the payment method has been set to default or not #[schema(example = true)] pub is_default: bool, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodListData { Card(CardDetailFromLocker), #[cfg(feature = "payouts")] #[schema(value_type = Bank)] Bank(payouts::Bank), } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethod { /// Token for payment method in temporary card locker which gets refreshed often #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")] pub payment_token: String, /// The unique identifier of the customer. #[schema(example = "pm_iouuy468iyuowqs")] pub payment_method_id: String, /// The unique identifier of the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>,example = "credit_card")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user #[schema(example = "Citibank")] pub payment_method_issuer: Option<String>, /// A standard code representing the issuer of payment method #[schema(value_type = Option<PaymentMethodIssuerCode>,example = "jp_applepay")] pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional. #[schema(example = true)] pub installment_payment_enabled: Option<bool>, /// Type of payment experience enabled with the connector #[schema(value_type = Option<Vec<PaymentExperience>>,example = json!(["redirect_to_url"]))] pub payment_experience: Option<Vec<api_enums::PaymentExperience>>, /// Card details from card locker #[schema(example = json!({"last4": "1142","exp_month": "03","exp_year": "2030"}))] pub card: Option<CardDetailFromLocker>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = Option<PrimitiveDateTime>,example = "2023-01-18T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] #[serde(skip_serializing_if = "Option::is_none")] pub bank_transfer: Option<payouts::Bank>, /// Masked bank details from PM auth services #[schema(example = json!({"mask": "0000"}))] pub bank: Option<MaskedBankDetails>, /// Surcharge details for this saved card pub surcharge_details: Option<SurchargeDetailsResponse>, /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = Option<PrimitiveDateTime>,example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_used_at: Option<time::PrimitiveDateTime>, /// Indicates if the payment method has been set to default or not #[schema(example = true)] pub default_payment_method_set: bool, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodCollectLinkRequest { /// The unique identifier for the collect link. #[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: Option<String>, /// The unique identifier of the customer. #[schema(value_type = String, example = "cus_92dnwed8s32bV9D8Snbiasd8v")] pub customer_id: id_type::CustomerId, #[serde(flatten)] #[schema(value_type = Option<GenericLinkUiConfig>)] pub ui_config: Option<link_utils::GenericLinkUiConfig>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds /// (900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Redirect to this URL post completion #[schema(value_type = Option<String>, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1/status")] pub return_url: Option<String>, /// List of payment methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodCollectLinkResponse { /// The unique identifier for the collect link. #[schema(value_type = String, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: String, /// The unique identifier of the customer. #[schema(value_type = String, example = "cus_92dnwed8s32bV9D8Snbiasd8v")] pub customer_id: id_type::CustomerId, /// Time when this link will be expired in ISO8601 format #[schema(value_type = PrimitiveDateTime, example = "2025-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: time::PrimitiveDateTime, /// URL to the form's link generated for collecting payment method details. #[schema(value_type = String, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1")] pub link: masking::Secret<url::Url>, /// Redirect to this URL post completion #[schema(value_type = Option<String>, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1/status")] pub return_url: Option<String>, /// Collect link config used #[serde(flatten)] #[schema(value_type = GenericLinkUiConfig)] pub ui_config: link_utils::GenericLinkUiConfig, /// List of payment methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodCollectLinkRenderRequest { /// Unique identifier for a merchant. #[schema(example = "merchant_1671528864", value_type = String)] pub merchant_id: id_type::MerchantId, /// The unique identifier for the collect link. #[schema(value_type = String, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: String, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodCollectLinkDetails { pub publishable_key: masking::Secret<String>, pub client_secret: masking::Secret<String>, pub pm_collect_link_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: time::PrimitiveDateTime, pub return_url: Option<String>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodCollectLinkStatusDetails { pub pm_collect_link_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: time::PrimitiveDateTime, pub return_url: Option<url::Url>, pub status: link_utils::PaymentMethodCollectStatus, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MaskedBankDetails { pub mask: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodId { pub payment_method_id: String, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DefaultPaymentMethod { #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, pub payment_method_id: String, } //------------------------------------------------TokenizeService------------------------------------------------ #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizePayloadEncrypted { pub payload: String, pub key_id: String, pub version: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizePayloadRequest { pub value1: String, pub value2: String, pub lookup_key: String, pub service_name: String, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct GetTokenizePayloadRequest { pub lookup_key: String, pub service_name: String, pub get_value2: bool, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct DeleteTokenizeByTokenRequest { pub lookup_key: String, pub service_name: String, } #[derive(Debug, serde::Serialize)] // Blocked: Yet to be implemented by `basilisk` pub struct DeleteTokenizeByDateRequest { pub buffer_minutes: i32, pub service_name: String, pub max_rows: i32, } #[derive(Debug, serde::Deserialize)] pub struct GetTokenizePayloadResponse { pub lookup_key: String, pub get_value2: Option<bool>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCardValue1 { pub card_number: String, pub exp_year: String, pub exp_month: String, pub name_on_card: Option<String>, pub nickname: Option<String>, pub card_last_four: Option<String>, pub card_token: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ListCountriesCurrenciesRequest { pub connector: api_enums::Connector, pub payment_method_type: api_enums::PaymentMethodType, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ListCountriesCurrenciesResponse { pub currencies: HashSet<api_enums::Currency>, pub countries: HashSet<CountryCodeWithName>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq)] pub struct CountryCodeWithName { pub code: api_enums::CountryAlpha2, pub name: api_enums::Country, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCardValue2 { pub card_security_code: Option<String>, pub card_fingerprint: Option<String>, pub external_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub payment_method_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedWalletValue1 { pub data: payments::WalletData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedWalletValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankTransferValue1 { pub data: payments::BankTransferData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankTransferValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankRedirectValue1 { pub data: payments::BankRedirectData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankRedirectValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PaymentMethodRecord { pub customer_id: id_type::CustomerId, pub name: Option<masking::Secret<String>>, pub email: Option<pii::Email>, pub phone: Option<masking::Secret<String>>, pub phone_country_code: Option<String>, pub merchant_id: Option<id_type::MerchantId>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_type: Option<api_enums::PaymentMethodType>, pub nick_name: Option<masking::Secret<String>>, pub payment_instrument_id: Option<masking::Secret<String>>, pub connector_customer_id: Option<String>, pub card_number_masked: masking::Secret<String>, pub card_expiry_month: masking::Secret<String>, pub card_expiry_year: masking::Secret<String>, pub card_scheme: Option<String>, pub original_transaction_id: Option<String>, pub billing_address_zip: Option<masking::Secret<String>>, pub billing_address_state: Option<masking::Secret<String>>, pub billing_address_first_name: Option<masking::Secret<String>>, pub billing_address_last_name: Option<masking::Secret<String>>, pub billing_address_city: Option<String>, pub billing_address_country: Option<api_enums::CountryAlpha2>, pub billing_address_line1: Option<masking::Secret<String>>, pub billing_address_line2: Option<masking::Secret<String>>, pub billing_address_line3: Option<masking::Secret<String>>, pub raw_card_number: Option<masking::Secret<String>>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub merchant_connector_ids: Option<String>, pub original_transaction_amount: Option<i64>, pub original_transaction_currency: Option<common_enums::Currency>, pub line_number: Option<i64>, pub network_token_number: Option<CardNumber>, pub network_token_expiry_month: Option<masking::Secret<String>>, pub network_token_expiry_year: Option<masking::Secret<String>>, pub network_token_requestor_ref_id: Option<String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct UpdatePaymentMethodRecord { pub payment_method_id: String, pub status: Option<common_enums::PaymentMethodStatus>, pub network_transaction_id: Option<String>, pub line_number: Option<i64>, pub payment_instrument_id: Option<masking::Secret<String>>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, } #[derive(Debug, serde::Serialize)] pub struct PaymentMethodUpdateResponse { pub payment_method_id: String, pub status: Option<common_enums::PaymentMethodStatus>, pub network_transaction_id: Option<String>, pub connector_mandate_details: Option<pii::SecretSerdeValue>, pub update_status: UpdateStatus, #[serde(skip_serializing_if = "Option::is_none")] pub update_error: Option<String>, pub line_number: Option<i64>, } #[derive(Debug, Default, serde::Serialize)] pub struct PaymentMethodMigrationResponse { pub line_number: Option<i64>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method: Option<api_enums::PaymentMethod>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method_type: Option<api_enums::PaymentMethodType>, pub customer_id: Option<id_type::CustomerId>, pub migration_status: MigrationStatus, #[serde(skip_serializing_if = "Option::is_none")] pub migration_error: Option<String>, pub card_number_masked: Option<masking::Secret<String>>, pub card_migrated: Option<bool>, pub network_token_migrated: Option<bool>, pub connector_mandate_details_migrated: Option<bool>, pub network_transaction_id_migrated: Option<bool>, } #[derive(Debug, Default, serde::Serialize)] pub enum MigrationStatus { Success, #[default] Failed, } #[derive(Debug, Default, serde::Serialize)] pub enum UpdateStatus { Success, #[default] Failed, }
crates/api_models/src/payment_methods.rs#chunk2
api_models
chunk
8,190
null
null
null
null
null
null
null
null
null
null
null
null
null
impl webhooks::IncomingWebhook for Thunes { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } }
crates/hyperswitch_connectors/src/connectors/thunes.rs
hyperswitch_connectors
impl_block
210
rust
null
Thunes
webhooks::IncomingWebhook for
impl webhooks::IncomingWebhook for for Thunes
null
null
null
null
null
null
null
null
pub async fn list_all_themes_in_lineage( state: SessionState, user: UserFromToken, entity_type: EntityType, ) -> UserResponse<Vec<theme_api::GetThemeResponse>> { let lineage = theme_utils::get_theme_lineage_from_user_token(&user, &state, &entity_type).await?; let db_themes = state .store .list_themes_at_and_under_lineage(lineage) .await .change_context(UserErrors::InternalServerError)?; let mut themes = Vec::new(); for theme in db_themes { match theme_utils::retrieve_file_from_theme_bucket( &state, &theme_utils::get_theme_file_key(&theme.theme_id), ) .await { Ok(file) => { match file .to_bytes() .parse_struct("ThemeData") .change_context(UserErrors::InternalServerError) { Ok(parsed_data) => { themes.push(theme_api::GetThemeResponse { email_config: theme.email_config(), theme_id: theme.theme_id, theme_name: theme.theme_name, entity_type: theme.entity_type, tenant_id: theme.tenant_id, org_id: theme.org_id, merchant_id: theme.merchant_id, profile_id: theme.profile_id, theme_data: parsed_data, }); } Err(_) => { return Err(UserErrors::ErrorRetrievingFile.into()); } } } Err(_) => { return Err(UserErrors::ErrorRetrievingFile.into()); } } } Ok(ApplicationResponse::Json(themes)) }
crates/router/src/core/user/theme.rs
router
function_signature
347
rust
null
null
null
null
list_all_themes_in_lineage
null
null
null
null
null
null
null
pub async fn get_verified_apple_domains_with_mid_mca_id( state: SessionState, merchant_id: common_utils::id_type::MerchantId, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult< services::ApplicationResponse<verifications::ApplepayVerifiedDomainsResponse>, errors::ApiErrorResponse, > { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?; #[cfg(feature = "v1")] let verified_domains = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &merchant_id, &merchant_connector_id, &key_store, ) .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound)? .applepay_verified_domains .unwrap_or_default(); #[cfg(feature = "v2")] let verified_domains = db .find_merchant_connector_account_by_id( key_manager_state, &merchant_connector_id, &key_store, ) .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound)? .applepay_verified_domains .unwrap_or_default(); Ok(services::api::ApplicationResponse::Json( verifications::ApplepayVerifiedDomainsResponse { verified_domains }, )) }
crates/router/src/core/verification.rs
router
function_signature
342
rust
null
null
null
null
get_verified_apple_domains_with_mid_mca_id
null
null
null
null
null
null
null
pub struct VolumeSplit<T> { pub split: u8, pub output: T, }
crates/router/src/core/payments/routing/utils.rs
router
struct_definition
21
rust
VolumeSplit
null
null
null
null
null
null
null
null
null
null
null
/// Get the entity_type from the lineage pub fn entity_type(&self) -> EntityType { match self { Self::Tenant { .. } => EntityType::Tenant, Self::Organization { .. } => EntityType::Organization, Self::Merchant { .. } => EntityType::Merchant, Self::Profile { .. } => EntityType::Profile, } }
crates/common_utils/src/types/user/theme.rs
common_utils
function_signature
76
rust
null
null
null
null
entity_type
null
null
null
null
null
null
null
File: crates/analytics/src/payments/metrics/payment_processed_amount.rs use std::collections::HashSet; use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::PaymentMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct PaymentProcessedAmount; #[async_trait::async_trait] impl<T> super::PaymentMetric<T> for PaymentProcessedAmount where T: AnalyticsDataSource + super::PaymentMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Sum { field: "amount", alias: Some("total"), }) .switch()?; query_builder.add_select_column("currency").switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", alias: Some("start_bucket"), }) .switch()?; query_builder .add_select_column(Aggregate::Max { field: "created_at", alias: Some("end_bucket"), }) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; auth.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; for dim in dimensions.iter() { query_builder .add_group_by_clause(dim) .attach_printable("Error grouping by dimensions") .switch()?; } query_builder .add_group_by_clause("currency") .attach_printable("Error grouping by currency") .switch()?; if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } query_builder .add_filter_clause( PaymentDimensions::PaymentStatus, storage_enums::AttemptStatus::Charged, ) .switch()?; query_builder .execute_query::<PaymentMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( PaymentMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.authentication_type.as_ref().map(|i| i.0), i.payment_method.clone(), i.payment_method_type.clone(), i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), i.card_network.clone(), i.merchant_id.clone(), i.card_last_4.clone(), i.card_issuer.clone(), i.error_reason.clone(), i.routing_approach.as_ref().map(|i| i.0.clone()), i.signature_network.clone(), i.is_issuer_regulated, i.is_debit_routed, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, _ => time_range.start_time, }, end_time: granularity.as_ref().map_or_else( || Ok(time_range.end_time), |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), )?, }, ), i, )) }) .collect::<error_stack::Result< HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/payments/metrics/payment_processed_amount.rs
analytics
full_file
1,016
null
null
null
null
null
null
null
null
null
null
null
null
null
pub async fn delete( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::connector .eq(connector) .and(dsl::flow.eq(flow)) .and(dsl::sub_flow.eq(sub_flow)) .and(dsl::code.eq(code)) .and(dsl::message.eq(message)), ) .await }
crates/diesel_models/src/query/gsm.rs
diesel_models
function_signature
129
rust
null
null
null
null
delete
null
null
null
null
null
null
null
pub struct MerchantAdvice { code: Option<String>, code_raw: Option<String>, }
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
hyperswitch_connectors
struct_definition
19
rust
MerchantAdvice
null
null
null
null
null
null
null
null
null
null
null
pub struct Shift4NonThreeDsResponse { pub id: String, pub currency: String, pub amount: u32, pub status: Shift4PaymentStatus, pub captured: bool, pub refunded: bool, pub flow: Option<FlowResponse>, }
crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
hyperswitch_connectors
struct_definition
60
rust
Shift4NonThreeDsResponse
null
null
null
null
null
null
null
null
null
null
null
impl Responder { let gsm_retrieve_req = json_payload.into_inner(); let flow = Flow::GsmRuleRetrieve; Box::pin(api::server_wrap( flow, state.clone(), &req, gsm_retrieve_req, |state, _, gsm_retrieve_req, _| gsm::retrieve_gsm_rule(state, gsm_retrieve_req), &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/gsm.rs
router
impl_block
107
rust
null
Responder
null
impl Responder
null
null
null
null
null
null
null
null
pub async fn decide_connector( state: SessionState, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, routing_data: &mut storage::RoutingData, payment_dsl_input: core_routing::PaymentsDslInput<'_>, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<ConnectorCallType> { // If the connector was already decided previously, use the same connector // This is in case of flows like payments_sync, payments_cancel where the successive operations // with the connector have to be made using the same connector account. let predetermined_info_cloned = routing_data .routed_through .as_ref() .zip(routing_data.merchant_connector_id.as_ref()) .map(|(cn_ref, mci_ref)| (cn_ref.clone(), mci_ref.clone())); match ( predetermined_info_cloned, routing_data.pre_routing_connector_choice.as_ref(), ) { // Condition 1: Connector was already decided previously (Some((owned_connector_name, owned_merchant_connector_id)), _) => { api::ConnectorData::get_connector_by_name( &state.conf.connectors, &owned_connector_name, api::GetToken::Connector, Some(owned_merchant_connector_id.clone()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received in 'routed_through'") .map(|connector_data| { routing_data.routed_through = Some(owned_connector_name); ConnectorCallType::PreDetermined(connector_data.into()) }) } // Condition 2: Pre-routing connector choice (None, Some(routable_connector_choice)) => { 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() } }; routable_connector_list .first() .ok_or_else(|| { report!(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("No first routable connector in pre_routing_connector_choice") }) .and_then(|first_routable_connector| { routing_data.routed_through = Some(first_routable_connector.connector.to_string()); routing_data .merchant_connector_id .clone_from(&first_routable_connector.merchant_connector_id); let pre_routing_connector_data_list_result: RouterResult<Vec<api::ConnectorData>> = routable_connector_list .iter() .map(|connector_choice| { api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_choice.connector.to_string(), api::GetToken::Connector, connector_choice.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received while processing pre_routing_connector_choice") }) .collect::<Result<Vec<_>, _>>(); // Collects into RouterResult<Vec<ConnectorData>> pre_routing_connector_data_list_result .and_then(|list| { list.first() .cloned() .ok_or_else(|| { report!(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("Empty pre_routing_connector_data_list after mapping") }) .map(|first_data| ConnectorCallType::PreDetermined(first_data.into())) }) }) } (None, None) => { route_connector_v2_for_payments( &state, merchant_context, business_profile, payment_dsl_input, routing_data, mandate_type, ) .await } } }
crates/router/src/core/payments.rs
router
function_signature
814
rust
null
null
null
null
decide_connector
null
null
null
null
null
null
null
pub async fn payments_core<F, Res, Req, Op, FData, D>( state: SessionState, req_state: ReqState, merchant_context: domain::MerchantContext, profile: domain::Profile, operation: Op, req: Req, payment_id: id_type::GlobalPaymentId, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, ) -> RouterResponse<Res> where F: Send + Clone + Sync, Req: Send + Sync + Authenticate, FData: Send + Sync + Clone, Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone, Req: Debug, D: OperationSessionGetters<F> + OperationSessionSetters<F> + transformers::GenerateResponse<Res> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, // To create updatable objects in post update tracker RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, { // Validate the request fields operation .to_validate_request()? .validate_request(&req, &merchant_context)?; // Get the tracker related information. This includes payment intent and payment attempt let get_tracker_response = operation .to_get_tracker()? .get_trackers( &state, &payment_id, &req, &merchant_context, &profile, &header_payload, ) .await?; let (payment_data, connector_http_status_code, external_latency, connector_response_data) = if state.conf.merchant_id_auth.merchant_id_auth_enabled { let ( payment_data, _req, connector_http_status_code, external_latency, connector_response_data, ) = internal_payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_context.clone(), &profile, operation.clone(), req, get_tracker_response, call_connector_action, header_payload.clone(), ) .await?; ( payment_data, connector_http_status_code, external_latency, connector_response_data, ) } else { let ( payment_data, _req, _customer, connector_http_status_code, external_latency, connector_response_data, ) = payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_context.clone(), &profile, operation.clone(), req, get_tracker_response, call_connector_action, header_payload.clone(), ) .await?; ( payment_data, connector_http_status_code, external_latency, connector_response_data, ) }; payment_data.generate_response( &state, connector_http_status_code, external_latency, header_payload.x_hs_latency, &merchant_context, &profile, Some(connector_response_data), ) }
crates/router/src/core/payments.rs
router
function_signature
751
rust
null
null
null
null
payments_core
null
null
null
null
null
null
null
impl ResponseId { pub fn get_connector_transaction_id( &self, ) -> errors::CustomResult<String, errors::ValidationError> { match self { Self::ConnectorTransactionId(txn_id) => Ok(txn_id.to_string()), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "connector_transaction_id", }) .attach_printable("Expected connector transaction ID not found"), } } }
crates/hyperswitch_domain_models/src/router_request_types.rs
hyperswitch_domain_models
impl_block
94
rust
null
ResponseId
null
impl ResponseId
null
null
null
null
null
null
null
null
impl Responder { let wrapper = routing_types::ProfileDefaultRoutingConfig { profile_id: path.into_inner(), connectors: json_payload.into_inner(), }; Box::pin(oss_api::server_wrap( Flow::RoutingUpdateDefaultConfig, state, &req, wrapper, |state, auth: auth::AuthenticationData, wrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::update_default_fallback_routing( state, merchant_context, wrapper.profile_id, wrapper.connectors, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantRoutingWrite, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/routing.rs
router
impl_block
249
rust
null
Responder
null
impl Responder
null
null
null
null
null
null
null
null
pub struct AuthenticationDataWithOrg { pub organization_id: id_type::OrganizationId, }
crates/router/src/services/authentication.rs
router
struct_definition
19
rust
AuthenticationDataWithOrg
null
null
null
null
null
null
null
null
null
null
null
impl Display for GenericLinksData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match *self { Self::ExpiredLink(_) => "ExpiredLink", Self::PaymentMethodCollect(_) => "PaymentMethodCollect", Self::PayoutLink(_) => "PayoutLink", Self::PayoutLinkStatus(_) => "PayoutLinkStatus", Self::PaymentMethodCollectStatus(_) => "PaymentMethodCollectStatus", Self::SecurePaymentLink(_) => "SecurePaymentLink", } ) } }
crates/hyperswitch_domain_models/src/api.rs
hyperswitch_domain_models
impl_block
133
rust
null
GenericLinksData
Display for
impl Display for for GenericLinksData
null
null
null
null
null
null
null
null
impl api::revenue_recovery_v2::BillingConnectorInvoiceSyncIntegrationV2 for Recurly {}
crates/hyperswitch_connectors/src/connectors/recurly.rs
hyperswitch_connectors
impl_block
21
rust
null
Recurly
api::revenue_recovery_v2::BillingConnectorInvoiceSyncIntegrationV2 for
impl api::revenue_recovery_v2::BillingConnectorInvoiceSyncIntegrationV2 for for Recurly
null
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs Public functions: 3 Public structs: 26 #[cfg(all(feature = "revenue_recovery", feature = "v2"))] use std::str::FromStr; use common_enums::enums; use common_utils::{errors::CustomResult, ext_traits::ByteSliceExt, pii, types::MinorUnit}; use error_stack::ResultExt; #[cfg(all(feature = "revenue_recovery", feature = "v2"))] use hyperswitch_domain_models::revenue_recovery; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::{ refunds::{Execute, RSync}, RecoveryRecordBack, }, router_request_types::{revenue_recovery::RevenueRecoveryRecordBackRequest, ResponseId}, router_response_types::{ revenue_recovery::RevenueRecoveryRecordBackResponse, PaymentsResponseData, RefundsResponseData, }, types::{PaymentsAuthorizeRouterData, RefundsRouterData, RevenueRecoveryRecordBackRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{self, PaymentsAuthorizeRequestData}, }; //TODO: Fill the struct with respective fields pub struct ChargebeeRouterData<T> { pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(MinorUnit, T)> for ChargebeeRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] pub struct ChargebeePaymentsRequest { amount: MinorUnit, card: ChargebeeCard, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct ChargebeeCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } impl TryFrom<&ChargebeeRouterData<&PaymentsAuthorizeRouterData>> for ChargebeePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &ChargebeeRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { let card = ChargebeeCard { number: req_card.card_number, expiry_month: req_card.card_exp_month, expiry_year: req_card.card_exp_year, cvc: req_card.card_cvc, complete: item.router_data.request.is_auto_capture()?, }; Ok(Self { amount: item.amount, card, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } // Auth Struct pub struct ChargebeeAuthType { pub(super) full_access_key_v1: Secret<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct ChargebeeMetadata { pub(super) site: Secret<String>, } impl TryFrom<&Option<pii::SecretSerdeValue>> for ChargebeeMetadata { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata", })?; Ok(metadata) } } impl TryFrom<&ConnectorAuthType> for ChargebeeAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { full_access_key_v1: api_key.clone(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse //TODO: Append the remaining status flags #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum ChargebeePaymentStatus { Succeeded, Failed, #[default] Processing, } impl From<ChargebeePaymentStatus> for common_enums::AttemptStatus { fn from(item: ChargebeePaymentStatus) -> Self { match item { ChargebeePaymentStatus::Succeeded => Self::Charged, ChargebeePaymentStatus::Failed => Self::Failure, ChargebeePaymentStatus::Processing => Self::Authorizing, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct ChargebeePaymentsResponse { status: ChargebeePaymentStatus, id: String, } impl<F, T> TryFrom<ResponseRouterData<F, ChargebeePaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, ChargebeePaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } //TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct ChargebeeRefundRequest { pub amount: MinorUnit, } impl<F> TryFrom<&ChargebeeRouterData<&RefundsRouterData<F>>> for ChargebeeRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &ChargebeeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct ChargebeeErrorResponse { pub api_error_code: String, pub message: String, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeWebhookBody { pub content: ChargebeeWebhookContent, pub event_type: ChargebeeEventType, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeInvoiceBody { pub content: ChargebeeInvoiceContent, pub event_type: ChargebeeEventType, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeInvoiceContent { pub invoice: ChargebeeInvoiceData, pub subscription: Option<ChargebeeSubscriptionData>, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeWebhookContent { pub transaction: ChargebeeTransactionData, pub invoice: ChargebeeInvoiceData, pub customer: Option<ChargebeeCustomer>, pub subscription: Option<ChargebeeSubscriptionData>, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeSubscriptionData { #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub current_term_start: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub next_billing_at: Option<PrimitiveDateTime>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "snake_case")] pub enum ChargebeeEventType { PaymentSucceeded, PaymentFailed, InvoiceDeleted, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeInvoiceData { // invoice id pub id: String, pub total: MinorUnit, pub currency_code: enums::Currency, pub billing_address: Option<ChargebeeInvoiceBillingAddress>, pub linked_payments: Option<Vec<ChargebeeInvoicePayments>>, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeInvoicePayments { pub txn_status: Option<String>, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeTransactionData { id_at_gateway: Option<String>, status: ChargebeeTranasactionStatus, error_code: Option<String>, error_text: Option<String>, gateway_account_id: String, currency_code: enums::Currency, amount: MinorUnit, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] date: Option<PrimitiveDateTime>, payment_method: ChargebeeTransactionPaymentMethod, payment_method_details: String, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "snake_case")] pub enum ChargebeeTransactionPaymentMethod { Card, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeePaymentMethodDetails { card: ChargebeeCardDetails, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeCardDetails { funding_type: ChargebeeFundingType, brand: common_enums::CardNetwork, iin: String, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "snake_case")] pub enum ChargebeeFundingType { Credit, Debit, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "snake_case")] pub enum ChargebeeTranasactionStatus { // Waiting for response from the payment gateway. InProgress, // The transaction is successful. Success, // Transaction failed. Failure, // No response received while trying to charge the card. Timeout, // Indicates that a successful payment transaction has failed now due to a late failure notification from the payment gateway, // typically caused by issues like insufficient funds or a closed bank account. LateFailure, // Connection with Gateway got terminated abruptly. So, status of this transaction needs to be resolved manually NeedsAttention, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeCustomer { pub payment_method: ChargebeePaymentMethod, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeInvoiceBillingAddress { pub line1: Option<Secret<String>>, pub line2: Option<Secret<String>>, pub line3: Option<Secret<String>>, pub state: Option<Secret<String>>, pub country: Option<enums::CountryAlpha2>, pub zip: Option<Secret<String>>, pub city: Option<String>, } #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeePaymentMethod { pub reference_id: String, pub gateway: ChargebeeGateway, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "snake_case")] pub enum ChargebeeGateway { Stripe, Braintree, } impl ChargebeeWebhookBody { pub fn get_webhook_object_from_body(body: &[u8]) -> CustomResult<Self, errors::ConnectorError> { let webhook_body = body .parse_struct::<Self>("ChargebeeWebhookBody") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(webhook_body) } } impl ChargebeeInvoiceBody { pub fn get_invoice_webhook_data_from_body( body: &[u8], ) -> CustomResult<Self, errors::ConnectorError> { let webhook_body = body .parse_struct::<Self>("ChargebeeInvoiceBody") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(webhook_body) } } pub struct ChargebeeMandateDetails { pub customer_id: String, pub mandate_id: String, } impl ChargebeeCustomer { // the logic to find connector customer id & mandate id is different for different gateways, reference : https://apidocs.chargebee.com/docs/api/customers?prod_cat_ver=2#customer_payment_method_reference_id . pub fn find_connector_ids(&self) -> Result<ChargebeeMandateDetails, errors::ConnectorError> { match self.payment_method.gateway { ChargebeeGateway::Stripe | ChargebeeGateway::Braintree => { let mut parts = self.payment_method.reference_id.split('/'); let customer_id = parts .next() .ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)? .to_string(); let mandate_id = parts .next_back() .ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)? .to_string(); Ok(ChargebeeMandateDetails { customer_id, mandate_id, }) } } } } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: ChargebeeWebhookBody) -> Result<Self, Self::Error> { let amount = item.content.transaction.amount; let currency = item.content.transaction.currency_code.to_owned(); let merchant_reference_id = common_utils::id_type::PaymentReferenceId::from_str(&item.content.invoice.id) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let connector_transaction_id = item .content .transaction .id_at_gateway .map(common_utils::types::ConnectorTransactionId::TxnId); let error_code = item.content.transaction.error_code.clone(); let error_message = item.content.transaction.error_text.clone(); let connector_mandate_details = item .content .customer .as_ref() .map(|customer| customer.find_connector_ids()) .transpose()? .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "connector_mandate_details", })?; let connector_account_reference_id = item.content.transaction.gateway_account_id.clone(); let transaction_created_at = item.content.transaction.date; let status = enums::AttemptStatus::from(item.content.transaction.status); let payment_method_type = enums::PaymentMethod::from(item.content.transaction.payment_method); let payment_method_details: ChargebeePaymentMethodDetails = serde_json::from_str(&item.content.transaction.payment_method_details) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let payment_method_sub_type = enums::PaymentMethodType::from(payment_method_details.card.funding_type); // Chargebee retry count will always be less than u16 always. Chargebee can have maximum 12 retry attempts #[allow(clippy::as_conversions)] let retry_count = item .content .invoice .linked_payments .map(|linked_payments| linked_payments.len() as u16); let invoice_next_billing_time = item .content .subscription .as_ref() .and_then(|subscription| subscription.next_billing_at); let invoice_billing_started_at_time = item .content .subscription .as_ref() .and_then(|subscription| subscription.current_term_start); Ok(Self { amount, currency, merchant_reference_id, connector_transaction_id, error_code, error_message, processor_payment_method_token: connector_mandate_details.mandate_id, connector_customer_id: connector_mandate_details.customer_id, connector_account_reference_id, transaction_created_at, status, payment_method_type, payment_method_sub_type, network_advice_code: None, network_decline_code: None, network_error_message: None, retry_count, invoice_next_billing_time, invoice_billing_started_at_time, // This field is none because it is specific to stripebilling. charge_id: None, // Need to populate these card info field card_info: api_models::payments::AdditionalCardInfo { card_network: Some(payment_method_details.card.brand), card_isin: Some(payment_method_details.card.iin), card_issuer: None, card_type: None, card_issuing_country: None, bank_code: None, last4: None, card_extended_bin: None, card_exp_month: None, card_exp_year: None, card_holder_name: None, payment_checks: None, authentication_data: None, is_regulated: None, signature_network: None, }, }) } } impl From<ChargebeeTranasactionStatus> for enums::AttemptStatus { fn from(status: ChargebeeTranasactionStatus) -> Self { match status { ChargebeeTranasactionStatus::InProgress | ChargebeeTranasactionStatus::NeedsAttention => Self::Pending, ChargebeeTranasactionStatus::Success => Self::Charged, ChargebeeTranasactionStatus::Failure | ChargebeeTranasactionStatus::Timeout | ChargebeeTranasactionStatus::LateFailure => Self::Failure, } } } impl From<ChargebeeTransactionPaymentMethod> for enums::PaymentMethod { fn from(payment_method: ChargebeeTransactionPaymentMethod) -> Self { match payment_method { ChargebeeTransactionPaymentMethod::Card => Self::Card, } } } impl From<ChargebeeFundingType> for enums::PaymentMethodType { fn from(funding_type: ChargebeeFundingType) -> Self { match funding_type { ChargebeeFundingType::Credit => Self::Credit, ChargebeeFundingType::Debit => Self::Debit, } } } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] impl From<ChargebeeEventType> for api_models::webhooks::IncomingWebhookEvent { fn from(event: ChargebeeEventType) -> Self { match event { ChargebeeEventType::PaymentSucceeded => Self::RecoveryPaymentSuccess, ChargebeeEventType::PaymentFailed => Self::RecoveryPaymentFailure, ChargebeeEventType::InvoiceDeleted => Self::RecoveryInvoiceCancel, } } } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] impl TryFrom<ChargebeeInvoiceBody> for revenue_recovery::RevenueRecoveryInvoiceData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: ChargebeeInvoiceBody) -> Result<Self, Self::Error> { let merchant_reference_id = common_utils::id_type::PaymentReferenceId::from_str(&item.content.invoice.id) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; // The retry count will never exceed u16 limit in a billing connector. It can have maximum of 12 in case of charge bee so its ok to suppress this #[allow(clippy::as_conversions)] let retry_count = item .content .invoice .linked_payments .as_ref() .map(|linked_payments| linked_payments.len() as u16); let invoice_next_billing_time = item .content .subscription .as_ref() .and_then(|subscription| subscription.next_billing_at); let billing_started_at = item .content .subscription .as_ref() .and_then(|subscription| subscription.current_term_start); Ok(Self { amount: item.content.invoice.total, currency: item.content.invoice.currency_code, merchant_reference_id, billing_address: Some(api_models::payments::Address::from(item.content.invoice)), retry_count, next_billing_at: invoice_next_billing_time, billing_started_at, }) } } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] impl From<ChargebeeInvoiceData> for api_models::payments::Address { fn from(item: ChargebeeInvoiceData) -> Self { Self { address: item .billing_address .map(api_models::payments::AddressDetails::from), phone: None, email: None, } } } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] impl From<ChargebeeInvoiceBillingAddress> for api_models::payments::AddressDetails { fn from(item: ChargebeeInvoiceBillingAddress) -> Self { Self { city: item.city, country: item.country, state: item.state, zip: item.zip, line1: item.line1, line2: item.line2, line3: item.line3, first_name: None, last_name: None, origin_zip: None, } } } #[derive(Debug, Serialize)] pub struct ChargebeeRecordPaymentRequest { #[serde(rename = "transaction[amount]")] pub amount: MinorUnit, #[serde(rename = "transaction[payment_method]")] pub payment_method: ChargebeeRecordPaymentMethod, #[serde(rename = "transaction[id_at_gateway]")] pub connector_payment_id: Option<String>, #[serde(rename = "transaction[status]")] pub status: ChargebeeRecordStatus, } #[derive(Debug, Serialize, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum ChargebeeRecordPaymentMethod { Other, } #[derive(Debug, Serialize, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum ChargebeeRecordStatus { Success, Failure, } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl TryFrom<&ChargebeeRouterData<&RevenueRecoveryRecordBackRouterData>> for ChargebeeRecordPaymentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &ChargebeeRouterData<&RevenueRecoveryRecordBackRouterData>, ) -> Result<Self, Self::Error> { let req = &item.router_data.request; Ok(Self { amount: req.amount, payment_method: ChargebeeRecordPaymentMethod::Other, connector_payment_id: req .connector_transaction_id .as_ref() .map(|connector_payment_id| connector_payment_id.get_id().to_string()), status: ChargebeeRecordStatus::try_from(req.attempt_status)?, }) } } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl TryFrom<enums::AttemptStatus> for ChargebeeRecordStatus { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(status: enums::AttemptStatus) -> Result<Self, Self::Error> { match status { enums::AttemptStatus::Charged | enums::AttemptStatus::PartialCharged | enums::AttemptStatus::PartialChargedAndChargeable => Ok(Self::Success), enums::AttemptStatus::Failure | enums::AttemptStatus::CaptureFailed | enums::AttemptStatus::RouterDeclined => Ok(Self::Failure), enums::AttemptStatus::AuthenticationFailed | enums::AttemptStatus::Started | enums::AttemptStatus::AuthenticationPending | enums::AttemptStatus::AuthenticationSuccessful | enums::AttemptStatus::Authorized | enums::AttemptStatus::PartiallyAuthorized | enums::AttemptStatus::AuthorizationFailed | enums::AttemptStatus::Authorizing | enums::AttemptStatus::CodInitiated | enums::AttemptStatus::Voided | enums::AttemptStatus::VoidedPostCharge | enums::AttemptStatus::VoidInitiated | enums::AttemptStatus::CaptureInitiated | enums::AttemptStatus::VoidFailed | enums::AttemptStatus::AutoRefunded | enums::AttemptStatus::Unresolved | enums::AttemptStatus::Pending | enums::AttemptStatus::PaymentMethodAwaited | enums::AttemptStatus::ConfirmationAwaited | enums::AttemptStatus::DeviceDataCollectionPending | enums::AttemptStatus::IntegrityFailure | enums::AttemptStatus::Expired => Err(errors::ConnectorError::NotSupported { message: "Record back flow is only supported for terminal status".to_string(), connector: "chargebee", } .into()), } } } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ChargebeeRecordbackResponse { pub invoice: ChargebeeRecordbackInvoice, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct ChargebeeRecordbackInvoice { pub id: common_utils::id_type::PaymentReferenceId, } impl TryFrom< ResponseRouterData< RecoveryRecordBack, ChargebeeRecordbackResponse, RevenueRecoveryRecordBackRequest, RevenueRecoveryRecordBackResponse, >, > for RevenueRecoveryRecordBackRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< RecoveryRecordBack, ChargebeeRecordbackResponse, RevenueRecoveryRecordBackRequest, RevenueRecoveryRecordBackResponse, >, ) -> Result<Self, Self::Error> { let merchant_reference_id = item.response.invoice.id; Ok(Self { response: Ok(RevenueRecoveryRecordBackResponse { merchant_reference_id, }), ..item.data }) } }
crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
hyperswitch_connectors
full_file
5,893
null
null
null
null
null
null
null
null
null
null
null
null
null
File: crates/openapi/src/routes.rs #![allow(unused)] pub mod api_keys; pub mod authentication; pub mod blocklist; pub mod customers; pub mod disputes; pub mod gsm; pub mod mandates; pub mod merchant_account; pub mod merchant_connector_account; pub mod organization; pub mod payment_link; pub mod payment_method; pub mod payments; pub mod payouts; pub mod platform; pub mod poll; pub mod profile; pub mod profile_acquirer; pub mod proxy; pub mod refunds; pub mod relay; pub mod revenue_recovery; pub mod routing; pub mod three_ds_decision_rule; pub mod tokenization; pub mod webhook_events;
crates/openapi/src/routes.rs
openapi
full_file
134
null
null
null
null
null
null
null
null
null
null
null
null
null
pub fn get_trustpay_response( response: TrustpayPaymentsResponse, status_code: u16, previous_attempt_status: enums::AttemptStatus, ) -> CustomResult< ( enums::AttemptStatus, Option<ErrorResponse>, PaymentsResponseData, ), errors::ConnectorError, > { match response { TrustpayPaymentsResponse::CardsPayments(response) => { handle_cards_response(*response, status_code) } TrustpayPaymentsResponse::BankRedirectPayments(response) => { handle_bank_redirects_response(*response) } TrustpayPaymentsResponse::BankRedirectSync(response) => { handle_bank_redirects_sync_response(*response, status_code) } TrustpayPaymentsResponse::BankRedirectError(response) => { handle_bank_redirects_error_response(*response, status_code, previous_attempt_status) } TrustpayPaymentsResponse::WebhookResponse(response) => { handle_webhook_response(*response, status_code) } } }
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
hyperswitch_connectors
function_signature
208
rust
null
null
null
null
get_trustpay_response
null
null
null
null
null
null
null
pub struct GpayInfo { pub payment_token: Option<Secret<String>>, }
crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
hyperswitch_connectors
struct_definition
17
rust
GpayInfo
null
null
null
null
null
null
null
null
null
null
null
pub struct EbanxFulfillResponse { #[serde(rename = "type")] status: EbanxFulfillStatus, message: String, }
crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs
hyperswitch_connectors
struct_definition
31
rust
EbanxFulfillResponse
null
null
null
null
null
null
null
null
null
null
null
pub struct MerchantConnectorWebhookDetails { #[schema(value_type = String, example = "12345678900987654321")] pub merchant_secret: Secret<String>, #[schema(value_type = String, example = "12345678900987654321")] pub additional_secret: Option<Secret<String>>, }
crates/api_models/src/admin.rs
api_models
struct_definition
91
rust
MerchantConnectorWebhookDetails
null
null
null
null
null
null
null
null
null
null
null
impl Barclaycard { pub fn generate_digest(&self, payload: &[u8]) -> String { let payload_digest = digest::digest(&digest::SHA256, payload); consts::BASE64_ENGINE.encode(payload_digest) } pub fn generate_signature( &self, auth: barclaycard::BarclaycardAuthType, host: String, resource: &str, payload: &String, date: OffsetDateTime, http_method: Method, ) -> CustomResult<String, errors::ConnectorError> { let barclaycard::BarclaycardAuthType { api_key, merchant_account, api_secret, } = auth; let is_post_method = matches!(http_method, Method::Post); let digest_str = if is_post_method { "digest " } else { "" }; let headers = format!("host date (request-target) {digest_str}{V_C_MERCHANT_ID}"); let request_target = if is_post_method { format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n") } else { format!("(request-target): get {resource}\n") }; let signature_string = format!( "host: {host}\ndate: {date}\n{request_target}{V_C_MERCHANT_ID}: {}", merchant_account.peek() ); let key_value = consts::BASE64_ENGINE .decode(api_secret.expose()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "connector_account_details.api_secret", })?; let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value); let signature_value = consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref()); let signature_header = format!( r#"keyid="{}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""#, api_key.peek() ); Ok(signature_header) } }
crates/hyperswitch_connectors/src/connectors/barclaycard.rs
hyperswitch_connectors
impl_block
446
rust
null
Barclaycard
null
impl Barclaycard
null
null
null
null
null
null
null
null
pub struct StoredCredentials { pub sequence: Sequence, pub initiator: Initiator, pub is_scheduled: bool, pub cardbrand_original_transaction_id: Option<Secret<String>>, }
crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
hyperswitch_connectors
struct_definition
40
rust
StoredCredentials
null
null
null
null
null
null
null
null
null
null
null
pub struct PayuAuthUpdateRequest { grant_type: String, client_id: Secret<String>, client_secret: Secret<String>, }
crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
hyperswitch_connectors
struct_definition
29
rust
PayuAuthUpdateRequest
null
null
null
null
null
null
null
null
null
null
null
pub struct PaymentAddress { shipping: Option<Address>, billing: Option<Address>, unified_payment_method_billing: Option<Address>, payment_method_billing: Option<Address>, }
crates/hyperswitch_domain_models/src/payment_address.rs
hyperswitch_domain_models
struct_definition
35
rust
PaymentAddress
null
null
null
null
null
null
null
null
null
null
null
pub fn new(time_bucket: Option<String>) -> Self { Self { time_bucket } }
crates/api_models/src/analytics/active_payments.rs
api_models
function_signature
20
rust
null
null
null
null
new
null
null
null
null
null
null
null
pub async fn switch_merchant_for_user_in_org( state: SessionState, request: user_api::SwitchMerchantRequest, user_from_token: auth::UserFromToken, ) -> UserResponse<user_api::TokenResponse> { if user_from_token.merchant_id == request.merchant_id { return Err(UserErrors::InvalidRoleOperationWithMessage( "User switching to same merchant".to_string(), ) .into()); } let key_manager_state = &(&state).into(); let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve role information")?; // Check if the role is internal and handle separately let (org_id, merchant_id, profile_id, role_id) = if role_info.is_internal() { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &request.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(UserErrors::MerchantIdNotFound)?; let merchant_account = state .store .find_merchant_account_by_merchant_id( key_manager_state, &request.merchant_id, &merchant_key_store, ) .await .to_not_found_response(UserErrors::MerchantIdNotFound)?; let profile_id = state .store .list_profile_by_merchant_id( key_manager_state, &merchant_key_store, &request.merchant_id, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to list business profiles by merchant_id")? .pop() .ok_or(UserErrors::InternalServerError) .attach_printable("No business profile found for the given merchant_id")? .get_id() .to_owned(); ( merchant_account.organization_id, request.merchant_id, profile_id, user_from_token.role_id.clone(), ) } else { // Match based on the other entity types match role_info.get_entity_type() { EntityType::Tenant | EntityType::Organization => { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &request.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(UserErrors::MerchantIdNotFound)?; let merchant_id = state .store .find_merchant_account_by_merchant_id( key_manager_state, &request.merchant_id, &merchant_key_store, ) .await .change_context(UserErrors::MerchantIdNotFound)? .organization_id .eq(&user_from_token.org_id) .then(|| request.merchant_id.clone()) .ok_or_else(|| { UserErrors::InvalidRoleOperationWithMessage( "No such merchant_id found for the user in the org".to_string(), ) })?; let profile_id = state .store .list_profile_by_merchant_id( key_manager_state, &merchant_key_store, &merchant_id, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to list business profiles by merchant_id")? .pop() .ok_or(UserErrors::InternalServerError) .attach_printable("No business profile found for the merchant_id")? .get_id() .to_owned(); ( user_from_token.org_id.clone(), merchant_id, profile_id, user_from_token.role_id.clone(), ) } EntityType::Merchant | EntityType::Profile => { let user_role = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: Some(&request.merchant_id), profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: Some(1), }) .await .change_context(UserErrors::InternalServerError) .attach_printable( "Failed to list user roles for the given user_id, org_id and merchant_id", )? .pop() .ok_or(UserErrors::InvalidRoleOperationWithMessage( "No user role associated with the requested merchant_id".to_string(), ))?; let (merchant_id, profile_id) = utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role) .await?; ( user_from_token.org_id, merchant_id, profile_id, user_role.role_id, ) } } }; let lineage_context = LineageContext { user_id: user_from_token.user_id.clone(), merchant_id: merchant_id.clone(), role_id: role_id.clone(), org_id: org_id.clone(), profile_id: profile_id.clone(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id) .clone(), }; utils::user::spawn_async_lineage_context_update_to_db( &state, &user_from_token.user_id, lineage_context, ); let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, merchant_id.clone(), org_id.clone(), role_id.clone(), profile_id, user_from_token.tenant_id.clone(), ) .await?; utils::user_role::set_role_info_in_cache_by_role_id_org_id( &state, &role_id, &org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await; let response = user_api::TokenResponse { token: token.clone(), token_type: common_enums::TokenPurpose::UserInfo, }; auth::cookies::set_cookie_response(response, token) }
crates/router/src/core/user.rs
router
function_signature
1,424
rust
null
null
null
null
switch_merchant_for_user_in_org
null
null
null
null
null
null
null
impl api::RefundSync for Authipay {}
crates/hyperswitch_connectors/src/connectors/authipay.rs
hyperswitch_connectors
impl_block
10
rust
null
Authipay
api::RefundSync for
impl api::RefundSync for for Authipay
null
null
null
null
null
null
null
null
impl api::PaymentSync for Bambora {}
crates/hyperswitch_connectors/src/connectors/bambora.rs
hyperswitch_connectors
impl_block
10
rust
null
Bambora
api::PaymentSync for
impl api::PaymentSync for for Bambora
null
null
null
null
null
null
null
null
pub struct AttributeResponse { vault: PaypalVaultResponse, }
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
hyperswitch_connectors
struct_definition
13
rust
AttributeResponse
null
null
null
null
null
null
null
null
null
null
null
impl ConnectorSpecifications for Vgs {}
crates/hyperswitch_connectors/src/connectors/vgs.rs
hyperswitch_connectors
impl_block
7
rust
null
Vgs
ConnectorSpecifications for
impl ConnectorSpecifications for for Vgs
null
null
null
null
null
null
null
null
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, } }
crates/router/src/core/payment_methods/tokenize/card_executor.rs
router
function_signature
97
rust
null
null
null
null
build
null
null
null
null
null
null
null
pub struct PanMetadataUpdateBody { pub card: NetworkTokenRequestorData, }
crates/router/src/types/payment_methods.rs
router
struct_definition
18
rust
PanMetadataUpdateBody
null
null
null
null
null
null
null
null
null
null
null
impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(&self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .as_ref() .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self .email .clone() .or(other.and_then(|other| other.email.clone())), phone: { self.phone .clone() .and_then(|phone_details| { if phone_details.number.is_some() { Some(phone_details) } else { None } }) .or_else(|| other.and_then(|other| other.phone.clone())) }, } } }
crates/hyperswitch_domain_models/src/address.rs
hyperswitch_domain_models
impl_block
192
rust
null
Address
null
impl Address
null
null
null
null
null
null
null
null
File: crates/router/tests/connectors/cybersource.rs use std::str::FromStr; use common_utils::pii::Email; use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentAuthorizeType}, }; struct Cybersource; impl ConnectorActions for Cybersource {} impl utils::Connector for Cybersource { fn get_data(&self) -> api::ConnectorData { use router::connector::Cybersource; utils::construct_connector_data_old( Box::new(Cybersource::new()), types::Connector::Cybersource, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .cybersource .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "cybersource".to_string() } } fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { currency: enums::Currency::USD, email: Some(Email::from_str("abc@gmail.com").unwrap()), ..PaymentAuthorizeType::default().0 }) } #[actix_web::test] async fn should_only_authorize_payment() { let response = Cybersource {} .authorize_payment( get_default_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); } #[actix_web::test] async fn should_make_payment() { let response = Cybersource {} .make_payment( get_default_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Pending); } #[actix_web::test] async fn should_capture_already_authorized_payment() { let connector = Cybersource {}; let response = connector .authorize_and_capture_payment( get_default_payment_authorize_data(), None, get_default_payment_info(), ) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Pending); } #[actix_web::test] async fn should_partially_capture_already_authorized_payment() { let connector = Cybersource {}; let response = connector .authorize_and_capture_payment( get_default_payment_authorize_data(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Pending); } #[actix_web::test] #[ignore = "Status field is missing in the response, Communication is being done with cybersource team"] async fn should_sync_payment() { let connector = Cybersource {}; let response = connector .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "6699597903496176903954".to_string(), ), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_void_already_authorized_payment() { let connector = Cybersource {}; let response = connector .authorize_and_void_payment( get_default_payment_authorize_data(), Some(types::PaymentsCancelData { connector_transaction_id: "".to_string(), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Voided); } #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("13".to_string()), ..utils::CCardType::default().0 }), ..get_default_payment_authorize_data().unwrap() }), get_default_payment_info(), ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!( x.message, "Declined - One or more fields in the request contains invalid data", ); assert_eq!( x.reason, Some("paymentInformation.card.expirationMonth : INVALID_DATA".to_string()) ); } #[actix_web::test] async fn should_fail_payment_for_invalid_exp_year() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2022".to_string()), ..utils::CCardType::default().0 }), ..get_default_payment_authorize_data().unwrap() }), get_default_payment_info(), ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!(x.message, "Decline - Expired card. You might also receive this if the expiration date you provided does not match the date the issuing bank has on file."); } #[actix_web::test] async fn should_fail_payment_for_invalid_card_cvc() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("9123456789".to_string()), ..utils::CCardType::default().0 }), ..get_default_payment_authorize_data().unwrap() }), get_default_payment_info(), ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!( x.message, "Declined - One or more fields in the request contains invalid data", ); assert_eq!( x.reason, Some("paymentInformation.card.securityCode : INVALID_DATA".to_string()) ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_reversed_payment() { let connector = Cybersource {}; // Authorize let authorize_response = connector .make_payment( get_default_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); // Void let void_response = connector .void_payment("6736046645576085004953".to_string(), None, None) .await .unwrap(); let res = void_response.response.unwrap_err(); assert_eq!( res.message, "Decline - The authorization has already been reversed." ); } #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let connector = Cybersource {}; let response = connector .capture_payment("12345".to_string(), None, get_default_payment_info()) .await .unwrap(); let err = response.response.unwrap_err(); assert_eq!( err.message, "Declined - One or more fields in the request contains invalid data" ); assert_eq!(err.code, "InvalidData".to_string()); } #[actix_web::test] async fn should_refund_succeeded_payment() { let connector = Cybersource {}; let response = connector .make_payment_and_refund( get_default_payment_authorize_data(), None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } #[actix_web::test] #[ignore = "Connector Error, needs to be looked into and fixed"] async fn should_refund_manually_captured_payment() { let connector = Cybersource {}; let response = connector .auth_capture_and_refund( get_default_payment_authorize_data(), None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let connector = Cybersource {}; let refund_response = connector .make_payment_and_refund( get_default_payment_authorize_data(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_partially_refund_manually_captured_payment() { let connector = Cybersource {}; let response = connector .auth_capture_and_refund( get_default_payment_authorize_data(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } #[actix_web::test] async fn should_fail_refund_for_invalid_amount() { let connector = Cybersource {}; let response = connector .make_payment_and_refund( get_default_payment_authorize_data(), Some(types::RefundsData { refund_amount: 15000, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } #[actix_web::test] #[ignore = "Status field is missing in the response, Communication is being done with cybersource team"] async fn should_sync_refund() { let connector = Cybersource {}; let response = connector .rsync_retry_till_status_matches( enums::RefundStatus::Success, "6699597076726585603955".to_string(), None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_sync_manually_captured_refund() {} #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_refund_auto_captured_payment() {} #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_refund_succeeded_payment_multiple_times() {} #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_fail_for_refund_amount_higher_than_payment_amount() {}
crates/router/tests/connectors/cybersource.rs
router
full_file
2,880
null
null
null
null
null
null
null
null
null
null
null
null
null
impl ConnectorCommon for Payu { fn id(&self) -> &'static str { "payu" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.payu.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = payu::PayuAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: payu::PayuErrorResponse = res .response .parse_struct("Payu ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.status.status_code, message: response.status.status_desc, reason: response.status.code_literal, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } }
crates/hyperswitch_connectors/src/connectors/payu.rs
hyperswitch_connectors
impl_block
369
rust
null
Payu
ConnectorCommon for
impl ConnectorCommon for for Payu
null
null
null
null
null
null
null
null
impl api::RefundSync for Worldpayvantiv {}
crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
hyperswitch_connectors
impl_block
12
rust
null
Worldpayvantiv
api::RefundSync for
impl api::RefundSync for for Worldpayvantiv
null
null
null
null
null
null
null
null
pub struct ElavonErrorResponse { error_code: Option<String>, error_message: String, error_name: String, }
crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs
hyperswitch_connectors
struct_definition
27
rust
ElavonErrorResponse
null
null
null
null
null
null
null
null
null
null
null
impl HashedApiKey { pub fn into_inner(self) -> String { self.0 } }
crates/diesel_models/src/api_keys.rs
diesel_models
impl_block
23
rust
null
HashedApiKey
null
impl HashedApiKey
null
null
null
null
null
null
null
null
pub struct CardData { pub card_number: CardNumber, pub exp_month: Secret<String>, pub exp_year: Secret<String>, pub card_security_code: Option<Secret<String>>, }
crates/router/src/types/payment_methods.rs
router
struct_definition
41
rust
CardData
null
null
null
null
null
null
null
null
null
null
null
OpenAPI Block Path: paths."/events/{merchant_id}/{event_id}/retry" { "post": { "tags": [ "Event" ], "summary": "Events - Manual Retry", "description": "Manually retry the delivery of the specified Event.", "operationId": "Manually retry the delivery of an Event", "parameters": [ { "name": "merchant_id", "in": "path", "description": "The unique identifier for the Merchant Account.", "required": true, "schema": { "type": "string" } }, { "name": "event_id", "in": "path", "description": "The unique identifier for the Event", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "The delivery of the Event was attempted. Check the `response` field in the response payload to identify the status of the delivery attempt.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/EventRetrieveResponse" } } } } }, "security": [ { "admin_api_key": [] } ] } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
289
.json
null
null
null
null
null
openapi_spec
paths
[ "/events/{merchant_id}/{event_id}/retry" ]
null
null
null
null
/// get_requires_cvv_key pub fn get_requires_cvv_key(&self) -> String { format!("{}_requires_cvv", self.get_string_repr()) }
crates/common_utils/src/id_type/merchant.rs
common_utils
function_signature
36
rust
null
null
null
null
get_requires_cvv_key
null
null
null
null
null
null
null
pub async fn list_routing_configs_for_profile( state: web::Data<AppState>, req: HttpRequest, query: web::Query<RoutingRetrieveQuery>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { let flow = Flow::RoutingRetrieveDictionary; Box::pin(oss_api::server_wrap( flow, state, &req, query.into_inner(), |state, auth: auth::AuthenticationData, query_params, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_merchant_routing_dictionary( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), query_params.clone(), transaction_type .or(query_params.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/routing.rs
router
function_signature
273
rust
null
null
null
null
list_routing_configs_for_profile
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/aci/aci_result_codes.rs pub(super) const FAILURE_CODES: [&str; 501] = [ "100.370.100", "100.370.110", "100.370.111", "100.380.100", "100.380.101", "100.380.110", "100.380.201", "100.380.305", "100.380.306", "100.380.401", "100.380.501", "100.395.502", "100.396.101", "100.400.000", "100.400.001", "100.400.002", "100.400.005", "100.400.007", "100.400.020", "100.400.021", "100.400.030", "100.400.039", "100.400.040", "100.400.041", "100.400.042", "100.400.043", "100.400.044", "100.400.045", "100.400.051", "100.400.060", "100.400.061", "100.400.063", "100.400.064", "100.400.065", "100.400.071", "100.400.080", "100.400.081", "100.400.083", "100.400.084", "100.400.085", "100.400.086", "100.400.087", "100.400.091", "100.400.100", "100.400.120", "100.400.121", "100.400.122", "100.400.123", "100.400.130", "100.400.139", "100.400.140", "100.400.141", "100.400.142", "100.400.143", "100.400.144", "100.400.145", "100.400.146", "100.400.147", "100.400.148", "100.400.149", "100.400.150", "100.400.151", "100.400.152", "100.400.241", "100.400.242", "100.400.243", "100.400.260", "100.400.300", "100.400.301", "100.400.302", "100.400.303", "100.400.304", "100.400.305", "100.400.306", "100.400.307", "100.400.308", "100.400.309", "100.400.310", "100.400.311", "100.400.312", "100.400.313", "100.400.314", "100.400.315", "100.400.316", "100.400.317", "100.400.318", "100.400.319", "100.400.320", "100.400.321", "100.400.322", "100.400.323", "100.400.324", "100.400.325", "100.400.326", "100.400.327", "100.400.328", "800.400.100", "800.400.101", "800.400.102", "800.400.103", "800.400.104", "800.400.105", "800.400.110", "800.400.150", "800.400.151", "100.380.401", "100.390.101", "100.390.102", "100.390.103", "100.390.104", "100.390.105", "100.390.106", "100.390.107", "100.390.108", "100.390.109", "100.390.110", "100.390.111", "100.390.112", "100.390.113", "100.390.114", "100.390.115", "100.390.116", "100.390.117", "100.390.118", "800.400.200", "100.100.701", "800.200.159", "800.200.160", "800.200.165", "800.200.202", "800.200.208", "800.200.220", "800.300.101", "800.300.102", "800.300.200", "800.300.301", "800.300.302", "800.300.401", "800.300.500", "800.300.501", "800.310.200", "800.310.210", "800.310.211", "800.110.100", "800.120.100", "800.120.101", "800.120.102", "800.120.103", "800.120.200", "800.120.201", "800.120.202", "800.120.203", "800.120.300", "800.120.401", "800.130.100", "800.140.100", "800.140.101", "800.140.110", "800.140.111", "800.140.112", "800.140.113", "800.150.100", "800.160.100", "800.160.110", "800.160.120", "800.160.130", "500.100.201", "500.100.202", "500.100.203", "500.100.301", "500.100.302", "500.100.303", "500.100.304", "500.100.401", "500.100.402", "500.100.403", "500.200.101", "600.200.100", "600.200.200", "600.200.201", "600.200.202", "600.200.300", "600.200.310", "600.200.400", "600.200.500", "600.200.501", "600.200.600", "600.200.700", "600.200.800", "600.200.810", "600.300.101", "600.300.200", "600.300.210", "600.300.211", "800.121.100", "800.121.200", "100.150.100", "100.150.101", "100.150.200", "100.150.201", "100.150.202", "100.150.203", "100.150.204", "100.150.205", "100.150.300", "100.350.100", "100.350.101", "100.350.200", "100.350.201", "100.350.301", "100.350.302", "100.350.303", "100.350.310", "100.350.311", "100.350.312", "100.350.313", "100.350.314", "100.350.315", "100.350.316", "100.350.400", "100.350.500", "100.350.601", "100.350.602", "100.250.100", "100.250.105", "100.250.106", "100.250.107", "100.250.110", "100.250.111", "100.250.120", "100.250.121", "100.250.122", "100.250.123", "100.250.124", "100.250.125", "100.250.250", "100.360.201", "100.360.300", "100.360.303", "100.360.400", "700.100.100", "700.100.200", "700.100.300", "700.100.400", "700.100.500", "700.100.600", "700.100.700", "700.100.701", "700.100.710", "700.300.100", "700.300.200", "700.300.300", "700.300.400", "700.300.500", "700.300.600", "700.300.700", "700.300.800", "700.400.000", "700.400.100", "700.400.101", "700.400.200", "700.400.300", "700.400.400", "700.400.402", "700.400.410", "700.400.411", "700.400.420", "700.400.510", "700.400.520", "700.400.530", "700.400.540", "700.400.550", "700.400.560", "700.400.561", "700.400.562", "700.400.565", "700.400.570", "700.400.580", "700.400.590", "700.400.600", "700.400.700", "700.450.001", "700.500.001", "700.500.002", "700.500.003", "700.500.004", "100.300.101", "100.300.200", "100.300.300", "100.300.400", "100.300.401", "100.300.402", "100.300.501", "100.300.600", "100.300.601", "100.300.700", "100.300.701", "100.370.100", "100.370.101", "100.370.102", "100.370.110", "100.370.111", "100.370.121", "100.370.122", "100.370.123", "100.370.124", "100.370.125", "100.370.131", "100.370.132", "100.500.101", "100.500.201", "100.500.301", "100.500.302", "100.500.303", "100.500.304", "100.600.500", "100.900.500", "200.100.101", "200.100.102", "200.100.103", "200.100.150", "200.100.151", "200.100.199", "200.100.201", "200.100.300", "200.100.301", "200.100.302", "200.100.401", "200.100.402", "200.100.403", "200.100.404", "200.100.501", "200.100.502", "200.100.503", "200.100.504", "200.100.601", "200.100.602", "200.100.603", "200.200.106", "200.300.403", "200.300.404", "200.300.405", "200.300.406", "200.300.407", "800.900.100", "800.900.101", "800.900.200", "800.900.201", "800.900.300", "800.900.301", "800.900.302", "800.900.303", "800.900.399", "800.900.401", "800.900.450", "100.800.100", "100.800.101", "100.800.102", "100.800.200", "100.800.201", "100.800.202", "100.800.300", "100.800.301", "100.800.302", "100.800.400", "100.800.401", "100.800.500", "100.800.501", "100.700.100", "100.700.101", "100.700.200", "100.700.201", "100.700.300", "100.700.400", "100.700.500", "100.700.800", "100.700.801", "100.700.802", "100.700.810", "100.900.100", "100.900.101", "100.900.105", "100.900.200", "100.900.300", "100.900.301", "100.900.400", "100.900.401", "100.900.450", "100.900.500", "100.100.100", "100.100.101", "100.100.104", "100.100.200", "100.100.201", "100.100.300", "100.100.301", "100.100.303", "100.100.304", "100.100.305", "100.100.400", "100.100.401", "100.100.402", "100.100.500", "100.100.501", "100.100.600", "100.100.601", "100.100.650", "100.100.651", "100.100.700", "100.100.701", "100.200.100", "100.200.103", "100.200.104", "100.200.200", "100.210.101", "100.210.102", "100.211.101", "100.211.102", "100.211.103", "100.211.104", "100.211.105", "100.211.106", "100.212.101", "100.212.102", "100.212.103", "100.550.300", "100.550.301", "100.550.303", "100.550.310", "100.550.311", "100.550.312", "100.550.400", "100.550.401", "100.550.601", "100.550.603", "100.550.605", "100.550.701", "100.550.702", "100.380.101", "100.380.201", "100.380.305", "100.380.306", "800.100.100", "800.100.150", "800.100.151", "800.100.152", "800.100.153", "800.100.154", "800.100.155", "800.100.156", "800.100.157", "800.100.158", "800.100.159", "800.100.160", "800.100.161", "800.100.162", "800.100.163", "800.100.164", "800.100.165", "800.100.166", "800.100.167", "800.100.168", "800.100.169", "800.100.170", "800.100.171", "800.100.172", "800.100.173", "800.100.174", "800.100.175", "800.100.176", "800.100.177", "800.100.178", "800.100.179", "800.100.190", "800.100.191", "800.100.192", "800.100.195", "800.100.196", "800.100.197", "800.100.198", "800.100.199", "800.100.200", "800.100.201", "800.100.202", "800.100.203", "800.100.204", "800.100.205", "800.100.206", "800.100.207", "800.100.208", "800.100.402", "800.100.403", "800.100.500", "800.100.501", "800.700.100", "800.700.101", "800.700.201", "800.700.500", "800.800.102", "800.800.202", "800.800.302", ]; pub(super) const SUCCESSFUL_CODES: [&str; 16] = [ "000.000.000", "000.000.100", "000.100.105", "000.100.106", "000.100.110", "000.100.111", "000.100.112", "000.300.000", "000.300.100", "000.300.101", "000.300.102", "000.300.103", "000.310.100", "000.310.101", "000.310.110", "000.600.000", ]; pub(super) const PENDING_CODES: [&str; 26] = [ "000.400.000", "000.400.010", "000.400.020", "000.400.040", "000.400.050", "000.400.060", "000.400.070", "000.400.080", "000.400.081", "000.400.082", "000.400.090", "000.400.091", "000.400.100", "000.400.110", "000.200.000", "000.200.001", "000.200.100", "000.200.101", "000.200.102", "000.200.103", "000.200.200", "000.200.201", "100.400.500", "800.400.500", "800.400.501", "800.400.502", ];
crates/hyperswitch_connectors/src/connectors/aci/aci_result_codes.rs
hyperswitch_connectors
full_file
7,676
null
null
null
null
null
null
null
null
null
null
null
null
null
File: crates/router/src/core/payments/operations/payment_status.rs Public functions: 1 Public structs: 1 use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments::{ helpers, operations, types as payment_types, CustomerDetails, PaymentAddress, PaymentData, }, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api, domain, storage::{self, enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "sync")] pub struct PaymentStatus; type PaymentStatusOperation<'b, F, R> = BoxedOperation<'b, F, R, PaymentData<F>>; impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for PaymentStatus { type Data = PaymentData<F>; fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> { Ok(self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> { Ok(self) } } impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for &PaymentStatus { type Data = PaymentData<F>; fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> { Ok(*self) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> { Ok(*self) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentStatus { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::Customer>, ), errors::StorageError, > { helpers::create_customer_if_not_exist( state, Box::new(self), payment_data, request, &key_store.merchant_id, key_store, storage_scheme, ) .await } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } #[instrument(skip_all)] async fn add_task_to_process_tracker<'a>( &'a self, state: &'a SessionState, payment_attempt: &storage::PaymentAttempt, requeue: bool, schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { helpers::add_domain_task_to_pt(self, state, payment_attempt, requeue, schedule_time).await } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, request: &api::PaymentsRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, request.routing.clone()).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentStatus { async fn update_trackers<'b>( &'b self, _state: &'b SessionState, req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRequest>, PaymentData<F>, )> where F: 'b + Send, { req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentStatus)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { async fn update_trackers<'b>( &'b self, _state: &'b SessionState, req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>, PaymentData<F>, )> where F: 'b + Send, { req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentStatus)) .with(payment_data.to_event()) .emit(); Ok((Box::new(self), payment_data)) } } #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsRetrieveRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>, > { Box::pin(get_tracker_for_sync( payment_id, &merchant_context.clone(), state, request, self, merchant_context.get_merchant_account().storage_scheme, )) .await } } #[cfg(feature = "v2")] async fn get_tracker_for_sync< 'a, F: Send + Clone, Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync, >( _payment_id: &api::PaymentIdType, _merchant_context: &domain::MerchantContext, _state: &SessionState, _request: &api::PaymentsRetrieveRequest, _operation: Op, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>> { todo!() } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn get_tracker_for_sync< 'a, F: Send + Clone, Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync, >( payment_id: &api::PaymentIdType, merchant_context: &domain::MerchantContext, state: &SessionState, request: &api::PaymentsRetrieveRequest, operation: Op, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>> { let (payment_intent, mut payment_attempt, currency, amount); (payment_intent, payment_attempt) = get_payment_intent_payment_attempt( state, payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), storage_scheme, ) .await?; helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; let payment_id = payment_attempt.payment_id.clone(); currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await?; payment_attempt.encoded_data.clone_from(&request.param); let db = &*state.store; let key_manager_state = &state.into(); let attempts = match request.expand_attempts { Some(true) => { Some(db .find_attempts_by_merchant_id_payment_id(merchant_context.get_merchant_account().get_id(), &payment_id, storage_scheme) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving attempt list for, merchant_id: {:?}, payment_id: {payment_id:?}",merchant_context.get_merchant_account().get_id()) })?) }, _ => None, }; let multiple_capture_data = if payment_attempt.multiple_capture_count > Some(0) { let captures = db .find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &payment_attempt.merchant_id, &payment_attempt.payment_id, &payment_attempt.attempt_id, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving capture list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_context.get_merchant_account().get_id()) })?; Some(payment_types::MultipleCaptureData::new_for_sync( captures, request.expand_captures, )?) } else { None }; let refunds = db .find_refund_by_payment_id_merchant_id( &payment_id, merchant_context.get_merchant_account().get_id(), storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( "Failed while getting refund list for, payment_id: {:?}, merchant_id: {:?}", &payment_id, merchant_context.get_merchant_account().get_id() ) })?; let authorizations = db .find_all_authorizations_by_merchant_id_payment_id( merchant_context.get_merchant_account().get_id(), &payment_id, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!( "Failed while getting authorizations list for, payment_id: {:?}, merchant_id: {:?}", &payment_id, merchant_context.get_merchant_account().get_id() ) })?; let disputes = db .find_disputes_by_merchant_id_payment_id(merchant_context.get_merchant_account().get_id(), &payment_id) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_context.get_merchant_account().get_id()) })?; let frm_response = if cfg!(feature = "frm") { db.find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_context.get_merchant_account().get_id().clone()) .await .change_context(errors::ApiErrorResponse::PaymentNotFound) .attach_printable_lazy(|| { format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_context.get_merchant_account().get_id()) }) .ok() } else { None }; let contains_encoded_data = payment_attempt.encoded_data.is_some(); let creds_identifier = request .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); request .merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config( db, merchant_context.get_merchant_account().get_id(), mcd, ) .await }) .await .transpose()?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_method_info = if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() { match db .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), payment_method_id, storage_scheme, ) .await { Ok(payment_method) => Some(payment_method), Err(error) => { if error.current_context().is_db_not_found() { logger::info!("Payment Method not found in db {:?}", error); None } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error retrieving payment method from db")? } } } } else { None }; let merchant_id = payment_intent.merchant_id.clone(); let authentication_store = if let Some(ref authentication_id) = payment_attempt.authentication_id { let authentication = db .find_authentication_by_merchant_id_authentication_id(&merchant_id, authentication_id) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Error while fetching authentication record with authentication_id {}", authentication_id.get_string_repr() ) })?; Some( hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore { authentication, cavv: None, // marking this as None since we don't need authentication value in payment status flow }, ) } else { None }; let payment_link_data = payment_intent .payment_link_id .as_ref() .async_map(|id| crate::core::payments::get_payment_link_response_from_id(state, id)) .await .transpose()?; let payment_data = PaymentData { flow: PhantomData, payment_intent, currency, amount, email: None, mandate_id: payment_attempt .mandate_id .clone() .map(|id| api_models::payments::MandateIds { mandate_id: Some(id), mandate_reference_id: None, }), mandate_connector: None, setup_mandate: None, customer_acceptance: None, token: None, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), token_data: None, confirm: Some(request.force_sync), payment_method_data: None, payment_method_token: None, payment_method_info, force_sync: Some( request.force_sync && (helpers::check_force_psync_precondition(payment_attempt.status) || contains_encoded_data), ), all_keys_required: request.all_keys_required, payment_attempt, refunds, disputes, attempts, sessions_token: vec![], card_cvc: None, creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data, redirect_response: None, payment_link_data, surcharge_details: None, frm_message: frm_response, incremental_authorization_details: None, authorizations, authentication: authentication_store, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(operation), customer_details: None, payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRetrieveRequest, PaymentData<F>> for PaymentStatus { fn validate_request<'b>( &'b self, request: &api::PaymentsRetrieveRequest, merchant_context: &domain::MerchantContext, ) -> RouterResult<( PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>, operations::ValidateResult, )> { let request_merchant_id = request.merchant_id.as_ref(); helpers::validate_merchant_id( merchant_context.get_merchant_account().get_id(), request_merchant_id, ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), })?; Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: request.resource_id.clone(), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } } pub async fn get_payment_intent_payment_attempt( state: &SessionState, payment_id: &api::PaymentIdType, merchant_id: &common_utils::id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<(storage::PaymentIntent, storage::PaymentAttempt)> { let key_manager_state: KeyManagerState = state.into(); let db = &*state.store; let get_pi_pa = || async { let (pi, pa); match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => { pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, id, merchant_id, key_store, storage_scheme, ) .await?; pa = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &pi.payment_id, merchant_id, pi.active_attempt.get_id().as_str(), storage_scheme, ) .await?; } api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => { pa = db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, id, storage_scheme, ) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => { pa = db .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } api_models::payments::PaymentIdType::PreprocessingId(ref id) => { pa = db .find_payment_attempt_by_preprocessing_id_merchant_id( id, merchant_id, storage_scheme, ) .await?; pi = db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &pa.payment_id, merchant_id, key_store, storage_scheme, ) .await?; } } error_stack::Result::<_, errors::StorageError>::Ok((pi, pa)) }; get_pi_pa() .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) // TODO (#7195): Add platform merchant account validation once client_secret auth is solved }
crates/router/src/core/payments/operations/payment_status.rs
router
full_file
4,998
null
null
null
null
null
null
null
null
null
null
null
null
null
impl api::Refund for Juspaythreedsserver {}
crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs
hyperswitch_connectors
impl_block
14
rust
null
Juspaythreedsserver
api::Refund for
impl api::Refund for for Juspaythreedsserver
null
null
null
null
null
null
null
null
impl api::ExternalVaultCreate for HyperswitchVault {}
crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
hyperswitch_connectors
impl_block
12
rust
null
HyperswitchVault
api::ExternalVaultCreate for
impl api::ExternalVaultCreate for for HyperswitchVault
null
null
null
null
null
null
null
null
pub fn get_payout_attempt_id(payout_id: &str, attempt_count: i16) -> String { format!("{payout_id}_{attempt_count}") }
crates/router/src/utils.rs
router
function_signature
35
rust
null
null
null
null
get_payout_attempt_id
null
null
null
null
null
null
null
pub struct KlarnaCheckoutRequestData { merchant_urls: MerchantURLs, options: CheckoutOptions, }
crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs
hyperswitch_connectors
struct_definition
23
rust
KlarnaCheckoutRequestData
null
null
null
null
null
null
null
null
null
null
null
pub fn get_id(&self) -> &id_type::GlobalCustomerId { &self.id }
crates/hyperswitch_domain_models/src/customer.rs
hyperswitch_domain_models
function_signature
22
rust
null
null
null
null
get_id
null
null
null
null
null
null
null
pub async fn get_theme_using_theme_id( state: SessionState, theme_id: String, ) -> UserResponse<theme_api::GetThemeResponse> { let theme = state .store .find_theme_by_theme_id(theme_id.clone()) .await .to_not_found_response(UserErrors::ThemeNotFound)?; let file = theme_utils::retrieve_file_from_theme_bucket( &state, &theme_utils::get_theme_file_key(&theme_id), ) .await?; let parsed_data = file .to_bytes() .parse_struct("ThemeData") .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::Json(theme_api::GetThemeResponse { email_config: theme.email_config(), theme_id: theme.theme_id, theme_name: theme.theme_name, entity_type: theme.entity_type, tenant_id: theme.tenant_id, org_id: theme.org_id, merchant_id: theme.merchant_id, profile_id: theme.profile_id, theme_data: parsed_data, })) }
crates/router/src/core/user/theme.rs
router
function_signature
225
rust
null
null
null
null
get_theme_using_theme_id
null
null
null
null
null
null
null
pub struct PaymentsErrorResponse { pub rc: String, pub message: String, }
crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
hyperswitch_connectors
struct_definition
18
rust
PaymentsErrorResponse
null
null
null
null
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.CustomerResponse { "type": "object", "required": [ "customer_id", "created_at" ], "properties": { "customer_id": { "type": "string", "description": "The identifier for the customer object", "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", "maxLength": 64, "minLength": 1 }, "name": { "type": "string", "description": "The customer's name", "example": "Jon Test", "nullable": true, "maxLength": 255 }, "email": { "type": "string", "description": "The customer's email address", "example": "JonTest@test.com", "nullable": true, "maxLength": 255 }, "phone": { "type": "string", "description": "The customer's phone number", "example": "9123456789", "nullable": true, "maxLength": 255 }, "phone_country_code": { "type": "string", "description": "The country code for the customer phone number", "example": "+65", "nullable": true, "maxLength": 255 }, "description": { "type": "string", "description": "An arbitrary string that you can attach to a customer object.", "example": "First Customer", "nullable": true, "maxLength": 255 }, "address": { "allOf": [ { "$ref": "#/components/schemas/AddressDetails" } ], "nullable": true }, "created_at": { "type": "string", "format": "date-time", "description": "A timestamp (ISO 8601 code) that determines when the customer was created", "example": "2023-01-18T11:04:09.922Z" }, "metadata": { "type": "object", "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500\ncharacters long. Metadata is useful for storing additional, structured information on an\nobject.", "nullable": true }, "default_payment_method_id": { "type": "string", "description": "The identifier for the default payment method.", "example": "pm_djh2837dwduh890123", "nullable": true, "maxLength": 64 }, "tax_registration_id": { "type": "string", "description": "The customer's tax registration number.", "example": "123456789", "nullable": true, "maxLength": 255 } } }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
683
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "CustomerResponse" ]
null
null
null
null
pub trait ConnectorCommon { fn id(&self) -> &'static str; fn get_auth_header( &self, _auth_type: &auth_types::ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { Ok(Vec::new()) } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str; fn build_error_response( &self, res: auth_types::Response, ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { Ok(auth_types::ErrorResponse { status_code: res.status_code, code: crate::consts::NO_ERROR_CODE.to_string(), message: crate::consts::NO_ERROR_MESSAGE.to_string(), reason: None, }) } }
crates/pm_auth/src/types/api.rs
pm_auth
trait_definition
197
rust
null
null
ConnectorCommon
null
null
null
null
null
null
null
null
null
pub async fn refunds_metadata_update() {}
crates/openapi/src/routes/refunds.rs
openapi
function_signature
8
rust
null
null
null
null
refunds_metadata_update
null
null
null
null
null
null
null
impl TransactionType { fn get_from_capture_method_and_amount_string( capture_method: CaptureMethod, amount: &str, ) -> Self { let amount_value = amount.parse::<f64>(); if capture_method == CaptureMethod::Manual || amount_value == Ok(0.0) { Self::Auth } else { Self::Sale } } }
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
hyperswitch_connectors
impl_block
83
rust
null
TransactionType
null
impl TransactionType
null
null
null
null
null
null
null
null
impl ConnectorValidation for Boku {}
crates/hyperswitch_connectors/src/connectors/boku.rs
hyperswitch_connectors
impl_block
7
rust
null
Boku
ConnectorValidation for
impl ConnectorValidation for for Boku
null
null
null
null
null
null
null
null
pub struct CoingateSyncResponse { status: CoingatePaymentStatus, id: i64, }
crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs
hyperswitch_connectors
struct_definition
25
rust
CoingateSyncResponse
null
null
null
null
null
null
null
null
null
null
null
pub async fn configure_dynamic_routing_volume_split( state: SessionState, merchant_context: domain::MerchantContext, profile_id: common_utils::id_type::ProfileId, routing_info: routing::RoutingVolumeSplit, ) -> RouterResponse<routing::RoutingVolumeSplit> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add( 1, router_env::metric_attributes!(("profile_id", profile_id.clone())), ); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); utils::when( routing_info.split > crate::consts::DYNAMIC_ROUTING_MAX_VOLUME, || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Dynamic routing volume split should be less than 100".to_string(), }) }, )?; let business_profile: domain::Profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), Some(&profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile .dynamic_routing_algorithm .clone() .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize dynamic routing algorithm ref from business profile", )? .unwrap_or_default(); dynamic_routing_algo_ref.update_volume_split(Some(routing_info.split)); helpers::update_business_profile_active_dynamic_algorithm_ref( db, &((&state).into()), merchant_context.get_merchant_key_store(), business_profile.clone(), dynamic_routing_algo_ref.clone(), ) .await?; Ok(service_api::ApplicationResponse::Json(routing_info)) }
crates/router/src/core/routing.rs
router
function_signature
429
rust
null
null
null
null
configure_dynamic_routing_volume_split
null
null
null
null
null
null
null
impl api::Refund for Powertranz {}
crates/hyperswitch_connectors/src/connectors/powertranz.rs
hyperswitch_connectors
impl_block
10
rust
null
Powertranz
api::Refund for
impl api::Refund for for Powertranz
null
null
null
null
null
null
null
null
impl api::PaymentToken for Airwallex {}
crates/hyperswitch_connectors/src/connectors/airwallex.rs
hyperswitch_connectors
impl_block
10
rust
null
Airwallex
api::PaymentToken for
impl api::PaymentToken for for Airwallex
null
null
null
null
null
null
null
null
pub struct LineItemData { #[serde(skip_serializing_if = "Option::is_none")] pub item_sequence_number: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub item_description: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub product_code: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub quantity: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub unit_of_measure: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub tax_amount: Option<MinorUnit>, #[serde(skip_serializing_if = "Option::is_none")] pub line_item_total: Option<MinorUnit>, #[serde(skip_serializing_if = "Option::is_none")] pub line_item_total_with_tax: Option<MinorUnit>, #[serde(skip_serializing_if = "Option::is_none")] pub item_discount_amount: Option<MinorUnit>, #[serde(skip_serializing_if = "Option::is_none")] pub commodity_code: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub unit_cost: Option<MinorUnit>, }
crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
hyperswitch_connectors
struct_definition
265
rust
LineItemData
null
null
null
null
null
null
null
null
null
null
null
impl PaymentMethodsStorageInterface for MockDb {}
crates/payment_methods/src/state.rs
payment_methods
impl_block
9
rust
null
MockDb
PaymentMethodsStorageInterface for
impl PaymentMethodsStorageInterface for for MockDb
null
null
null
null
null
null
null
null
pub struct ZenRefundRequest { amount: String, transaction_id: String, currency: enums::Currency, merchant_transaction_id: String, }
crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
hyperswitch_connectors
struct_definition
33
rust
ZenRefundRequest
null
null
null
null
null
null
null
null
null
null
null