repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/blocklist_fingerprint.rs | crates/router/src/types/storage/blocklist_fingerprint.rs | pub use diesel_models::blocklist_fingerprint::{BlocklistFingerprint, BlocklistFingerprintNew};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/blocklist.rs | crates/router/src/types/storage/blocklist.rs | pub use diesel_models::blocklist::{Blocklist, BlocklistNew};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/payment_attempt.rs | crates/router/src/types/storage/payment_attempt.rs | use common_utils::types::MinorUnit;
use diesel_models::{capture::CaptureNew, enums};
use error_stack::ResultExt;
pub use hyperswitch_domain_models::payments::payment_attempt::{
PaymentAttempt, PaymentAttemptUpdate,
};
use crate::{
core::errors, errors::RouterResult, types::transformers::ForeignFrom, utils::OptionExt,
};
pub trait PaymentAttemptExt {
fn make_new_capture(
&self,
capture_amount: MinorUnit,
capture_status: enums::CaptureStatus,
) -> RouterResult<CaptureNew>;
fn get_next_capture_id(&self) -> String;
fn get_total_amount(&self) -> MinorUnit;
fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails>;
}
impl PaymentAttemptExt for PaymentAttempt {
#[cfg(feature = "v2")]
fn make_new_capture(
&self,
capture_amount: MinorUnit,
capture_status: enums::CaptureStatus,
) -> RouterResult<CaptureNew> {
todo!()
}
#[cfg(feature = "v1")]
fn make_new_capture(
&self,
capture_amount: MinorUnit,
capture_status: enums::CaptureStatus,
) -> RouterResult<CaptureNew> {
let capture_sequence = self.multiple_capture_count.unwrap_or_default() + 1;
let now = common_utils::date_time::now();
Ok(CaptureNew {
payment_id: self.payment_id.clone(),
merchant_id: self.merchant_id.clone(),
capture_id: self.get_next_capture_id(),
status: capture_status,
amount: capture_amount,
currency: self.currency,
connector: self
.connector
.clone()
.get_required_value("connector")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"connector field is required in payment_attempt to create a capture",
)?,
error_message: None,
tax_amount: None,
created_at: now,
modified_at: now,
error_code: None,
error_reason: None,
authorized_attempt_id: self.attempt_id.clone(),
capture_sequence,
connector_capture_id: None,
connector_response_reference_id: None,
processor_capture_data: None,
// Below fields are deprecated. Please add any new fields above this line.
connector_capture_data: None,
})
}
#[cfg(feature = "v1")]
fn get_next_capture_id(&self) -> String {
let next_sequence_number = self.multiple_capture_count.unwrap_or_default() + 1;
format!("{}_{}", self.attempt_id.clone(), next_sequence_number)
}
#[cfg(feature = "v2")]
fn get_next_capture_id(&self) -> String {
todo!()
}
#[cfg(feature = "v1")]
fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails> {
self.net_amount
.get_surcharge_amount()
.map(
|surcharge_amount| api_models::payments::RequestSurchargeDetails {
surcharge_amount,
tax_amount: self.net_amount.get_tax_on_surcharge(),
},
)
}
#[cfg(feature = "v2")]
fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails> {
todo!()
}
#[cfg(feature = "v1")]
fn get_total_amount(&self) -> MinorUnit {
self.net_amount.get_total_amount()
}
#[cfg(feature = "v2")]
fn get_total_amount(&self) -> MinorUnit {
todo!()
}
}
pub trait AttemptStatusExt {
fn maps_to_intent_status(self, intent_status: enums::IntentStatus) -> bool;
}
impl AttemptStatusExt for enums::AttemptStatus {
fn maps_to_intent_status(self, intent_status: enums::IntentStatus) -> bool {
enums::IntentStatus::foreign_from(self) == intent_status
}
}
#[cfg(test)]
#[cfg(all(
feature = "v1", // Ignoring tests for v2 since they aren't actively running
feature = "dummy_connector"
))]
mod tests {
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
use tokio::sync::oneshot;
use uuid::Uuid;
use crate::{
configs::settings::Settings,
db::StorageImpl,
routes, services,
types::{self, storage::enums},
};
async fn create_single_connection_test_transaction_pool() -> routes::AppState {
// Set pool size to 1 and minimum idle connection size to 0
std::env::set_var("ROUTER__MASTER_DATABASE__POOL_SIZE", "1");
std::env::set_var("ROUTER__MASTER_DATABASE__MIN_IDLE", "0");
std::env::set_var("ROUTER__REPLICA_DATABASE__POOL_SIZE", "1");
std::env::set_var("ROUTER__REPLICA_DATABASE__MIN_IDLE", "0");
let conf = Settings::new().expect("invalid settings");
let tx: oneshot::Sender<()> = oneshot::channel().0;
let api_client = Box::new(services::MockApiClient);
Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
api_client,
))
.await
}
#[tokio::test]
async fn test_payment_attempt_insert() {
let state = create_single_connection_test_transaction_pool().await;
let payment_id =
common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let current_time = common_utils::date_time::now();
let connector = types::Connector::DummyConnector1.to_string();
let merchant_id = common_utils::id_type::MerchantId::default();
let payment_attempt = PaymentAttempt {
payment_id: payment_id.clone(),
connector: Some(connector),
created_at: current_time,
modified_at: current_time,
merchant_id: merchant_id.clone(),
attempt_id: Default::default(),
status: Default::default(),
net_amount: Default::default(),
currency: Default::default(),
save_to_locker: Default::default(),
error_message: Default::default(),
offer_amount: Default::default(),
payment_method_id: Default::default(),
payment_method: Default::default(),
capture_method: Default::default(),
capture_on: Default::default(),
confirm: Default::default(),
authentication_type: Default::default(),
last_synced: Default::default(),
cancellation_reason: Default::default(),
amount_to_capture: Default::default(),
mandate_id: Default::default(),
browser_info: Default::default(),
payment_token: Default::default(),
error_code: Default::default(),
connector_metadata: Default::default(),
payment_experience: Default::default(),
payment_method_type: Default::default(),
payment_method_data: Default::default(),
business_sub_label: Default::default(),
straight_through_algorithm: Default::default(),
preprocessing_step_id: Default::default(),
mandate_details: Default::default(),
error_reason: Default::default(),
connector_response_reference_id: Default::default(),
multiple_capture_count: Default::default(),
amount_capturable: Default::default(),
updated_by: Default::default(),
authentication_data: Default::default(),
encoded_data: Default::default(),
merchant_connector_id: Default::default(),
unified_code: Default::default(),
unified_message: Default::default(),
external_three_ds_authentication_attempted: Default::default(),
authentication_connector: Default::default(),
authentication_id: Default::default(),
mandate_data: Default::default(),
payment_method_billing_address_id: Default::default(),
fingerprint_id: Default::default(),
client_source: Default::default(),
client_version: Default::default(),
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
connector_mandate_detail: Default::default(),
request_extended_authorization: Default::default(),
extended_authorization_applied: Default::default(),
extended_authorization_last_applied_at: Default::default(),
capture_before: Default::default(),
card_discovery: Default::default(),
processor_merchant_id: Default::default(),
created_by: None,
setup_future_usage_applied: Default::default(),
routing_approach: Default::default(),
connector_request_reference_id: Default::default(),
network_transaction_id: Default::default(),
network_details: Default::default(),
is_stored_credential: None,
authorized_amount: Default::default(),
tokenization: Default::default(),
charge_id: Default::default(),
charges: Default::default(),
issuer_error_code: Default::default(),
issuer_error_message: Default::default(),
debit_routing_savings: Default::default(),
is_overcapture_enabled: Default::default(),
connector_transaction_id: Default::default(),
encrypted_payment_method_data: Default::default(),
};
let store = state
.stores
.get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
let key_store = store
.get_merchant_key_store_by_merchant_id(
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.unwrap();
let response = store
.insert_payment_attempt(
payment_attempt,
enums::MerchantStorageScheme::PostgresOnly,
&key_store,
)
.await
.unwrap();
eprintln!("{response:?}");
assert_eq!(response.payment_id, payment_id.clone());
}
#[tokio::test]
/// Example of unit test
/// Kind of test: state-based testing
async fn test_find_payment_attempt() {
let state = create_single_connection_test_transaction_pool().await;
let current_time = common_utils::date_time::now();
let payment_id =
common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let attempt_id = Uuid::new_v4().to_string();
let merchant_id = common_utils::id_type::MerchantId::new_from_unix_timestamp();
let connector = types::Connector::DummyConnector1.to_string();
let payment_attempt = PaymentAttempt {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
connector: Some(connector),
created_at: current_time,
modified_at: current_time,
attempt_id: attempt_id.clone(),
status: Default::default(),
net_amount: Default::default(),
currency: Default::default(),
save_to_locker: Default::default(),
error_message: Default::default(),
offer_amount: Default::default(),
payment_method_id: Default::default(),
payment_method: Default::default(),
capture_method: Default::default(),
capture_on: Default::default(),
confirm: Default::default(),
authentication_type: Default::default(),
last_synced: Default::default(),
cancellation_reason: Default::default(),
amount_to_capture: Default::default(),
mandate_id: Default::default(),
browser_info: Default::default(),
payment_token: Default::default(),
error_code: Default::default(),
connector_metadata: Default::default(),
payment_experience: Default::default(),
payment_method_type: Default::default(),
payment_method_data: Default::default(),
business_sub_label: Default::default(),
straight_through_algorithm: Default::default(),
preprocessing_step_id: Default::default(),
mandate_details: Default::default(),
error_reason: Default::default(),
connector_response_reference_id: Default::default(),
multiple_capture_count: Default::default(),
amount_capturable: Default::default(),
updated_by: Default::default(),
authentication_data: Default::default(),
encoded_data: Default::default(),
merchant_connector_id: Default::default(),
unified_code: Default::default(),
unified_message: Default::default(),
external_three_ds_authentication_attempted: Default::default(),
authentication_connector: Default::default(),
authentication_id: Default::default(),
mandate_data: Default::default(),
payment_method_billing_address_id: Default::default(),
fingerprint_id: Default::default(),
client_source: Default::default(),
client_version: Default::default(),
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
connector_mandate_detail: Default::default(),
request_extended_authorization: Default::default(),
extended_authorization_applied: Default::default(),
extended_authorization_last_applied_at: Default::default(),
capture_before: Default::default(),
card_discovery: Default::default(),
processor_merchant_id: Default::default(),
created_by: None,
setup_future_usage_applied: Default::default(),
routing_approach: Default::default(),
connector_request_reference_id: Default::default(),
network_transaction_id: Default::default(),
network_details: Default::default(),
is_stored_credential: Default::default(),
authorized_amount: Default::default(),
tokenization: Default::default(),
charge_id: Default::default(),
charges: Default::default(),
issuer_error_code: Default::default(),
issuer_error_message: Default::default(),
debit_routing_savings: Default::default(),
is_overcapture_enabled: Default::default(),
connector_transaction_id: Default::default(),
encrypted_payment_method_data: Default::default(),
};
let store = state
.stores
.get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
let key_store = store
.get_merchant_key_store_by_merchant_id(
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.unwrap();
store
.insert_payment_attempt(
payment_attempt,
enums::MerchantStorageScheme::PostgresOnly,
&key_store,
)
.await
.unwrap();
let response = store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_id,
&merchant_id,
&attempt_id,
enums::MerchantStorageScheme::PostgresOnly,
&key_store,
)
.await
.unwrap();
eprintln!("{response:?}");
assert_eq!(response.payment_id, payment_id);
}
#[tokio::test]
/// Example of unit test
/// Kind of test: state-based testing
async fn test_payment_attempt_mandate_field() {
let state = create_single_connection_test_transaction_pool().await;
let uuid = Uuid::new_v4().to_string();
let merchant_id =
common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant1"))
.unwrap();
let payment_id =
common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let current_time = common_utils::date_time::now();
let connector = types::Connector::DummyConnector1.to_string();
let payment_attempt = PaymentAttempt {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
connector: Some(connector),
created_at: current_time,
modified_at: current_time,
mandate_id: Some("man_121212".to_string()),
attempt_id: uuid.clone(),
status: Default::default(),
net_amount: Default::default(),
currency: Default::default(),
save_to_locker: Default::default(),
error_message: Default::default(),
offer_amount: Default::default(),
payment_method_id: Default::default(),
payment_method: Default::default(),
capture_method: Default::default(),
capture_on: Default::default(),
confirm: Default::default(),
authentication_type: Default::default(),
last_synced: Default::default(),
cancellation_reason: Default::default(),
amount_to_capture: Default::default(),
browser_info: Default::default(),
payment_token: Default::default(),
error_code: Default::default(),
connector_metadata: Default::default(),
payment_experience: Default::default(),
payment_method_type: Default::default(),
payment_method_data: Default::default(),
business_sub_label: Default::default(),
straight_through_algorithm: Default::default(),
preprocessing_step_id: Default::default(),
mandate_details: Default::default(),
error_reason: Default::default(),
connector_response_reference_id: Default::default(),
multiple_capture_count: Default::default(),
amount_capturable: Default::default(),
updated_by: Default::default(),
authentication_data: Default::default(),
encoded_data: Default::default(),
merchant_connector_id: Default::default(),
unified_code: Default::default(),
unified_message: Default::default(),
external_three_ds_authentication_attempted: Default::default(),
authentication_connector: Default::default(),
authentication_id: Default::default(),
mandate_data: Default::default(),
payment_method_billing_address_id: Default::default(),
fingerprint_id: Default::default(),
client_source: Default::default(),
client_version: Default::default(),
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
connector_mandate_detail: Default::default(),
request_extended_authorization: Default::default(),
extended_authorization_applied: Default::default(),
extended_authorization_last_applied_at: Default::default(),
capture_before: Default::default(),
card_discovery: Default::default(),
processor_merchant_id: Default::default(),
created_by: None,
setup_future_usage_applied: Default::default(),
routing_approach: Default::default(),
connector_request_reference_id: Default::default(),
network_transaction_id: Default::default(),
network_details: Default::default(),
is_stored_credential: Default::default(),
authorized_amount: Default::default(),
tokenization: Default::default(),
charge_id: Default::default(),
charges: Default::default(),
issuer_error_code: Default::default(),
issuer_error_message: Default::default(),
debit_routing_savings: Default::default(),
is_overcapture_enabled: Default::default(),
connector_transaction_id: Default::default(),
encrypted_payment_method_data: Default::default(),
};
let store = state
.stores
.get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
let key_store = store
.get_merchant_key_store_by_merchant_id(
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.unwrap();
store
.insert_payment_attempt(
payment_attempt,
enums::MerchantStorageScheme::PostgresOnly,
&key_store,
)
.await
.unwrap();
let response = store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_id,
&merchant_id,
&uuid,
enums::MerchantStorageScheme::PostgresOnly,
&key_store,
)
.await
.unwrap();
// checking it after fetch
assert_eq!(response.mandate_id, Some("man_121212".to_string()));
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/fraud_check.rs | crates/router/src/types/storage/fraud_check.rs | pub use diesel_models::fraud_check::{
FraudCheck, FraudCheckNew, FraudCheckUpdate, FraudCheckUpdateInternal,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/callback_mapper.rs | crates/router/src/types/storage/callback_mapper.rs | pub use diesel_models::callback_mapper::CallbackMapper;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/dynamic_routing_stats.rs | crates/router/src/types/storage/dynamic_routing_stats.rs | pub use diesel_models::dynamic_routing_stats::{
DynamicRoutingStats, DynamicRoutingStatsNew, DynamicRoutingStatsUpdate,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/address.rs | crates/router/src/types/storage/address.rs | pub use diesel_models::address::{Address, AddressNew, AddressUpdateInternal};
pub use crate::types::domain::AddressUpdate;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/customers.rs | crates/router/src/types/storage/customers.rs | pub use diesel_models::customers::{Customer, CustomerNew, CustomerUpdateInternal};
#[cfg(feature = "v2")]
pub use crate::types::domain::CustomerGeneralUpdate;
pub use crate::types::domain::CustomerUpdate;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/user_authentication_method.rs | crates/router/src/types/storage/user_authentication_method.rs | pub use diesel_models::user_authentication_method::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/capture.rs | crates/router/src/types/storage/capture.rs | pub use diesel_models::capture::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/revenue_recovery.rs | crates/router/src/types/storage/revenue_recovery.rs | use std::{collections::HashMap, fmt::Debug};
use common_enums::enums::{self, CardNetwork};
use common_utils::{date_time, ext_traits::ValueExt, id_type};
use error_stack::ResultExt;
use external_services::grpc_client::{self as external_grpc_client, GrpcHeaders};
use hyperswitch_domain_models::{
business_profile, merchant_account, merchant_connector_account, merchant_key_store,
payment_method_data::{Card, PaymentMethodData},
payments::{payment_attempt::PaymentAttempt, PaymentIntent, PaymentStatusData},
};
use masking::PeekInterface;
use router_env::logger;
use serde::{Deserialize, Serialize};
use crate::{db::StorageInterface, routes::SessionState, types, workflows::revenue_recovery};
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct RevenueRecoveryWorkflowTrackingData {
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
pub global_payment_id: id_type::GlobalPaymentId,
pub payment_attempt_id: id_type::GlobalAttemptId,
pub billing_mca_id: id_type::MerchantConnectorAccountId,
pub revenue_recovery_retry: enums::RevenueRecoveryAlgorithmType,
pub invoice_scheduled_time: Option<time::PrimitiveDateTime>,
}
#[derive(Debug, Clone)]
pub struct RevenueRecoveryPaymentData {
pub merchant_account: merchant_account::MerchantAccount,
pub profile: business_profile::Profile,
pub key_store: merchant_key_store::MerchantKeyStore,
pub billing_mca: merchant_connector_account::MerchantConnectorAccount,
pub retry_algorithm: enums::RevenueRecoveryAlgorithmType,
pub psync_data: Option<PaymentStatusData<types::api::PSync>>,
}
impl RevenueRecoveryPaymentData {
pub async fn get_schedule_time_based_on_retry_type(
&self,
state: &SessionState,
merchant_id: &id_type::MerchantId,
retry_count: i32,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
is_hard_decline: bool,
) -> Option<time::PrimitiveDateTime> {
if is_hard_decline {
logger::info!("Hard Decline encountered");
return None;
}
match self.retry_algorithm {
enums::RevenueRecoveryAlgorithmType::Monitoring => {
logger::error!("Monitoring type found for Revenue Recovery retry payment");
None
}
enums::RevenueRecoveryAlgorithmType::Cascading => {
logger::info!("Cascading type found for Revenue Recovery retry payment");
revenue_recovery::get_schedule_time_to_retry_mit_payments(
state.store.as_ref(),
merchant_id,
retry_count,
)
.await
}
enums::RevenueRecoveryAlgorithmType::Smart => None,
}
}
}
#[derive(Debug, serde::Deserialize, Clone, Default)]
pub struct RevenueRecoverySettings {
pub monitoring_threshold_in_seconds: i64,
pub retry_algorithm_type: enums::RevenueRecoveryAlgorithmType,
pub recovery_timestamp: RecoveryTimestamp,
pub card_config: RetryLimitsConfig,
pub redis_ttl_in_seconds: i64,
}
#[derive(Debug, serde::Deserialize, Clone)]
pub struct RecoveryTimestamp {
pub initial_timestamp_in_seconds: i64,
pub job_schedule_buffer_time_in_seconds: i64,
pub reopen_workflow_buffer_time_in_seconds: i64,
pub max_random_schedule_delay_in_seconds: i64,
pub redis_ttl_buffer_in_seconds: i64,
pub unretried_invoice_schedule_time_offset_seconds: i64,
}
impl Default for RecoveryTimestamp {
fn default() -> Self {
Self {
initial_timestamp_in_seconds: 1,
job_schedule_buffer_time_in_seconds: 15,
reopen_workflow_buffer_time_in_seconds: 60,
max_random_schedule_delay_in_seconds: 300,
redis_ttl_buffer_in_seconds: 300,
unretried_invoice_schedule_time_offset_seconds: 300,
}
}
}
#[derive(Debug, serde::Deserialize, Clone, Default)]
pub struct RetryLimitsConfig(pub HashMap<CardNetwork, NetworkRetryConfig>);
#[derive(Debug, serde::Deserialize, Clone, Default)]
pub struct NetworkRetryConfig {
pub max_retries_per_day: i32,
pub max_retry_count_for_thirty_day: i32,
}
impl RetryLimitsConfig {
pub fn get_network_config(&self, network: Option<CardNetwork>) -> &NetworkRetryConfig {
// Hardcoded fallback default config
static DEFAULT_CONFIG: NetworkRetryConfig = NetworkRetryConfig {
max_retries_per_day: 20,
max_retry_count_for_thirty_day: 20,
};
if let Some(net) = network {
self.0.get(&net).unwrap_or(&DEFAULT_CONFIG)
} else {
self.0.get(&CardNetwork::Visa).unwrap_or(&DEFAULT_CONFIG)
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/payment_link.rs | crates/router/src/types/storage/payment_link.rs | use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};
pub use diesel_models::{
payment_link::{PaymentLink, PaymentLinkNew},
schema::payment_link::dsl,
};
use error_stack::ResultExt;
use crate::{
connection::PgPooledConn,
core::errors::{self, CustomResult},
logger,
};
#[async_trait::async_trait]
pub trait PaymentLinkDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
}
#[async_trait::async_trait]
impl PaymentLinkDbExt for PaymentLink {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::created_at.desc())
.into_boxed();
if let Some(created_time) = payment_link_list_constraints.created {
filter = filter.filter(dsl::created_at.eq(created_time));
}
if let Some(created_time_lt) = payment_link_list_constraints.created_lt {
filter = filter.filter(dsl::created_at.lt(created_time_lt));
}
if let Some(created_time_gt) = payment_link_list_constraints.created_gt {
filter = filter.filter(dsl::created_at.gt(created_time_gt));
}
if let Some(created_time_lte) = payment_link_list_constraints.created_lte {
filter = filter.filter(dsl::created_at.le(created_time_lte));
}
if let Some(created_time_gte) = payment_link_list_constraints.created_gte {
filter = filter.filter(dsl::created_at.ge(created_time_gte));
}
if let Some(limit) = payment_link_list_constraints.limit {
filter = filter.limit(limit);
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
.get_results_async(conn)
.await
// The query built here returns an empty Vec when no records are found, and if any error does occur,
// it would be an internal database error, due to which we are raising a DatabaseError::Unknown error
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering payment link by specified constraints")
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/dispute.rs | crates/router/src/types/storage/dispute.rs | use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::errors::CustomResult;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl};
pub use diesel_models::dispute::{Dispute, DisputeNew, DisputeUpdate};
use diesel_models::{errors, query::generics::db_metrics, schema::dispute::dsl};
use error_stack::ResultExt;
use hyperswitch_domain_models::disputes;
use crate::{connection::PgPooledConn, logger};
#[async_trait::async_trait]
pub trait DisputeDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
async fn get_dispute_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::DatabaseError>;
}
#[async_trait::async_trait]
impl DisputeDbExt for Dispute {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::modified_at.desc())
.into_boxed();
let mut search_by_payment_or_dispute_id = false;
if let (Some(payment_id), Some(dispute_id)) = (
&dispute_list_constraints.payment_id,
&dispute_list_constraints.dispute_id,
) {
search_by_payment_or_dispute_id = true;
filter = filter.filter(
dsl::payment_id
.eq(payment_id.to_owned())
.or(dsl::dispute_id.eq(dispute_id.to_owned())),
);
};
if !search_by_payment_or_dispute_id {
if let Some(payment_id) = &dispute_list_constraints.payment_id {
filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
};
}
if !search_by_payment_or_dispute_id {
if let Some(dispute_id) = &dispute_list_constraints.dispute_id {
filter = filter.filter(dsl::dispute_id.eq(dispute_id.clone()));
};
}
if let Some(time_range) = dispute_list_constraints.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
if let Some(end_time) = time_range.end_time {
filter = filter.filter(dsl::created_at.le(end_time));
}
}
if let Some(profile_id) = &dispute_list_constraints.profile_id {
filter = filter.filter(dsl::profile_id.eq_any(profile_id.clone()));
}
if let Some(connector_list) = &dispute_list_constraints.connector {
filter = filter.filter(dsl::connector.eq_any(connector_list.clone()));
}
if let Some(reason) = &dispute_list_constraints.reason {
filter = filter.filter(dsl::connector_reason.eq(reason.clone()));
}
if let Some(dispute_stage) = &dispute_list_constraints.dispute_stage {
filter = filter.filter(dsl::dispute_stage.eq_any(dispute_stage.clone()));
}
if let Some(dispute_status) = &dispute_list_constraints.dispute_status {
filter = filter.filter(dsl::dispute_status.eq_any(dispute_status.clone()));
}
if let Some(currency_list) = &dispute_list_constraints.currency {
filter = filter.filter(dsl::dispute_currency.eq_any(currency_list.clone()));
}
if let Some(merchant_connector_id) = &dispute_list_constraints.merchant_connector_id {
filter = filter.filter(dsl::merchant_connector_id.eq(merchant_connector_id.clone()))
}
if let Some(limit) = dispute_list_constraints.limit {
filter = filter.limit(limit.into());
}
if let Some(offset) = dispute_list_constraints.offset {
filter = filter.offset(offset.into());
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_results_async(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
}
async fn get_dispute_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::DatabaseError> {
let mut query = <Self as HasTable>::table()
.group_by(dsl::dispute_status)
.select((dsl::dispute_status, diesel::dsl::count_star()))
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
if let Some(profile_id) = profile_id_list {
query = query.filter(dsl::profile_id.eq_any(profile_id));
}
query = query.filter(dsl::created_at.ge(time_range.start_time));
query = match time_range.end_time {
Some(ending_at) => query.filter(dsl::created_at.le(ending_at)),
None => query,
};
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
query.get_results_async::<(common_enums::DisputeStatus, i64)>(conn),
db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/ephemeral_key.rs | crates/router/src/types/storage/ephemeral_key.rs | #[cfg(feature = "v2")]
pub use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew};
pub use diesel_models::ephemeral_key::{EphemeralKey, EphemeralKeyNew};
#[cfg(feature = "v2")]
use crate::db::errors;
#[cfg(feature = "v2")]
use crate::types::transformers::ForeignTryFrom;
#[cfg(feature = "v2")]
impl ForeignTryFrom<ClientSecretType> for api_models::ephemeral_key::ClientSecretResponse {
type Error = errors::ApiErrorResponse;
fn foreign_try_from(from: ClientSecretType) -> Result<Self, errors::ApiErrorResponse> {
match from.resource_id {
common_utils::types::authentication::ResourceId::Payment(global_payment_id) => {
Err(errors::ApiErrorResponse::InternalServerError)
}
common_utils::types::authentication::ResourceId::PaymentMethodSession(
global_payment_id,
) => Err(errors::ApiErrorResponse::InternalServerError),
common_utils::types::authentication::ResourceId::Customer(global_customer_id) => {
Ok(Self {
resource_id: api_models::ephemeral_key::ResourceId::Customer(
global_customer_id.clone(),
),
created_at: from.created_at,
expires: from.expires,
secret: from.secret,
id: from.id,
})
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/payout_attempt.rs | crates/router/src/types/storage/payout_attempt.rs | pub use diesel_models::payout_attempt::{
PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/cards_info.rs | crates/router/src/types/storage/cards_info.rs | pub use diesel_models::cards_info::{CardInfo, UpdateCardInfo};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/merchant_account.rs | crates/router/src/types/storage/merchant_account.rs | pub use diesel_models::merchant_account::{
MerchantAccount, MerchantAccountNew, MerchantAccountUpdateInternal,
};
pub use crate::types::domain::MerchantAccountUpdate;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/enums.rs | crates/router/src/types/storage/enums.rs | pub use diesel_models::enums::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/generic_link.rs | crates/router/src/types/storage/generic_link.rs | pub use diesel_models::generic_link::{
GenericLink, GenericLinkData, GenericLinkNew, GenericLinkState, GenericLinkUpdateInternal,
PaymentMethodCollectLink, PayoutLink, PayoutLinkUpdate,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/user_role.rs | crates/router/src/types/storage/user_role.rs | pub use diesel_models::user_role::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/file.rs | crates/router/src/types/storage/file.rs | pub use diesel_models::file::{
FileMetadata, FileMetadataNew, FileMetadataUpdate, FileMetadataUpdateInternal,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/merchant_connector_account.rs | crates/router/src/types/storage/merchant_connector_account.rs | pub use diesel_models::merchant_connector_account::{
MerchantConnectorAccount, MerchantConnectorAccountNew, MerchantConnectorAccountUpdateInternal,
};
pub use crate::types::domain::MerchantConnectorAccountUpdate;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/blocklist_lookup.rs | crates/router/src/types/storage/blocklist_lookup.rs | pub use diesel_models::blocklist_lookup::{BlocklistLookup, BlocklistLookupNew};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/payment_method.rs | crates/router/src/types/storage/payment_method.rs | use api_models::payment_methods;
use diesel_models::enums;
pub use diesel_models::payment_method::{
PaymentMethod, PaymentMethodNew, PaymentMethodUpdate, PaymentMethodUpdateInternal,
TokenizeCoreWorkflow,
};
use crate::types::{api, domain};
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PaymentTokenKind {
Temporary,
Permanent,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CardTokenData {
pub payment_method_id: Option<String>,
pub locker_id: Option<String>,
pub token: String,
pub network_token_locker_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BankDebitTokenData {
pub payment_method_id: String,
pub locker_id: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CardTokenData {
pub payment_method_id: common_utils::id_type::GlobalPaymentMethodId,
pub locker_id: Option<String>,
pub token: String,
}
#[derive(Debug, Clone, serde::Serialize, Default, serde::Deserialize)]
pub struct PaymentMethodDataWithId {
pub payment_method: Option<enums::PaymentMethod>,
pub payment_method_data: Option<domain::PaymentMethodData>,
pub payment_method_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericTokenData {
pub token: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct WalletTokenData {
pub payment_method_id: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[cfg(feature = "v1")]
pub enum PaymentTokenData {
// The variants 'Temporary' and 'Permanent' are added for backwards compatibility
// with any tokenized data present in Redis at the time of deployment of this change
Temporary(GenericTokenData),
TemporaryGeneric(GenericTokenData),
Permanent(CardTokenData),
PermanentCard(CardTokenData),
AuthBankDebit(payment_methods::BankAccountTokenData),
WalletToken(WalletTokenData),
BankDebit(BankDebitTokenData),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[cfg(feature = "v2")]
pub enum PaymentTokenData {
TemporaryGeneric(GenericTokenData),
PermanentCard(CardTokenData),
AuthBankDebit(payment_methods::BankAccountTokenData),
}
impl PaymentTokenData {
#[cfg(feature = "v1")]
pub fn permanent_card(
payment_method_id: Option<String>,
locker_id: Option<String>,
token: String,
network_token_locker_id: Option<String>,
) -> Self {
Self::PermanentCard(CardTokenData {
payment_method_id,
locker_id,
token,
network_token_locker_id,
})
}
#[cfg(feature = "v2")]
pub fn permanent_card(
payment_method_id: common_utils::id_type::GlobalPaymentMethodId,
locker_id: Option<String>,
token: String,
) -> Self {
Self::PermanentCard(CardTokenData {
payment_method_id,
locker_id,
token,
})
}
pub fn temporary_generic(token: String) -> Self {
Self::TemporaryGeneric(GenericTokenData { token })
}
#[cfg(feature = "v1")]
pub fn wallet_token(payment_method_id: String) -> Self {
Self::WalletToken(WalletTokenData { payment_method_id })
}
#[cfg(feature = "v1")]
pub fn is_permanent_card(&self) -> bool {
matches!(self, Self::PermanentCard(_) | Self::Permanent(_))
}
#[cfg(feature = "v2")]
pub fn is_permanent_card(&self) -> bool {
matches!(self, Self::PermanentCard(_))
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentMethodListContext {
pub card_details: Option<api::CardDetailFromLocker>,
pub hyperswitch_token_data: Option<PaymentTokenData>,
#[cfg(feature = "payouts")]
pub bank_transfer_details: Option<api::BankPayout>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum PaymentMethodListContext {
Card {
card_details: api::CardDetailFromLocker,
// TODO: Why can't these fields be mandatory?
token_data: Option<PaymentTokenData>,
},
Bank {
token_data: Option<PaymentTokenData>,
},
#[cfg(feature = "payouts")]
BankTransfer {
bank_transfer_details: api::BankPayout,
token_data: Option<PaymentTokenData>,
},
TemporaryToken {
token_data: Option<PaymentTokenData>,
},
}
#[cfg(feature = "v2")]
impl PaymentMethodListContext {
pub(crate) fn get_token_data(&self) -> Option<PaymentTokenData> {
match self {
Self::Card { token_data, .. }
| Self::Bank { token_data }
| Self::BankTransfer { token_data, .. }
| Self::TemporaryToken { token_data } => token_data.clone(),
}
}
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct PaymentMethodStatusTrackingData {
pub payment_method_id: String,
pub prev_status: enums::PaymentMethodStatus,
pub curr_status: enums::PaymentMethodStatus,
pub merchant_id: common_utils::id_type::MerchantId,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/payouts.rs | crates/router/src/types/storage/payouts.rs | pub use diesel_models::payouts::{Payouts, PayoutsNew, PayoutsUpdate, PayoutsUpdateInternal};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/unified_translations.rs | crates/router/src/types/storage/unified_translations.rs | pub use diesel_models::unified_translations::{
UnifiedTranslations, UnifiedTranslationsNew, UnifiedTranslationsUpdate,
UnifiedTranslationsUpdateInternal,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/gsm.rs | crates/router/src/types/storage/gsm.rs | pub use diesel_models::gsm::{
GatewayStatusMap, GatewayStatusMapperUpdateInternal, GatewayStatusMappingNew,
GatewayStatusMappingUpdate,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/revenue_recovery_redis_operation.rs | crates/router/src/types/storage/revenue_recovery_redis_operation.rs | use std::collections::HashMap;
use api_models::revenue_recovery_data_backfill::{self, AccountUpdateHistoryRecord, RedisKeyType};
use common_enums::enums::CardNetwork;
use common_utils::{date_time, errors::CustomResult, id_type};
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret};
use redis_interface::{DelReply, SetnxReply};
use router_env::{instrument, logger, tracing};
use serde::{Deserialize, Deserializer, Serialize};
use time::{Date, Duration, OffsetDateTime, PrimitiveDateTime, Time};
use crate::{db::errors, types::storage::enums::RevenueRecoveryAlgorithmType, SessionState};
// Constants for retry window management
const INITIAL_RETRY_COUNT: i32 = 0;
const RETRY_WINDOW_IN_HOUR: i32 = 720;
/// Payment processor token details including card information
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub struct PaymentProcessorTokenDetails {
pub payment_processor_token: String,
pub expiry_month: Option<Secret<String>>,
pub expiry_year: Option<Secret<String>>,
pub card_issuer: Option<String>,
pub last_four_digits: Option<String>,
pub card_network: Option<CardNetwork>,
pub card_type: Option<String>,
pub card_isin: Option<String>,
}
/// Represents the status and retry history of a payment processor token
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentProcessorTokenStatus {
/// Payment processor token details including card information and token ID
pub payment_processor_token_details: PaymentProcessorTokenDetails,
/// Payment intent ID that originally inserted this token
pub inserted_by_attempt_id: id_type::GlobalAttemptId,
/// Error code associated with the token failure
pub error_code: Option<String>,
/// Daily retry count history for the last 30 days (date -> retry_count)
#[serde(deserialize_with = "parse_datetime_key")]
pub daily_retry_history: HashMap<PrimitiveDateTime, i32>,
/// Scheduled time for the next retry attempt
pub scheduled_at: Option<PrimitiveDateTime>,
/// Indicates if the token is a hard decline (no retries allowed)
pub is_hard_decline: Option<bool>,
/// Timestamp of the last modification to this token status
pub modified_at: Option<PrimitiveDateTime>,
/// Indicates if the token is active or not
pub is_active: Option<bool>,
/// Update history of the token
pub account_update_history: Option<Vec<AccountUpdateHistoryRecord>>,
/// Previous Decision threshold for selecting the best slot
pub decision_threshold: Option<f64>,
}
impl From<&PaymentProcessorTokenDetails> for api_models::payments::AdditionalCardInfo {
fn from(data: &PaymentProcessorTokenDetails) -> Self {
Self {
card_exp_month: data.expiry_month.clone(),
card_exp_year: data.expiry_year.clone(),
card_issuer: data.card_issuer.clone(),
card_network: data.card_network.clone(),
card_type: data.card_type.clone(),
last4: data.last_four_digits.clone(),
card_isin: data.card_isin.clone(),
card_issuing_country: None,
card_issuing_country_code: None,
bank_code: None,
card_extended_bin: None,
card_holder_name: None,
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
}
}
}
fn parse_datetime_key<'de, D>(deserializer: D) -> Result<HashMap<PrimitiveDateTime, i32>, D::Error>
where
D: serde::Deserializer<'de>,
{
let raw: HashMap<String, i32> = HashMap::deserialize(deserializer)?;
let mut parsed = HashMap::new();
// Full datetime
let full_dt_format = time::macros::format_description!(
"[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]"
);
// Date only
let date_only_format = time::macros::format_description!("[year]-[month]-[day]");
for (k, v) in raw {
let dt = PrimitiveDateTime::parse(&k, &full_dt_format)
.or_else(|_| {
Date::parse(&k, &date_only_format)
.map(|date| PrimitiveDateTime::new(date, Time::MIDNIGHT))
})
.map_err(|_| serde::de::Error::custom(format!("Invalid date key: {}", k)))?;
parsed.insert(dt, v);
}
Ok(parsed)
}
/// Token retry availability information with detailed wait times
#[derive(Debug, Clone)]
pub struct TokenRetryInfo {
pub monthly_wait_hours: i64, // Hours to wait for 30-day limit reset
pub daily_wait_hours: i64, // Hours to wait for daily limit reset
pub total_30_day_retries: i32, // Current total retry count in 30-day window
}
/// Complete token information with retry limits and wait times
#[derive(Debug, Clone)]
pub struct PaymentProcessorTokenWithRetryInfo {
/// The complete token status information
pub token_status: PaymentProcessorTokenStatus,
/// Hours to wait before next retry attempt (max of daily/monthly wait)
pub retry_wait_time_hours: i64,
/// Number of retries remaining in the 30-day rolling window
pub monthly_retry_remaining: i32,
// Current total retry count in 30-day window
pub total_30_day_retries: i32,
}
/// Redis-based token management struct
pub struct RedisTokenManager;
impl RedisTokenManager {
fn get_connector_customer_lock_key(connector_customer_id: &str) -> String {
format!("customer:{connector_customer_id}:status")
}
fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String {
format!("customer:{connector_customer_id}:tokens")
}
/// Lock connector customer
#[instrument(skip_all)]
pub async fn lock_connector_customer_status(
state: &SessionState,
connector_customer_id: &str,
payment_id: &id_type::GlobalPaymentId,
) -> CustomResult<bool, errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);
let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;
let result: bool = match redis_conn
.set_key_if_not_exists_with_expiry(
&lock_key.into(),
payment_id.get_string_repr(),
Some(*seconds),
)
.await
{
Ok(resp) => resp == SetnxReply::KeySet,
Err(error) => {
tracing::error!(operation = "lock_stream", err = ?error);
false
}
};
tracing::debug!(
connector_customer_id = connector_customer_id,
payment_id = payment_id.get_string_repr(),
lock_acquired = %result,
"Connector customer lock attempt"
);
Ok(result)
}
#[instrument(skip_all)]
pub async fn update_connector_customer_lock_ttl(
state: &SessionState,
connector_customer_id: &str,
exp_in_seconds: i64,
) -> CustomResult<(), errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);
let result: bool = redis_conn
.set_expiry(&lock_key.clone().into(), exp_in_seconds)
.await
.map_or_else(
|error| {
tracing::error!(operation = "update_lock_ttl", err = ?error);
false
},
|_| true,
);
if result {
tracing::debug!(
lock_key = %lock_key,
new_ttl_in_seconds = exp_in_seconds,
"Redis key TTL updated successfully"
);
} else {
tracing::error!(
lock_key = %lock_key,
"Failed to update TTL: key not found or error occurred"
);
}
Ok(())
}
/// Unlock connector customer status
#[instrument(skip_all)]
pub async fn unlock_connector_customer_status(
state: &SessionState,
connector_customer_id: &str,
payment_id: &id_type::GlobalPaymentId,
) -> CustomResult<bool, errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);
// Get the id used to lock that key
let stored_lock_value: String = redis_conn
.get_key(&lock_key.clone().into())
.await
.map_err(|err| {
tracing::error!(?err, "Failed to get lock key");
errors::StorageError::RedisError(errors::RedisError::RedisConnectionError.into())
})?;
Some(stored_lock_value)
.filter(|locked_value| locked_value == payment_id.get_string_repr())
.ok_or_else(|| {
tracing::warn!(
connector_customer_id = %connector_customer_id,
payment_id = %payment_id.get_string_repr(),
"Unlock attempt by non-lock owner",
);
errors::StorageError::RedisError(errors::RedisError::DeleteFailed.into())
})?;
match redis_conn.delete_key(&lock_key.into()).await {
Ok(DelReply::KeyDeleted) => {
tracing::debug!(
connector_customer_id = connector_customer_id,
"Connector customer unlocked"
);
Ok(true)
}
Ok(DelReply::KeyNotDeleted) => {
tracing::debug!("Tried to unlock a stream which is already unlocked");
Ok(false)
}
Err(err) => {
tracing::error!(?err, "Failed to delete lock key");
Ok(false)
}
}
}
/// Get all payment processor tokens for a connector customer
#[instrument(skip_all)]
pub async fn get_connector_customer_payment_processor_tokens(
state: &SessionState,
connector_customer_id: &str,
) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);
let get_hash_err =
errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());
let payment_processor_tokens: HashMap<String, String> = redis_conn
.get_hash_fields(&tokens_key.into())
.await
.change_context(get_hash_err)?;
let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> =
payment_processor_tokens
.into_iter()
.filter_map(|(token_id, token_data)| {
match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) {
Ok(token_status) => Some((token_id, token_status)),
Err(err) => {
tracing::warn!(
connector_customer_id = %connector_customer_id,
token_id = %token_id,
error = %err,
"Failed to deserialize token data, skipping",
);
None
}
}
})
.collect();
tracing::debug!(
connector_customer_id = connector_customer_id,
"Fetched payment processor tokens",
);
Ok(payment_processor_token_info_map)
}
/// Find the most recent date from retry history
pub fn find_nearest_date_from_current(
retry_history: &HashMap<PrimitiveDateTime, i32>,
) -> Option<(PrimitiveDateTime, i32)> {
let now_utc = OffsetDateTime::now_utc();
let reference_time = PrimitiveDateTime::new(
now_utc.date(),
Time::from_hms(now_utc.hour(), 0, 0).unwrap_or(Time::MIDNIGHT),
);
retry_history
.iter()
.filter(|(date, _)| **date <= reference_time) // Only past dates + today
.max_by_key(|(date, _)| *date) // Get the most recent
.map(|(date, retry_count)| (*date, *retry_count))
}
/// Update connector customer payment processor tokens or add if doesn't exist
#[instrument(skip_all)]
pub async fn update_or_add_connector_customer_payment_processor_tokens(
state: &SessionState,
connector_customer_id: &str,
payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>,
) -> CustomResult<(), errors::StorageError> {
let redis_conn =
state
.store
.get_redis_conn()
.change_context(errors::StorageError::RedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);
// allocate capacity up-front to avoid rehashing
let mut serialized_payment_processor_tokens: HashMap<String, String> =
HashMap::with_capacity(payment_processor_token_info_map.len());
// serialize all tokens, preserving explicit error handling and attachable diagnostics
for (payment_processor_token_id, payment_processor_token_status) in
payment_processor_token_info_map
{
let serialized = serde_json::to_string(&payment_processor_token_status)
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed to serialize token status")?;
serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);
}
let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;
// Update or add tokens
redis_conn
.set_hash_fields(
&tokens_key.into(),
serialized_payment_processor_tokens,
Some(*seconds),
)
.await
.change_context(errors::StorageError::RedisError(
errors::RedisError::SetHashFieldFailed.into(),
))?;
tracing::info!(
connector_customer_id = %connector_customer_id,
"Successfully updated or added customer tokens",
);
Ok(())
}
/// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).
pub fn normalize_retry_window(
payment_processor_token: &mut PaymentProcessorTokenStatus,
reference_time: PrimitiveDateTime,
) {
let mut normalized_retry_history: HashMap<PrimitiveDateTime, i32> = HashMap::new();
for hours_ago in 0..RETRY_WINDOW_IN_HOUR {
let date = reference_time - Duration::hours(hours_ago.into());
payment_processor_token
.daily_retry_history
.get(&date)
.map(|&retry_count| {
normalized_retry_history.insert(date, retry_count);
});
}
payment_processor_token.daily_retry_history = normalized_retry_history;
}
/// Get all payment processor tokens with retry information and wait times.
pub fn get_tokens_with_retry_metadata(
state: &SessionState,
payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,
) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {
let today = OffsetDateTime::now_utc().date();
let card_config = &state.conf.revenue_recovery.card_config;
let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> =
HashMap::with_capacity(payment_processor_token_info_map.len());
for (payment_processor_token_id, payment_processor_token_status) in
payment_processor_token_info_map.iter()
{
let card_network = payment_processor_token_status
.payment_processor_token_details
.card_network
.clone();
// Calculate retry information.
let retry_info = Self::payment_processor_token_retry_info(
state,
payment_processor_token_status,
card_network.clone(),
);
// Determine the wait time (max of monthly and daily wait hours).
let retry_wait_time_hours = retry_info
.monthly_wait_hours
.max(retry_info.daily_wait_hours);
// Obtain network-specific limits and compute remaining monthly retries.
let card_network_config = card_config.get_network_config(card_network);
let monthly_retry_remaining = std::cmp::max(
0,
card_network_config.max_retry_count_for_thirty_day
- retry_info.total_30_day_retries,
);
// Build the per-token result struct.
let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {
token_status: payment_processor_token_status.clone(),
retry_wait_time_hours,
monthly_retry_remaining,
total_30_day_retries: retry_info.total_30_day_retries,
};
result.insert(payment_processor_token_id.clone(), token_with_retry_info);
}
tracing::debug!("Fetched payment processor tokens with retry metadata",);
result
}
/// Sum retries over exactly the last 30 days
fn calculate_total_30_day_retries(
token: &PaymentProcessorTokenStatus,
reference_time: PrimitiveDateTime,
) -> i32 {
(0..RETRY_WINDOW_IN_HOUR)
.map(|i| {
let target_hour = reference_time - Duration::hours(i.into());
token
.daily_retry_history
.get(&target_hour)
.copied()
.unwrap_or(INITIAL_RETRY_COUNT)
})
.sum()
}
/// Calculate wait hours
fn calculate_wait_hours(target_date: PrimitiveDateTime, now: OffsetDateTime) -> i64 {
let expiry_time = target_date.assume_utc();
(expiry_time - now).whole_hours().max(0)
}
/// Calculate retry counts for exactly the last 30 days (hour-granular)
pub fn payment_processor_token_retry_info(
state: &SessionState,
token: &PaymentProcessorTokenStatus,
network_type: Option<CardNetwork>,
) -> TokenRetryInfo {
let card_config = &state.conf.revenue_recovery.card_config;
let card_network_config = card_config.get_network_config(network_type);
let now_utc = OffsetDateTime::now_utc();
let reference_time = PrimitiveDateTime::new(
now_utc.date(),
Time::from_hms(now_utc.hour(), 0, 0).unwrap_or(Time::MIDNIGHT),
);
// Total retries for last 720 hours
let total_30_day_retries = Self::calculate_total_30_day_retries(token, reference_time);
// Monthly wait-hour calculation ----
let monthly_wait_hours =
if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {
let mut accumulated_retries = 0;
(0..RETRY_WINDOW_IN_HOUR)
.map(|i| reference_time - Duration::hours(i.into()))
.find(|window_hour| {
let retries = token
.daily_retry_history
.get(window_hour)
.copied()
.unwrap_or(0);
accumulated_retries += retries;
accumulated_retries >= card_network_config.max_retry_count_for_thirty_day
})
.map(|breach_hour| {
let allowed_at = breach_hour + Duration::days(31);
Self::calculate_wait_hours(allowed_at, now_utc)
})
.unwrap_or(0)
} else {
0
};
// Today's retries (using hourly buckets) ----
let today_date = reference_time.date();
let today_retries: i32 = (0..24)
.map(|h| {
let hour_bucket = PrimitiveDateTime::new(
today_date,
Time::from_hms(h, 0, 0).unwrap_or(Time::MIDNIGHT),
);
token
.daily_retry_history
.get(&hour_bucket)
.copied()
.unwrap_or(0)
})
.sum();
let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {
let tomorrow_start =
PrimitiveDateTime::new(today_date + Duration::days(1), Time::MIDNIGHT);
Self::calculate_wait_hours(tomorrow_start, now_utc)
} else {
0
};
TokenRetryInfo {
monthly_wait_hours,
daily_wait_hours,
total_30_day_retries,
}
}
// Upsert payment processor token
#[instrument(skip_all)]
pub async fn upsert_payment_processor_token(
state: &SessionState,
connector_customer_id: &str,
token_data: PaymentProcessorTokenStatus,
) -> CustomResult<bool, errors::StorageError> {
let mut token_map =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?;
let token_id = token_data
.payment_processor_token_details
.payment_processor_token
.clone();
let was_existing = token_map.contains_key(&token_id);
let error_code = token_data.error_code.clone();
let last_external_attempt_at = token_data.modified_at;
let now_utc = OffsetDateTime::now_utc();
let reference_time = PrimitiveDateTime::new(
now_utc.date(),
Time::from_hms(now_utc.hour(), 0, 0).unwrap_or(Time::MIDNIGHT),
);
token_map
.get_mut(&token_id)
.map(|existing_token| {
Self::normalize_retry_window(existing_token, reference_time);
for (date, &value) in &token_data.daily_retry_history {
existing_token
.daily_retry_history
.entry(*date)
.and_modify(|v| *v += value)
.or_insert(value);
}
existing_token.account_update_history = token_data.account_update_history.clone();
existing_token.payment_processor_token_details =
token_data.payment_processor_token_details.clone();
existing_token
.modified_at
.zip(last_external_attempt_at)
.and_then(|(existing_token_modified_at, last_external_attempt_at)| {
(last_external_attempt_at > existing_token_modified_at)
.then_some(last_external_attempt_at)
})
.or_else(|| {
existing_token
.modified_at
.is_none()
.then_some(last_external_attempt_at)
.flatten()
})
.map(|last_external_attempt_at| {
existing_token.modified_at = Some(last_external_attempt_at);
existing_token.error_code = error_code;
existing_token.is_hard_decline = token_data.is_hard_decline;
token_data
.is_active
.map(|is_active| existing_token.is_active = Some(is_active));
});
})
.or_else(|| {
token_map.insert(token_id.clone(), token_data);
None
});
Self::update_or_add_connector_customer_payment_processor_tokens(
state,
connector_customer_id,
token_map,
)
.await?;
tracing::debug!(
connector_customer_id = connector_customer_id,
"Upsert payment processor tokens",
);
Ok(!was_existing)
}
// Update payment processor token error code with billing connector response
#[instrument(skip_all)]
pub async fn update_payment_processor_token_error_code_from_process_tracker(
state: &SessionState,
connector_customer_id: &str,
error_code: &Option<String>,
is_hard_decline: &Option<bool>,
payment_processor_token_id: Option<&str>,
) -> CustomResult<bool, errors::StorageError> {
let now_utc = OffsetDateTime::now_utc();
let reference_time = PrimitiveDateTime::new(
now_utc.date(),
Time::from_hms(now_utc.hour(), 0, 0).unwrap_or(Time::MIDNIGHT),
);
let updated_token = match payment_processor_token_id {
Some(token_id) => {
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?
.values()
.find(|status| {
status
.payment_processor_token_details
.payment_processor_token
== token_id
})
.map(|status| PaymentProcessorTokenStatus {
payment_processor_token_details: status
.payment_processor_token_details
.clone(),
inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),
error_code: error_code.clone(),
daily_retry_history: status.daily_retry_history.clone(),
scheduled_at: None,
is_hard_decline: *is_hard_decline,
modified_at: Some(PrimitiveDateTime::new(
OffsetDateTime::now_utc().date(),
OffsetDateTime::now_utc().time(),
)),
is_active: status.is_active,
account_update_history: status.account_update_history.clone(),
decision_threshold: status.decision_threshold,
})
}
None => None,
};
match updated_token {
Some(mut token) => {
Self::normalize_retry_window(&mut token, reference_time);
match token.error_code {
None => token.daily_retry_history.clear(),
Some(_) => {
let current_count = token
.daily_retry_history
.get(&reference_time)
.copied()
.unwrap_or(INITIAL_RETRY_COUNT);
token
.daily_retry_history
.insert(reference_time, current_count + 1);
}
}
let mut tokens_map = HashMap::new();
tokens_map.insert(
token
.payment_processor_token_details
.payment_processor_token
.clone(),
token.clone(),
);
Self::update_or_add_connector_customer_payment_processor_tokens(
state,
connector_customer_id,
tokens_map,
)
.await?;
tracing::debug!(
connector_customer_id = connector_customer_id,
"Updated payment processor tokens with error code",
);
Ok(true)
}
None => {
tracing::debug!(
connector_customer_id = connector_customer_id,
"No Token found with token id to update error code",
);
Ok(false)
}
}
}
// Update all payment processor token schedule time to None
#[instrument(skip_all)]
pub async fn update_payment_processor_tokens_schedule_time_to_none(
state: &SessionState,
connector_customer_id: &str,
) -> CustomResult<(), errors::StorageError> {
let tokens_map =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?;
let mut updated_tokens_map = HashMap::new();
for (token_id, status) in tokens_map {
let updated_status = PaymentProcessorTokenStatus {
payment_processor_token_details: status.payment_processor_token_details.clone(),
inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),
error_code: status.error_code.clone(),
daily_retry_history: status.daily_retry_history.clone(),
scheduled_at: None,
is_hard_decline: status.is_hard_decline,
modified_at: Some(PrimitiveDateTime::new(
OffsetDateTime::now_utc().date(),
OffsetDateTime::now_utc().time(),
)),
is_active: status.is_active,
account_update_history: status.account_update_history.clone(),
decision_threshold: status.decision_threshold,
};
updated_tokens_map.insert(token_id, updated_status);
}
Self::update_or_add_connector_customer_payment_processor_tokens(
state,
connector_customer_id,
updated_tokens_map,
)
.await?;
tracing::debug!(
connector_customer_id = connector_customer_id,
"Updated all payment processor tokens schedule time to None",
);
Ok(())
}
// Update payment processor token schedule time
#[instrument(skip_all)]
pub async fn update_payment_processor_token_schedule_time(
state: &SessionState,
connector_customer_id: &str,
payment_processor_token: &str,
schedule_time: Option<PrimitiveDateTime>,
decision_threshold: Option<f64>,
) -> CustomResult<bool, errors::StorageError> {
let updated_token =
Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)
.await?
.values()
.find(|status| {
status
.payment_processor_token_details
.payment_processor_token
== payment_processor_token
})
.map(|status| PaymentProcessorTokenStatus {
payment_processor_token_details: status.payment_processor_token_details.clone(),
inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),
error_code: status.error_code.clone(),
daily_retry_history: status.daily_retry_history.clone(),
scheduled_at: schedule_time,
is_hard_decline: status.is_hard_decline,
modified_at: Some(PrimitiveDateTime::new(
OffsetDateTime::now_utc().date(),
OffsetDateTime::now_utc().time(),
)),
is_active: status.is_active,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/authentication.rs | crates/router/src/types/storage/authentication.rs | pub use diesel_models::authentication::{Authentication, AuthenticationNew, AuthenticationUpdate};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/business_profile.rs | crates/router/src/types/storage/business_profile.rs | pub use diesel_models::business_profile::{Profile, ProfileNew, ProfileUpdateInternal};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/mandate.rs | crates/router/src/types/storage/mandate.rs | use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::errors::CustomResult;
use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};
pub use diesel_models::mandate::{
Mandate, MandateNew, MandateUpdate, MandateUpdateInternal, SingleUseMandate,
};
use diesel_models::{errors, schema::mandate::dsl};
use error_stack::ResultExt;
use crate::{connection::PgPooledConn, logger};
#[async_trait::async_trait]
pub trait MandateDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
mandate_list_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
}
#[async_trait::async_trait]
impl MandateDbExt for Mandate {
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
mandate_list_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::created_at.desc())
.into_boxed();
if let Some(created_time) = mandate_list_constraints.created_time {
filter = filter.filter(dsl::created_at.eq(created_time));
}
if let Some(created_time_lt) = mandate_list_constraints.created_time_lt {
filter = filter.filter(dsl::created_at.lt(created_time_lt));
}
if let Some(created_time_gt) = mandate_list_constraints.created_time_gt {
filter = filter.filter(dsl::created_at.gt(created_time_gt));
}
if let Some(created_time_lte) = mandate_list_constraints.created_time_lte {
filter = filter.filter(dsl::created_at.le(created_time_lte));
}
if let Some(created_time_gte) = mandate_list_constraints.created_time_gte {
filter = filter.filter(dsl::created_at.ge(created_time_gte));
}
if let Some(connector) = mandate_list_constraints.connector {
filter = filter.filter(dsl::connector.eq(connector));
}
if let Some(mandate_status) = mandate_list_constraints.mandate_status {
filter = filter.filter(dsl::mandate_status.eq(mandate_status));
}
if let Some(limit) = mandate_list_constraints.limit {
filter = filter.limit(limit);
}
if let Some(offset) = mandate_list_constraints.offset {
filter = filter.offset(offset);
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
.get_results_async(conn)
.await
// The query built here returns an empty Vec when no records are found, and if any error does occur,
// it would be an internal database error, due to which we are raising a DatabaseError::Unknown error
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering mandates by specified constraints")
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/role.rs | crates/router/src/types/storage/role.rs | pub use diesel_models::role::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/events.rs | crates/router/src/types/storage/events.rs | pub use diesel_models::events::{Event, EventMetadata, EventNew};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/authorization.rs | crates/router/src/types/storage/authorization.rs | pub use diesel_models::authorization::{Authorization, AuthorizationNew, AuthorizationUpdate};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/dashboard_metadata.rs | crates/router/src/types/storage/dashboard_metadata.rs | pub use diesel_models::user::dashboard_metadata::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/refund.rs | crates/router/src/types/storage/refund.rs | use api_models::payments::AmountFilter;
use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::errors::CustomResult;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl};
#[cfg(feature = "v1")]
use diesel_models::schema::refund::dsl;
#[cfg(feature = "v2")]
use diesel_models::schema_v2::refund::dsl;
use diesel_models::{
enums::{Currency, RefundStatus},
errors,
query::generics::db_metrics,
refund::Refund,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::refunds;
use crate::{connection::PgPooledConn, logger};
#[async_trait::async_trait]
pub trait RefundDbExt: Sized {
#[cfg(feature = "v1")]
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
#[cfg(feature = "v2")]
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
#[cfg(feature = "v1")]
async fn filter_by_meta_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &common_utils::types::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError>;
#[cfg(feature = "v1")]
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError>;
#[cfg(feature = "v1")]
async fn get_refund_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError>;
#[cfg(feature = "v2")]
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError>;
}
#[async_trait::async_trait]
impl RefundDbExt for Refund {
#[cfg(feature = "v1")]
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::modified_at.desc())
.into_boxed();
let mut search_by_pay_or_ref_id = false;
if let (Some(pid), Some(ref_id)) = (
&refund_list_details.payment_id,
&refund_list_details.refund_id,
) {
search_by_pay_or_ref_id = true;
filter = filter
.filter(
dsl::payment_id
.eq(pid.to_owned())
.or(dsl::refund_id.eq(ref_id.to_owned())),
)
.limit(limit)
.offset(offset);
};
if !search_by_pay_or_ref_id {
match &refund_list_details.payment_id {
Some(pid) => {
filter = filter.filter(dsl::payment_id.eq(pid.to_owned()));
}
None => {
filter = filter.limit(limit).offset(offset);
}
};
}
if !search_by_pay_or_ref_id {
match &refund_list_details.refund_id {
Some(ref_id) => {
filter = filter.filter(dsl::refund_id.eq(ref_id.to_owned()));
}
None => {
filter = filter.limit(limit).offset(offset);
}
};
}
match &refund_list_details.profile_id {
Some(profile_id) => {
filter = filter
.filter(dsl::profile_id.eq_any(profile_id.to_owned()))
.limit(limit)
.offset(offset);
}
None => {
filter = filter.limit(limit).offset(offset);
}
};
if let Some(time_range) = refund_list_details.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
if let Some(end_time) = time_range.end_time {
filter = filter.filter(dsl::created_at.le(end_time));
}
}
filter = match refund_list_details.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => filter.filter(dsl::refund_amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.le(end)),
_ => filter,
};
if let Some(connector) = refund_list_details.connector.clone() {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() {
filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id));
}
if let Some(filter_currency) = &refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency.clone()));
}
if let Some(filter_refund_status) = &refund_list_details.refund_status {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone()));
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_results_async(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
}
#[cfg(feature = "v2")]
async fn filter_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
limit: i64,
offset: i64,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::modified_at.desc())
.into_boxed();
if let Some(payment_id) = &refund_list_details.payment_id {
filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
}
if let Some(refund_id) = &refund_list_details.refund_id {
filter = filter.filter(dsl::id.eq(refund_id.to_owned()));
}
if let Some(time_range) = &refund_list_details.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
if let Some(end_time) = time_range.end_time {
filter = filter.filter(dsl::created_at.le(end_time));
}
}
filter = match refund_list_details.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => filter.filter(dsl::refund_amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.le(end)),
_ => filter,
};
if let Some(connector) = refund_list_details.connector {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(connector_id_list) = refund_list_details.connector_id_list {
filter = filter.filter(dsl::connector_id.eq_any(connector_id_list));
}
if let Some(filter_currency) = refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency));
}
if let Some(filter_refund_status) = refund_list_details.refund_status {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status));
}
filter = filter.limit(limit).offset(offset);
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_results_async(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
// todo!()
}
#[cfg(feature = "v1")]
async fn filter_by_meta_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &common_utils::types::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError> {
let start_time = refund_list_details.start_time;
let end_time = refund_list_details
.end_time
.unwrap_or_else(common_utils::date_time::now);
let filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.order(dsl::modified_at.desc())
.filter(dsl::created_at.ge(start_time))
.filter(dsl::created_at.le(end_time));
let filter_connector: Vec<String> = filter
.clone()
.select(dsl::connector)
.distinct()
.order_by(dsl::connector.asc())
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by connector")?;
let filter_currency: Vec<Currency> = filter
.clone()
.select(dsl::currency)
.distinct()
.order_by(dsl::currency.asc())
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by currency")?;
let filter_status: Vec<RefundStatus> = filter
.select(dsl::refund_status)
.distinct()
.order_by(dsl::refund_status.asc())
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by refund status")?;
let meta = api_models::refunds::RefundListMetaData {
connector: filter_connector,
currency: filter_currency,
refund_status: filter_status,
};
Ok(meta)
}
#[cfg(feature = "v1")]
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.count()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
let mut search_by_pay_or_ref_id = false;
if let (Some(pid), Some(ref_id)) = (
&refund_list_details.payment_id,
&refund_list_details.refund_id,
) {
search_by_pay_or_ref_id = true;
filter = filter.filter(
dsl::payment_id
.eq(pid.to_owned())
.or(dsl::refund_id.eq(ref_id.to_owned())),
);
};
if !search_by_pay_or_ref_id {
if let Some(pay_id) = &refund_list_details.payment_id {
filter = filter.filter(dsl::payment_id.eq(pay_id.to_owned()));
}
}
if !search_by_pay_or_ref_id {
if let Some(ref_id) = &refund_list_details.refund_id {
filter = filter.filter(dsl::refund_id.eq(ref_id.to_owned()));
}
}
if let Some(profile_id) = &refund_list_details.profile_id {
filter = filter.filter(dsl::profile_id.eq_any(profile_id.to_owned()));
}
if let Some(time_range) = refund_list_details.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
if let Some(end_time) = time_range.end_time {
filter = filter.filter(dsl::created_at.le(end_time));
}
}
filter = match refund_list_details.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => filter.filter(dsl::refund_amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.le(end)),
_ => filter,
};
if let Some(connector) = refund_list_details.connector.clone() {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() {
filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id))
}
if let Some(filter_currency) = &refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency.clone()));
}
if let Some(filter_refund_status) = &refund_list_details.refund_status {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone()));
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
.get_result_async::<i64>(conn)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering count of refunds")
}
#[cfg(feature = "v2")]
async fn get_refunds_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
.count()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
if let Some(payment_id) = &refund_list_details.payment_id {
filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
}
if let Some(refund_id) = &refund_list_details.refund_id {
filter = filter.filter(dsl::id.eq(refund_id.to_owned()));
}
if let Some(time_range) = refund_list_details.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
if let Some(end_time) = time_range.end_time {
filter = filter.filter(dsl::created_at.le(end_time));
}
}
filter = match refund_list_details.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => filter.filter(dsl::refund_amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => filter.filter(dsl::refund_amount.le(end)),
_ => filter,
};
if let Some(connector) = refund_list_details.connector {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(connector_id_list) = refund_list_details.connector_id_list {
filter = filter.filter(dsl::connector_id.eq_any(connector_id_list));
}
if let Some(filter_currency) = refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency));
}
if let Some(filter_refund_status) = refund_list_details.refund_status {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status));
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
.get_result_async::<i64>(conn)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering count of refunds")
}
#[cfg(feature = "v1")]
async fn get_refund_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError> {
let mut query = <Self as HasTable>::table()
.group_by(dsl::refund_status)
.select((dsl::refund_status, diesel::dsl::count_star()))
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
if let Some(profile_id) = profile_id_list {
query = query.filter(dsl::profile_id.eq_any(profile_id));
}
query = query.filter(dsl::created_at.ge(time_range.start_time));
query = match time_range.end_time {
Some(ending_at) => query.filter(dsl::created_at.le(ending_at)),
None => query,
};
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
query.get_results_async::<(RefundStatus, i64)>(conn),
db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering status count of refunds")
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/kv.rs | crates/router/src/types/storage/kv.rs | pub use diesel_models::kv::{
AddressUpdateMems, DBOperation, Insertable, PaymentAttemptUpdateMems, PaymentIntentUpdateMems,
RefundUpdateMems, TypedSql, Updateable,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/routing_algorithm.rs | crates/router/src/types/storage/routing_algorithm.rs | pub use diesel_models::routing_algorithm::{
RoutingAlgorithm, RoutingAlgorithmMetadata, RoutingProfileMetadata,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/configs.rs | crates/router/src/types/storage/configs.rs | pub use diesel_models::configs::{Config, ConfigNew, ConfigUpdate, ConfigUpdateInternal};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/hyperswitch_ai_interaction.rs | crates/router/src/types/storage/hyperswitch_ai_interaction.rs | pub use diesel_models::hyperswitch_ai_interaction::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/reverse_lookup.rs | crates/router/src/types/storage/reverse_lookup.rs | pub use diesel_models::reverse_lookup::{ReverseLookup, ReverseLookupNew};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/storage/merchant_key_store.rs | crates/router/src/types/storage/merchant_key_store.rs | pub use diesel_models::merchant_key_store::MerchantKeyStore;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/domain/user.rs | crates/router/src/types/domain/user.rs | use std::{
collections::HashSet,
ops::{Deref, Not},
str::FromStr,
sync::LazyLock,
};
use api_models::{
admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,
};
use common_enums::EntityType;
use common_utils::{
crypto::Encryptable, id_type, new_type::MerchantName, pii, type_name,
types::keymanager::Identifier,
};
use diesel_models::{
enums::{TotpStatus, UserRoleVersion, UserStatus},
organization::{self as diesel_org, Organization, OrganizationBridge},
user as storage_user,
user_role::{UserRole, UserRoleNew},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::api::ApplicationResponse;
use masking::{ExposeInterface, PeekInterface, Secret};
use rand::distributions::{Alphanumeric, DistString};
use time::PrimitiveDateTime;
use unicode_segmentation::UnicodeSegmentation;
#[cfg(feature = "keymanager_create")]
use {base64::Engine, common_utils::types::keymanager::EncryptionTransferRequest};
use crate::{
consts,
core::{
admin,
errors::{UserErrors, UserResult},
},
db::GlobalStorageInterface,
routes::SessionState,
services::{
self,
authentication::{AuthenticationDataWithOrg, UserFromToken},
},
types::{domain, transformers::ForeignFrom},
utils::{self, user::password},
};
pub mod dashboard_metadata;
pub mod decision_manager;
pub use decision_manager::*;
pub mod oidc;
pub mod user_authentication_method;
use super::{types as domain_types, UserKeyStore};
#[derive(Clone)]
pub struct UserName(Secret<String>);
impl UserName {
pub fn new(name: Secret<String>) -> UserResult<Self> {
let name = name.expose();
let is_empty_or_whitespace = name.trim().is_empty();
let is_too_long = name.graphemes(true).count() > consts::user::MAX_NAME_LENGTH;
let forbidden_characters = ['/', '(', ')', '"', '<', '>', '\\', '{', '}'];
let contains_forbidden_characters = name.chars().any(|g| forbidden_characters.contains(&g));
if is_empty_or_whitespace || is_too_long || contains_forbidden_characters {
Err(UserErrors::NameParsingError.into())
} else {
Ok(Self(name.into()))
}
}
pub fn get_secret(self) -> Secret<String> {
self.0
}
}
impl TryFrom<pii::Email> for UserName {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: pii::Email) -> UserResult<Self> {
Self::new(Secret::new(
value
.peek()
.split_once('@')
.ok_or(UserErrors::InvalidEmailError)?
.0
.to_string(),
))
}
}
#[derive(Clone, Debug)]
pub struct UserEmail(pii::Email);
static BLOCKED_EMAIL: LazyLock<HashSet<String>> = LazyLock::new(|| {
let blocked_emails_content = include_str!("../../utils/user/blocker_emails.txt");
let blocked_emails: HashSet<String> = blocked_emails_content
.lines()
.map(|s| s.trim().to_owned())
.collect();
blocked_emails
});
impl UserEmail {
pub fn new(email: Secret<String, pii::EmailStrategy>) -> UserResult<Self> {
use validator::ValidateEmail;
let email_string = email.expose().to_lowercase();
let email =
pii::Email::from_str(&email_string).change_context(UserErrors::EmailParsingError)?;
if email_string.validate_email() {
let (_username, domain) = match email_string.as_str().split_once('@') {
Some((u, d)) => (u, d),
None => return Err(UserErrors::EmailParsingError.into()),
};
if BLOCKED_EMAIL.contains(domain) {
return Err(UserErrors::InvalidEmailError.into());
}
Ok(Self(email))
} else {
Err(UserErrors::EmailParsingError.into())
}
}
pub fn from_pii_email(email: pii::Email) -> UserResult<Self> {
let email_string = email.expose().map(|inner| inner.to_lowercase());
Self::new(email_string)
}
pub fn into_inner(self) -> pii::Email {
self.0
}
pub fn get_inner(&self) -> &pii::Email {
&self.0
}
pub fn get_secret(self) -> Secret<String, pii::EmailStrategy> {
(*self.0).clone()
}
pub fn extract_domain(&self) -> UserResult<&str> {
let (_username, domain) = self
.peek()
.split_once('@')
.ok_or(UserErrors::InternalServerError)?;
Ok(domain)
}
}
impl TryFrom<pii::Email> for UserEmail {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: pii::Email) -> Result<Self, Self::Error> {
Self::from_pii_email(value)
}
}
impl Deref for UserEmail {
type Target = Secret<String, pii::EmailStrategy>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Clone)]
pub struct UserPassword(Secret<String>);
impl UserPassword {
pub fn new(password: Secret<String>) -> UserResult<Self> {
let password = password.expose();
let mut has_upper_case = false;
let mut has_lower_case = false;
let mut has_numeric_value = false;
let mut has_special_character = false;
let mut has_whitespace = false;
for c in password.chars() {
has_upper_case = has_upper_case || c.is_uppercase();
has_lower_case = has_lower_case || c.is_lowercase();
has_numeric_value = has_numeric_value || c.is_numeric();
has_special_character = has_special_character || !c.is_alphanumeric();
has_whitespace = has_whitespace || c.is_whitespace();
}
let is_password_format_valid = has_upper_case
&& has_lower_case
&& has_numeric_value
&& has_special_character
&& !has_whitespace;
let is_too_long = password.graphemes(true).count() > consts::user::MAX_PASSWORD_LENGTH;
let is_too_short = password.graphemes(true).count() < consts::user::MIN_PASSWORD_LENGTH;
if is_too_short || is_too_long || !is_password_format_valid {
return Err(UserErrors::PasswordParsingError.into());
}
Ok(Self(password.into()))
}
pub fn new_password_without_validation(password: Secret<String>) -> UserResult<Self> {
let password = password.expose();
if password.is_empty() {
return Err(UserErrors::PasswordParsingError.into());
}
Ok(Self(password.into()))
}
pub fn get_secret(&self) -> Secret<String> {
self.0.clone()
}
}
#[derive(Clone)]
pub struct UserCompanyName(String);
impl UserCompanyName {
pub fn new(company_name: String) -> UserResult<Self> {
let company_name = company_name.trim();
let is_empty_or_whitespace = company_name.is_empty();
let is_too_long =
company_name.graphemes(true).count() > consts::user::MAX_COMPANY_NAME_LENGTH;
let is_all_valid_characters = company_name
.chars()
.all(|x| x.is_alphanumeric() || x.is_ascii_whitespace() || x == '_');
if is_empty_or_whitespace || is_too_long || !is_all_valid_characters {
Err(UserErrors::CompanyNameParsingError.into())
} else {
Ok(Self(company_name.to_string()))
}
}
pub fn get_secret(self) -> String {
self.0
}
}
#[derive(Clone)]
pub struct NewUserOrganization(diesel_org::OrganizationNew);
impl NewUserOrganization {
pub async fn insert_org_in_db(self, state: SessionState) -> UserResult<Organization> {
state
.accounts_store
.insert_organization(self.0)
.await
.map_err(|e| {
if e.current_context().is_db_unique_violation() {
e.change_context(UserErrors::DuplicateOrganizationId)
} else {
e.change_context(UserErrors::InternalServerError)
}
})
.attach_printable("Error while inserting organization")
}
pub fn get_organization_id(&self) -> id_type::OrganizationId {
self.0.get_organization_id()
}
}
impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserOrganization {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> {
let new_organization = api_org::OrganizationNew::new(
common_enums::OrganizationType::Standard,
Some(UserCompanyName::new(value.company_name)?.get_secret()),
);
let db_organization = ForeignFrom::foreign_from(new_organization);
Ok(Self(db_organization))
}
}
impl From<user_api::SignUpRequest> for NewUserOrganization {
fn from(_value: user_api::SignUpRequest) -> Self {
let new_organization =
api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None);
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
}
impl From<user_api::ConnectAccountRequest> for NewUserOrganization {
fn from(_value: user_api::ConnectAccountRequest) -> Self {
let new_organization =
api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None);
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
}
impl From<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUserOrganization {
fn from(
(_value, org_id): (user_api::CreateInternalUserRequest, id_type::OrganizationId),
) -> Self {
let new_organization = api_org::OrganizationNew {
org_id,
org_type: common_enums::OrganizationType::Standard,
org_name: None,
};
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
}
impl From<UserMerchantCreateRequestWithToken> for NewUserOrganization {
fn from(value: UserMerchantCreateRequestWithToken) -> Self {
Self(diesel_org::OrganizationNew::new(
value.2.org_id,
common_enums::OrganizationType::Standard,
Some(value.1.company_name),
))
}
}
impl From<user_api::PlatformAccountCreateRequest> for NewUserOrganization {
fn from(value: user_api::PlatformAccountCreateRequest) -> Self {
let new_organization = api_org::OrganizationNew::new(
common_enums::OrganizationType::Platform,
Some(value.organization_name.expose()),
);
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
}
type InviteeUserRequestWithInvitedUserToken = (user_api::InviteUserRequest, UserFromToken);
impl From<InviteeUserRequestWithInvitedUserToken> for NewUserOrganization {
fn from(_value: InviteeUserRequestWithInvitedUserToken) -> Self {
let new_organization =
api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None);
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
}
impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUserOrganization {
fn from(
(_value, merchant_account_identifier): (
user_api::CreateTenantUserRequest,
MerchantAccountIdentifier,
),
) -> Self {
let new_organization = api_org::OrganizationNew {
org_id: merchant_account_identifier.org_id,
org_type: common_enums::OrganizationType::Standard,
org_name: None,
};
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
}
impl ForeignFrom<api_models::user::UserOrgMerchantCreateRequest>
for diesel_models::organization::OrganizationNew
{
fn foreign_from(item: api_models::user::UserOrgMerchantCreateRequest) -> Self {
let org_id = id_type::OrganizationId::default();
let api_models::user::UserOrgMerchantCreateRequest {
organization_name,
organization_details,
metadata,
..
} = item;
let mut org_new_db = Self::new(
org_id,
common_enums::OrganizationType::Standard,
Some(organization_name.expose()),
);
org_new_db.organization_details = organization_details;
org_new_db.metadata = metadata;
org_new_db
}
}
#[derive(Clone)]
pub struct MerchantId(String);
impl MerchantId {
pub fn new(merchant_id: String) -> UserResult<Self> {
let merchant_id = merchant_id.trim().to_lowercase().replace(' ', "_");
let is_empty_or_whitespace = merchant_id.is_empty();
let is_all_valid_characters = merchant_id.chars().all(|x| x.is_alphanumeric() || x == '_');
if is_empty_or_whitespace || !is_all_valid_characters {
Err(UserErrors::MerchantIdParsingError.into())
} else {
Ok(Self(merchant_id.to_string()))
}
}
pub fn get_secret(&self) -> String {
self.0.clone()
}
}
impl TryFrom<MerchantId> for id_type::MerchantId {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: MerchantId) -> Result<Self, Self::Error> {
Self::try_from(std::borrow::Cow::from(value.0))
.change_context(UserErrors::MerchantIdParsingError)
.attach_printable("Could not convert user merchant_id to merchant_id type")
}
}
#[derive(Clone)]
pub struct NewUserMerchant {
merchant_id: id_type::MerchantId,
company_name: Option<UserCompanyName>,
new_organization: NewUserOrganization,
product_type: Option<common_enums::MerchantProductType>,
merchant_account_type: Option<common_enums::MerchantAccountRequestType>,
}
impl TryFrom<UserCompanyName> for MerchantName {
// We should ideally not get this error because all the validations are done for company name
type Error = error_stack::Report<UserErrors>;
fn try_from(company_name: UserCompanyName) -> Result<Self, Self::Error> {
Self::try_new(company_name.get_secret()).change_context(UserErrors::CompanyNameParsingError)
}
}
impl NewUserMerchant {
pub fn get_company_name(&self) -> Option<String> {
self.company_name.clone().map(UserCompanyName::get_secret)
}
pub fn get_merchant_id(&self) -> id_type::MerchantId {
self.merchant_id.clone()
}
pub fn get_new_organization(&self) -> NewUserOrganization {
self.new_organization.clone()
}
pub fn get_product_type(&self) -> Option<common_enums::MerchantProductType> {
self.product_type
}
pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> {
if state
.store
.get_merchant_key_store_by_merchant_id(
&self.get_merchant_id(),
&state.store.get_master_key().to_vec().into(),
)
.await
.is_ok()
{
return Err(UserErrors::MerchantAccountCreationError(format!(
"Merchant with {:?} already exists",
self.get_merchant_id()
))
.into());
}
Ok(())
}
#[cfg(feature = "v2")]
fn create_merchant_account_request(&self) -> UserResult<admin_api::MerchantAccountCreate> {
let merchant_name = if let Some(company_name) = self.company_name.clone() {
MerchantName::try_from(company_name)
} else {
MerchantName::try_new("merchant".to_string())
.change_context(UserErrors::InternalServerError)
.attach_printable("merchant name validation failed")
}
.map(Secret::new)?;
Ok(admin_api::MerchantAccountCreate {
merchant_name,
organization_id: self.new_organization.get_organization_id(),
metadata: None,
merchant_details: None,
product_type: self.get_product_type(),
})
}
#[cfg(feature = "v1")]
fn create_merchant_account_request(&self) -> UserResult<admin_api::MerchantAccountCreate> {
Ok(admin_api::MerchantAccountCreate {
merchant_id: self.get_merchant_id(),
metadata: None,
locker_id: None,
return_url: None,
merchant_name: self.get_company_name().map(Secret::new),
webhook_details: None,
publishable_key: None,
organization_id: Some(self.new_organization.get_organization_id()),
merchant_details: None,
routing_algorithm: None,
parent_merchant_id: None,
sub_merchants_enabled: None,
frm_routing_algorithm: None,
#[cfg(feature = "payouts")]
payout_routing_algorithm: None,
primary_business_details: None,
payment_response_hash_key: None,
enable_payment_response_hash: None,
redirect_to_merchant_with_http_post: None,
pm_collect_link_config: None,
product_type: self.get_product_type(),
merchant_account_type: self.merchant_account_type,
})
}
#[cfg(feature = "v1")]
pub async fn create_new_merchant_and_insert_in_db(
&self,
state: SessionState,
) -> UserResult<domain::MerchantAccount> {
self.check_if_already_exists_in_db(state.clone()).await?;
let merchant_account_create_request = self
.create_merchant_account_request()
.attach_printable("Unable to construct merchant account create request")?;
let org_id = merchant_account_create_request
.clone()
.organization_id
.ok_or(UserErrors::InternalServerError)?;
let ApplicationResponse::Json(merchant_account_response) =
Box::pin(admin::create_merchant_account(
state.clone(),
merchant_account_create_request,
Some(AuthenticationDataWithOrg {
organization_id: org_id,
}),
))
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error while creating merchant")?
else {
return Err(UserErrors::InternalServerError.into());
};
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&merchant_account_response.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve merchant key store by merchant_id")?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(
&merchant_account_response.merchant_id,
&merchant_key_store,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve merchant account by merchant_id")?;
Ok(merchant_account)
}
#[cfg(feature = "v2")]
pub async fn create_new_merchant_and_insert_in_db(
&self,
state: SessionState,
) -> UserResult<domain::MerchantAccount> {
self.check_if_already_exists_in_db(state.clone()).await?;
let merchant_account_create_request = self
.create_merchant_account_request()
.attach_printable("unable to construct merchant account create request")?;
let ApplicationResponse::Json(merchant_account_response) = Box::pin(
admin::create_merchant_account(state.clone(), merchant_account_create_request, None),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error while creating a merchant")?
else {
return Err(UserErrors::InternalServerError.into());
};
let profile_create_request = admin_api::ProfileCreate {
profile_name: consts::user::DEFAULT_PROFILE_NAME.to_string(),
..Default::default()
};
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&merchant_account_response.id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve merchant key store by merchant_id")?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(
&merchant_account_response.id,
&merchant_key_store,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve merchant account by merchant_id")?;
let platform = domain::Platform::new(
merchant_account.clone(),
merchant_key_store.clone(),
merchant_account.clone(),
merchant_key_store.clone(),
None,
);
Box::pin(admin::create_profile(
state,
profile_create_request,
platform.get_processor().clone(),
))
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error while creating a profile")?;
Ok(merchant_account)
}
}
impl TryFrom<user_api::SignUpRequest> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::SignUpRequest) -> UserResult<Self> {
let merchant_id = id_type::MerchantId::new_from_unix_timestamp();
let new_organization = NewUserOrganization::from(value);
let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE);
Ok(Self {
company_name: None,
merchant_id,
new_organization,
product_type,
merchant_account_type: None,
})
}
}
impl TryFrom<user_api::ConnectAccountRequest> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::ConnectAccountRequest) -> UserResult<Self> {
let merchant_id = id_type::MerchantId::new_from_unix_timestamp();
let new_organization = NewUserOrganization::from(value);
let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE);
Ok(Self {
company_name: None,
merchant_id,
new_organization,
product_type,
merchant_account_type: None,
})
}
}
impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> {
let company_name = Some(UserCompanyName::new(value.company_name.clone())?);
let merchant_id = MerchantId::new(value.company_name.clone())?;
let new_organization = NewUserOrganization::try_from(value)?;
let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE);
Ok(Self {
company_name,
merchant_id: id_type::MerchantId::try_from(merchant_id)?,
new_organization,
product_type,
merchant_account_type: None,
})
}
}
impl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(
value: (user_api::CreateInternalUserRequest, id_type::OrganizationId),
) -> UserResult<Self> {
let merchant_id = id_type::MerchantId::get_internal_user_merchant_id(
consts::user_role::INTERNAL_USER_MERCHANT_ID,
);
let new_organization = NewUserOrganization::from(value);
Ok(Self {
company_name: None,
merchant_id,
new_organization,
product_type: None,
merchant_account_type: None,
})
}
}
impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: InviteeUserRequestWithInvitedUserToken) -> UserResult<Self> {
let merchant_id = value.clone().1.merchant_id;
let new_organization = NewUserOrganization::from(value);
Ok(Self {
company_name: None,
merchant_id,
new_organization,
product_type: None,
merchant_account_type: None,
})
}
}
impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUserMerchant {
fn from(value: (user_api::CreateTenantUserRequest, MerchantAccountIdentifier)) -> Self {
let merchant_id = value.1.merchant_id.clone();
let new_organization = NewUserOrganization::from(value);
Self {
company_name: None,
merchant_id,
new_organization,
product_type: None,
merchant_account_type: None,
}
}
}
type UserMerchantCreateRequestWithToken =
(UserFromStorage, user_api::UserMerchantCreate, UserFromToken);
impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: UserMerchantCreateRequestWithToken) -> UserResult<Self> {
let merchant_id =
utils::user::generate_env_specific_merchant_id(value.1.company_name.clone())?;
let (user_from_storage, user_merchant_create, user_from_token) = value;
Ok(Self {
merchant_id,
company_name: Some(UserCompanyName::new(
user_merchant_create.company_name.clone(),
)?),
product_type: user_merchant_create.product_type,
merchant_account_type: user_merchant_create.merchant_account_type,
new_organization: NewUserOrganization::from((
user_from_storage,
user_merchant_create,
user_from_token,
)),
})
}
}
impl TryFrom<user_api::PlatformAccountCreateRequest> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::PlatformAccountCreateRequest) -> UserResult<Self> {
let merchant_id = utils::user::generate_env_specific_merchant_id(
value.organization_name.clone().expose(),
)?;
let new_organization = NewUserOrganization::from(value);
Ok(Self {
company_name: None,
merchant_id,
new_organization,
product_type: Some(consts::user::DEFAULT_PRODUCT_TYPE),
merchant_account_type: None,
})
}
}
#[derive(Debug, Clone)]
pub struct MerchantAccountIdentifier {
pub merchant_id: id_type::MerchantId,
pub org_id: id_type::OrganizationId,
}
#[derive(Clone)]
pub struct NewUser {
user_id: String,
name: UserName,
email: UserEmail,
password: Option<NewUserPassword>,
new_merchant: NewUserMerchant,
}
#[derive(Clone)]
pub struct NewUserPassword {
password: UserPassword,
is_temporary: bool,
}
impl Deref for NewUserPassword {
type Target = UserPassword;
fn deref(&self) -> &Self::Target {
&self.password
}
}
impl NewUser {
pub fn get_user_id(&self) -> String {
self.user_id.clone()
}
pub fn get_email(&self) -> UserEmail {
self.email.clone()
}
pub fn get_name(&self) -> Secret<String> {
self.name.clone().get_secret()
}
pub fn get_new_merchant(&self) -> NewUserMerchant {
self.new_merchant.clone()
}
pub fn get_password(&self) -> Option<UserPassword> {
self.password
.as_ref()
.map(|password| password.deref().clone())
}
pub async fn insert_user_in_db(
&self,
db: &dyn GlobalStorageInterface,
) -> UserResult<UserFromStorage> {
match db.insert_user(self.clone().try_into()?).await {
Ok(user) => Ok(user.into()),
Err(e) => {
if e.current_context().is_db_unique_violation() {
Err(e.change_context(UserErrors::UserExists))
} else {
Err(e.change_context(UserErrors::InternalServerError))
}
}
}
.attach_printable("Error while inserting user")
}
pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> {
if state
.global_store
.find_user_by_email(&self.get_email())
.await
.is_ok()
{
return Err(report!(UserErrors::UserExists));
}
Ok(())
}
pub async fn insert_user_and_merchant_in_db(
&self,
state: SessionState,
) -> UserResult<UserFromStorage> {
self.check_if_already_exists_in_db(state.clone()).await?;
let db = state.global_store.as_ref();
let merchant_id = self.get_new_merchant().get_merchant_id();
self.new_merchant
.create_new_merchant_and_insert_in_db(state.clone())
.await?;
let created_user = self.insert_user_in_db(db).await;
if created_user.is_err() {
let _ = admin::merchant_account_delete(state, merchant_id).await;
};
created_user
}
pub fn get_no_level_user_role(
self,
role_id: String,
user_status: UserStatus,
) -> NewUserRole<NoLevel> {
let now = common_utils::date_time::now();
let user_id = self.get_user_id();
NewUserRole {
status: user_status,
created_by: user_id.clone(),
last_modified_by: user_id.clone(),
user_id,
role_id,
created_at: now,
last_modified: now,
entity: NoLevel,
}
}
pub async fn insert_org_level_user_role_in_db(
self,
state: SessionState,
role_id: String,
user_status: UserStatus,
) -> UserResult<UserRole> {
let org_id = self
.get_new_merchant()
.get_new_organization()
.get_organization_id();
let org_user_role = self
.get_no_level_user_role(role_id, user_status)
.add_entity(OrganizationLevel {
tenant_id: state.tenant.tenant_id.clone(),
org_id,
});
org_user_role.insert_in_v2(&state).await
}
}
impl TryFrom<NewUser> for storage_user::UserNew {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: NewUser) -> UserResult<Self> {
let hashed_password = value
.password
.as_ref()
.map(|password| password::generate_password_hash(password.get_secret()))
.transpose()?;
let now = common_utils::date_time::now();
Ok(Self {
user_id: value.get_user_id(),
name: value.get_name(),
email: value.get_email().into_inner(),
password: hashed_password,
is_verified: false,
created_at: Some(now),
last_modified_at: Some(now),
totp_status: TotpStatus::NotSet,
totp_secret: None,
totp_recovery_codes: None,
last_password_modified_at: value
.password
.and_then(|password_inner| password_inner.is_temporary.not().then_some(now)),
lineage_context: None,
})
}
}
impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUser {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> {
let email = value.email.clone().try_into()?;
let name = UserName::new(value.name.clone())?;
let password = NewUserPassword {
password: UserPassword::new(value.password.clone())?,
is_temporary: false,
};
let user_id = uuid::Uuid::new_v4().to_string();
let new_merchant = NewUserMerchant::try_from(value)?;
Ok(Self {
name,
email,
password: Some(password),
user_id,
new_merchant,
})
}
}
impl TryFrom<user_api::SignUpRequest> for NewUser {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::SignUpRequest) -> UserResult<Self> {
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.email.clone().try_into()?;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/domain/event.rs | crates/router/src/types/domain/event.rs | use common_utils::{
crypto::{Encryptable, OptionalEncryptableSecretString},
encryption::Encryption,
type_name,
types::keymanager::{KeyManagerState, ToEncryptable},
};
use diesel_models::{
enums::{EventClass, EventObjectType, EventType, WebhookDeliveryAttempt},
events::{EventMetadata, EventUpdateInternal},
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use rustc_hash::FxHashMap;
use crate::{
errors::{CustomResult, ValidationError},
types::domain::types,
};
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Event {
/// A string that uniquely identifies the event.
pub event_id: String,
/// Represents the type of event for the webhook.
pub event_type: EventType,
/// Represents the class of event for the webhook.
pub event_class: EventClass,
/// Indicates whether the current webhook delivery was successful.
pub is_webhook_notified: bool,
/// Reference to the object for which the webhook was created.
pub primary_object_id: String,
/// Type of the object type for which the webhook was created.
pub primary_object_type: EventObjectType,
/// The timestamp when the webhook was created.
pub created_at: time::PrimitiveDateTime,
/// Merchant Account identifier to which the object is associated with.
pub merchant_id: Option<common_utils::id_type::MerchantId>,
/// Business Profile identifier to which the object is associated with.
pub business_profile_id: Option<common_utils::id_type::ProfileId>,
/// The timestamp when the primary object was created.
pub primary_object_created_at: Option<time::PrimitiveDateTime>,
/// This allows the event to be uniquely identified to prevent multiple processing.
pub idempotent_event_id: Option<String>,
/// Links to the initial attempt of the event.
pub initial_attempt_id: Option<String>,
/// This field contains the encrypted request data sent as part of the event.
#[encrypt]
pub request: Option<Encryptable<Secret<String>>>,
/// This field contains the encrypted response data received as part of the event.
#[encrypt]
pub response: Option<Encryptable<Secret<String>>>,
/// Represents the event delivery type.
pub delivery_attempt: Option<WebhookDeliveryAttempt>,
/// Holds any additional data related to the event.
pub metadata: Option<EventMetadata>,
/// Indicates whether the event was ultimately delivered.
pub is_overall_delivery_successful: Option<bool>,
}
#[derive(Debug)]
pub enum EventUpdate {
UpdateResponse {
is_webhook_notified: bool,
response: OptionalEncryptableSecretString,
},
OverallDeliveryStatusUpdate {
is_overall_delivery_successful: bool,
},
}
impl From<EventUpdate> for EventUpdateInternal {
fn from(event_update: EventUpdate) -> Self {
match event_update {
EventUpdate::UpdateResponse {
is_webhook_notified,
response,
} => Self {
is_webhook_notified: Some(is_webhook_notified),
response: response.map(Into::into),
is_overall_delivery_successful: None,
},
EventUpdate::OverallDeliveryStatusUpdate {
is_overall_delivery_successful,
} => Self {
is_webhook_notified: None,
response: None,
is_overall_delivery_successful: Some(is_overall_delivery_successful),
},
}
}
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for Event {
type DstType = diesel_models::events::Event;
type NewDstType = diesel_models::events::EventNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::events::Event {
event_id: self.event_id,
event_type: self.event_type,
event_class: self.event_class,
is_webhook_notified: self.is_webhook_notified,
primary_object_id: self.primary_object_id,
primary_object_type: self.primary_object_type,
created_at: self.created_at,
merchant_id: self.merchant_id,
business_profile_id: self.business_profile_id,
primary_object_created_at: self.primary_object_created_at,
idempotent_event_id: self.idempotent_event_id,
initial_attempt_id: self.initial_attempt_id,
request: self.request.map(Into::into),
response: self.response.map(Into::into),
delivery_attempt: self.delivery_attempt,
metadata: self.metadata,
is_overall_delivery_successful: self.is_overall_delivery_successful,
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: common_utils::types::keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let decrypted = types::crypto_operation(
state,
type_name!(Self::DstType),
types::CryptoOperation::BatchDecrypt(EncryptedEvent::to_encryptable(EncryptedEvent {
request: item.request.clone(),
response: item.response.clone(),
})),
key_manager_identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting event data".to_string(),
})?;
let encryptable_event = EncryptedEvent::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting event data".to_string(),
},
)?;
Ok(Self {
event_id: item.event_id,
event_type: item.event_type,
event_class: item.event_class,
is_webhook_notified: item.is_webhook_notified,
primary_object_id: item.primary_object_id,
primary_object_type: item.primary_object_type,
created_at: item.created_at,
merchant_id: item.merchant_id,
business_profile_id: item.business_profile_id,
primary_object_created_at: item.primary_object_created_at,
idempotent_event_id: item.idempotent_event_id,
initial_attempt_id: item.initial_attempt_id,
request: encryptable_event.request,
response: encryptable_event.response,
delivery_attempt: item.delivery_attempt,
metadata: item.metadata,
is_overall_delivery_successful: item.is_overall_delivery_successful,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::events::EventNew {
event_id: self.event_id,
event_type: self.event_type,
event_class: self.event_class,
is_webhook_notified: self.is_webhook_notified,
primary_object_id: self.primary_object_id,
primary_object_type: self.primary_object_type,
created_at: self.created_at,
merchant_id: self.merchant_id,
business_profile_id: self.business_profile_id,
primary_object_created_at: self.primary_object_created_at,
idempotent_event_id: self.idempotent_event_id,
initial_attempt_id: self.initial_attempt_id,
request: self.request.map(Into::into),
response: self.response.map(Into::into),
delivery_attempt: self.delivery_attempt,
metadata: self.metadata,
is_overall_delivery_successful: self.is_overall_delivery_successful,
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/domain/address.rs | crates/router/src/types/domain/address.rs | use async_trait::async_trait;
use common_utils::{
crypto::{self, Encryptable},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
id_type, pii, type_name,
types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
};
use diesel_models::{address::AddressUpdateInternal, enums};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret, SwitchStrategy};
use rustc_hash::FxHashMap;
use time::{OffsetDateTime, PrimitiveDateTime};
use super::{behaviour, types};
#[derive(Clone, Debug, serde::Serialize, router_derive::ToEncryption)]
pub struct Address {
pub address_id: String,
pub city: Option<String>,
pub country: Option<enums::CountryAlpha2>,
#[encrypt]
pub line1: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub line2: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub line3: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub state: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub zip: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub first_name: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub last_name: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub phone_number: Option<Encryptable<Secret<String>>>,
pub country_code: Option<String>,
#[serde(skip_serializing)]
#[serde(with = "custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(skip_serializing)]
#[serde(with = "custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub merchant_id: id_type::MerchantId,
pub updated_by: String,
#[encrypt]
pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
#[encrypt]
pub origin_zip: Option<Encryptable<Secret<String>>>,
}
/// Based on the flow, appropriate address has to be used
/// In case of Payments, The `PaymentAddress`[PaymentAddress] has to be used
/// which contains only the `Address`[Address] object and `payment_id` and optional `customer_id`
#[derive(Debug, Clone)]
pub struct PaymentAddress {
pub address: Address,
pub payment_id: id_type::PaymentId,
// This is present in `PaymentAddress` because even `payouts` uses `PaymentAddress`
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, Clone)]
pub struct CustomerAddress {
pub address: Address,
pub customer_id: id_type::CustomerId,
}
#[async_trait]
impl behaviour::Conversion for CustomerAddress {
type DstType = diesel_models::address::Address;
type NewDstType = diesel_models::address::AddressNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let converted_address = Address::convert(self.address).await?;
Ok(diesel_models::address::Address {
customer_id: Some(self.customer_id),
payment_id: None,
..converted_address
})
}
async fn convert_back(
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let customer_id =
other
.customer_id
.clone()
.ok_or(ValidationError::MissingRequiredField {
field_name: "customer_id".to_string(),
})?;
let address = Address::convert_back(state, other, key, key_manager_identifier).await?;
Ok(Self {
address,
customer_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let address_new = Address::construct_new(self.address).await?;
Ok(Self::NewDstType {
customer_id: Some(self.customer_id),
payment_id: None,
..address_new
})
}
}
#[async_trait]
impl behaviour::Conversion for PaymentAddress {
type DstType = diesel_models::address::Address;
type NewDstType = diesel_models::address::AddressNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let converted_address = Address::convert(self.address).await?;
Ok(diesel_models::address::Address {
customer_id: self.customer_id,
payment_id: Some(self.payment_id),
..converted_address
})
}
async fn convert_back(
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let payment_id = other
.payment_id
.clone()
.ok_or(ValidationError::MissingRequiredField {
field_name: "payment_id".to_string(),
})?;
let customer_id = other.customer_id.clone();
let address = Address::convert_back(state, other, key, key_manager_identifier).await?;
Ok(Self {
address,
payment_id,
customer_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let address_new = Address::construct_new(self.address).await?;
Ok(Self::NewDstType {
customer_id: self.customer_id,
payment_id: Some(self.payment_id),
..address_new
})
}
}
#[async_trait]
impl behaviour::Conversion for Address {
type DstType = diesel_models::address::Address;
type NewDstType = diesel_models::address::AddressNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::address::Address {
address_id: self.address_id,
city: self.city,
country: self.country,
line1: self.line1.map(Encryption::from),
line2: self.line2.map(Encryption::from),
line3: self.line3.map(Encryption::from),
state: self.state.map(Encryption::from),
zip: self.zip.map(Encryption::from),
first_name: self.first_name.map(Encryption::from),
last_name: self.last_name.map(Encryption::from),
phone_number: self.phone_number.map(Encryption::from),
country_code: self.country_code,
created_at: self.created_at,
modified_at: self.modified_at,
merchant_id: self.merchant_id,
updated_by: self.updated_by,
email: self.email.map(Encryption::from),
payment_id: None,
customer_id: None,
origin_zip: self.origin_zip.map(Encryption::from),
})
}
async fn convert_back(
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let identifier = Identifier::Merchant(other.merchant_id.clone());
let decrypted: FxHashMap<String, Encryptable<Secret<String>>> = types::crypto_operation(
state,
type_name!(Self::DstType),
types::CryptoOperation::BatchDecrypt(EncryptedAddress::to_encryptable(
EncryptedAddress {
line1: other.line1,
line2: other.line2,
line3: other.line3,
state: other.state,
zip: other.zip,
first_name: other.first_name,
last_name: other.last_name,
phone_number: other.phone_number,
email: other.email,
origin_zip: other.origin_zip,
},
)),
identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting".to_string(),
})?;
let encryptable_address = EncryptedAddress::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting".to_string(),
},
)?;
Ok(Self {
address_id: other.address_id,
city: other.city,
country: other.country,
line1: encryptable_address.line1,
line2: encryptable_address.line2,
line3: encryptable_address.line3,
state: encryptable_address.state,
zip: encryptable_address.zip,
first_name: encryptable_address.first_name,
last_name: encryptable_address.last_name,
phone_number: encryptable_address.phone_number,
country_code: other.country_code,
created_at: other.created_at,
modified_at: other.modified_at,
updated_by: other.updated_by,
merchant_id: other.merchant_id,
email: encryptable_address.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
origin_zip: encryptable_address.origin_zip,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(Self::NewDstType {
address_id: self.address_id,
city: self.city,
country: self.country,
line1: self.line1.map(Encryption::from),
line2: self.line2.map(Encryption::from),
line3: self.line3.map(Encryption::from),
state: self.state.map(Encryption::from),
zip: self.zip.map(Encryption::from),
first_name: self.first_name.map(Encryption::from),
last_name: self.last_name.map(Encryption::from),
phone_number: self.phone_number.map(Encryption::from),
country_code: self.country_code,
merchant_id: self.merchant_id,
created_at: now,
modified_at: now,
updated_by: self.updated_by,
email: self.email.map(Encryption::from),
customer_id: None,
payment_id: None,
origin_zip: self.origin_zip.map(Encryption::from),
})
}
}
#[derive(Debug, Clone)]
pub enum AddressUpdate {
Update {
city: Option<String>,
country: Option<enums::CountryAlpha2>,
line1: crypto::OptionalEncryptableSecretString,
line2: crypto::OptionalEncryptableSecretString,
line3: crypto::OptionalEncryptableSecretString,
state: crypto::OptionalEncryptableSecretString,
zip: crypto::OptionalEncryptableSecretString,
first_name: crypto::OptionalEncryptableSecretString,
last_name: crypto::OptionalEncryptableSecretString,
phone_number: crypto::OptionalEncryptableSecretString,
country_code: Option<String>,
updated_by: String,
email: crypto::OptionalEncryptableEmail,
origin_zip: crypto::OptionalEncryptableSecretString,
},
}
impl From<AddressUpdate> for AddressUpdateInternal {
fn from(address_update: AddressUpdate) -> Self {
match address_update {
AddressUpdate::Update {
city,
country,
line1,
line2,
line3,
state,
zip,
first_name,
last_name,
phone_number,
country_code,
updated_by,
email,
origin_zip,
} => Self {
city,
country,
line1: line1.map(Encryption::from),
line2: line2.map(Encryption::from),
line3: line3.map(Encryption::from),
state: state.map(Encryption::from),
zip: zip.map(Encryption::from),
first_name: first_name.map(Encryption::from),
last_name: last_name.map(Encryption::from),
phone_number: phone_number.map(Encryption::from),
country_code,
modified_at: date_time::convert_to_pdt(OffsetDateTime::now_utc()),
updated_by,
email: email.map(Encryption::from),
origin_zip: origin_zip.map(Encryption::from),
},
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/domain/user_key_store.rs | crates/router/src/types/domain/user_key_store.rs | use common_utils::{
crypto::Encryptable,
date_time, type_name,
types::keymanager::{Identifier, KeyManagerState},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use masking::{PeekInterface, Secret};
use time::PrimitiveDateTime;
use crate::errors::{CustomResult, ValidationError};
#[derive(Clone, Debug, serde::Serialize)]
pub struct UserKeyStore {
pub user_id: String,
pub key: Encryptable<Secret<Vec<u8>>>,
pub created_at: PrimitiveDateTime,
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for UserKeyStore {
type DstType = diesel_models::user_key_store::UserKeyStore;
type NewDstType = diesel_models::user_key_store::UserKeyStoreNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::user_key_store::UserKeyStore {
key: self.key.into(),
user_id: self.user_id,
created_at: self.created_at,
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let identifier = Identifier::User(item.user_id.clone());
Ok(Self {
key: crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptLocally(item.key),
identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting user key store".to_string(),
})?,
user_id: item.user_id,
created_at: item.created_at,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::user_key_store::UserKeyStoreNew {
user_id: self.user_id,
key: self.key.into(),
created_at: date_time::now(),
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/domain/types.rs | crates/router/src/types/domain/types.rs | use ::payment_methods::state as pm_state;
use common_utils::types::keymanager::KeyManagerState;
pub use hyperswitch_domain_models::type_encryption::{
crypto_operation, AsyncLift, CryptoOperation, Lift, OptionalEncryptableJsonType,
};
use hyperswitch_interfaces::configs;
use crate::{
routes::app,
types::{api as api_types, ForeignFrom},
};
impl ForeignFrom<(&app::AppState, configs::Tenant)> for KeyManagerState {
fn foreign_from((app_state, tenant): (&app::AppState, configs::Tenant)) -> Self {
let conf = app_state.conf.key_manager.get_inner();
Self {
global_tenant_id: app_state.conf.multitenancy.global_tenant.tenant_id.clone(),
tenant_id: tenant.tenant_id.clone(),
enabled: conf.enabled,
url: conf.url.clone(),
client_idle_timeout: app_state.conf.proxy.idle_pool_connection_timeout,
#[cfg(feature = "km_forward_x_request_id")]
request_id: app_state.request_id.clone(),
#[cfg(feature = "keymanager_mtls")]
cert: conf.cert.clone(),
#[cfg(feature = "keymanager_mtls")]
ca: conf.ca.clone(),
infra_values: app::AppState::process_env_mappings(app_state.conf.infra_values.clone()),
}
}
}
impl From<&app::SessionState> for KeyManagerState {
fn from(state: &app::SessionState) -> Self {
let conf = state.conf.key_manager.get_inner();
Self {
global_tenant_id: state.conf.multitenancy.global_tenant.tenant_id.clone(),
tenant_id: state.tenant.tenant_id.clone(),
enabled: conf.enabled,
url: conf.url.clone(),
client_idle_timeout: state.conf.proxy.idle_pool_connection_timeout,
#[cfg(feature = "km_forward_x_request_id")]
request_id: state.request_id.clone(),
#[cfg(feature = "keymanager_mtls")]
cert: conf.cert.clone(),
#[cfg(feature = "keymanager_mtls")]
ca: conf.ca.clone(),
infra_values: app::AppState::process_env_mappings(state.conf.infra_values.clone()),
}
}
}
impl From<&app::SessionState> for pm_state::PaymentMethodsState {
fn from(state: &app::SessionState) -> Self {
Self {
store: state.store.get_payment_methods_store(),
key_store: None,
key_manager_state: state.into(),
}
}
}
pub struct ConnectorConversionHandler;
impl hyperswitch_interfaces::api_client::ConnectorConverter for ConnectorConversionHandler {
fn get_connector_enum_by_name(
&self,
connector: &str,
) -> common_utils::errors::CustomResult<
hyperswitch_interfaces::connector_integration_interface::ConnectorEnum,
hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse,
> {
api_types::ConnectorData::convert_connector(connector)
}
}
impl From<app::SessionState> for subscriptions::state::SubscriptionState {
fn from(state: app::SessionState) -> Self {
Self {
store: state.store.get_subscription_store(),
key_store: None,
key_manager_state: (&state).into(),
api_client: state.api_client.clone(),
conf: subscriptions::state::SubscriptionConfig {
proxy: state.conf.proxy.clone(),
internal_merchant_id_profile_id_auth: state
.conf
.internal_merchant_id_profile_id_auth
.clone(),
internal_services: state.conf.internal_services.clone(),
connectors: state.conf.connectors.clone(),
application_source: state.conf.application_source,
},
tenant: state.tenant.clone(),
event_handler: Box::new(state.event_handler.clone()),
connector_converter: Box::new(ConnectorConversionHandler),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/domain/merchant_connector_account.rs | crates/router/src/types/domain/merchant_connector_account.rs | pub use hyperswitch_domain_models::merchant_connector_account::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/domain/payments.rs | crates/router/src/types/domain/payments.rs | pub use hyperswitch_domain_models::payment_method_data::{
AliPayQr, ApplePayFlow, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod,
BankDebitData, BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardDetail,
CardRedirectData, CardToken, CashappQr, CryptoData, GcashRedirection, GiftCardData,
GiftCardDetails, GoPayRedirection, GooglePayPaymentMethodInfo, GooglePayRedirectData,
GooglePayThirdPartySdkData, GooglePayWalletData, IndomaretVoucherData, KakaoPayRedirection,
MbWayRedirection, MifinityData, NetworkTokenData, OpenBankingData, PayLaterData,
PaymentMethodData, RealTimePaymentData, RevolutPayData, SamsungPayWalletData,
SepaAndBacsBillingDetails, SwishQrData, TokenizedBankDebitValue1, TokenizedBankDebitValue2,
TokenizedBankRedirectValue1, TokenizedBankRedirectValue2, TokenizedBankTransferValue1,
TokenizedBankTransferValue2, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1,
TokenizedWalletValue2, TouchNGoRedirection, UpiCollectData, UpiData, UpiIntentData,
VoucherData, WalletData, WeChatPayQr,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/domain/user/decision_manager.rs | crates/router/src/types/domain/user/decision_manager.rs | use common_enums::TokenPurpose;
use common_utils::{id_type, types::user::LineageContext};
use diesel_models::{
enums::{UserRoleVersion, UserStatus},
user_role::UserRole,
};
use error_stack::ResultExt;
use masking::Secret;
use router_env::logger;
use super::UserFromStorage;
use crate::{
core::errors::{UserErrors, UserResult},
db::user_role::ListUserRolesByUserIdPayload,
routes::SessionState,
services::authentication as auth,
utils,
};
#[derive(Eq, PartialEq, Clone, Copy)]
pub enum UserFlow {
SPTFlow(SPTFlow),
JWTFlow(JWTFlow),
}
impl UserFlow {
async fn is_required(
&self,
user: &UserFromStorage,
path: &[TokenPurpose],
state: &SessionState,
user_tenant_id: &id_type::TenantId,
) -> UserResult<bool> {
match self {
Self::SPTFlow(flow) => flow.is_required(user, path, state, user_tenant_id).await,
Self::JWTFlow(flow) => flow.is_required(user, state).await,
}
}
}
#[derive(Eq, PartialEq, Clone, Copy)]
pub enum SPTFlow {
AuthSelect,
SSO,
TOTP,
VerifyEmail,
AcceptInvitationFromEmail,
ForceSetPassword,
MerchantSelect,
ResetPassword,
}
impl SPTFlow {
async fn is_required(
&self,
user: &UserFromStorage,
path: &[TokenPurpose],
state: &SessionState,
user_tenant_id: &id_type::TenantId,
) -> UserResult<bool> {
match self {
// Auth
Self::AuthSelect => Ok(true),
Self::SSO => Ok(true),
// TOTP
Self::TOTP => Ok(!path.contains(&TokenPurpose::SSO)),
// Main email APIs
Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true),
Self::VerifyEmail => Ok(true),
// Final Checks
Self::ForceSetPassword => user
.is_password_rotate_required(state)
.map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)),
Self::MerchantSelect => Ok(state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user.get_user_id(),
tenant_id: user_tenant_id,
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: Some(1),
})
.await
.change_context(UserErrors::InternalServerError)?
.is_empty()),
}
}
pub async fn generate_spt(
self,
state: &SessionState,
next_flow: &NextFlow,
) -> UserResult<Secret<String>> {
auth::SinglePurposeToken::new_token(
next_flow.user.get_user_id().to_string(),
self.into(),
next_flow.origin.clone(),
&state.conf,
next_flow.path.to_vec(),
Some(state.tenant.tenant_id.clone()),
)
.await
.map(|token| token.into())
}
}
#[derive(Eq, PartialEq, Clone, Copy)]
pub enum JWTFlow {
UserInfo,
}
impl JWTFlow {
async fn is_required(
&self,
_user: &UserFromStorage,
_state: &SessionState,
) -> UserResult<bool> {
Ok(true)
}
pub async fn generate_jwt(
self,
state: &SessionState,
next_flow: &NextFlow,
user_role: &UserRole,
) -> UserResult<Secret<String>> {
let user_id = next_flow.user.get_user_id();
// Fetch lineage context from DB
let lineage_context_from_db = state
.global_store
.find_user_by_id(user_id)
.await
.inspect_err(|e| {
logger::error!(
"Failed to fetch lineage context from DB for user {}: {:?}",
user_id,
e
)
})
.ok()
.and_then(|user| user.lineage_context);
let new_lineage_context = match lineage_context_from_db {
Some(ctx) => {
let tenant_id = ctx.tenant_id.clone();
let user_role_match_v2 = state
.global_store
.find_user_role_by_user_id_and_lineage_with_entity_type(
&ctx.user_id,
&tenant_id,
&ctx.org_id,
&ctx.merchant_id,
&ctx.profile_id,
UserRoleVersion::V2,
)
.await
.inspect_err(|e| {
logger::error!("Failed to validate V2 role: {e:?}");
})
.map(|role| role.role_id == ctx.role_id)
.unwrap_or_default();
if user_role_match_v2 {
ctx
} else {
let user_role_match_v1 = state
.global_store
.find_user_role_by_user_id_and_lineage_with_entity_type(
&ctx.user_id,
&tenant_id,
&ctx.org_id,
&ctx.merchant_id,
&ctx.profile_id,
UserRoleVersion::V1,
)
.await
.inspect_err(|e| {
logger::error!("Failed to validate V1 role: {e:?}");
})
.map(|role| role.role_id == ctx.role_id)
.unwrap_or_default();
if user_role_match_v1 {
ctx
} else {
// fallback to default lineage if cached context is invalid
Self::resolve_lineage_from_user_role(state, user_role, user_id).await?
}
}
}
None =>
// no cached context found
{
Self::resolve_lineage_from_user_role(state, user_role, user_id).await?
}
};
utils::user::spawn_async_lineage_context_update_to_db(
state,
user_id,
new_lineage_context.clone(),
);
auth::AuthToken::new_token(
new_lineage_context.user_id,
new_lineage_context.merchant_id,
new_lineage_context.role_id,
&state.conf,
new_lineage_context.org_id,
new_lineage_context.profile_id,
Some(new_lineage_context.tenant_id),
)
.await
.map(|token| token.into())
}
pub async fn resolve_lineage_from_user_role(
state: &SessionState,
user_role: &UserRole,
user_id: &str,
) -> UserResult<LineageContext> {
let org_id = utils::user_role::get_single_org_id(state, user_role).await?;
let merchant_id =
utils::user_role::get_single_merchant_id(state, user_role, &org_id).await?;
let profile_id =
utils::user_role::get_single_profile_id(state, user_role, &merchant_id).await?;
Ok(LineageContext {
user_id: user_id.to_string(),
org_id,
merchant_id,
profile_id,
role_id: user_role.role_id.clone(),
tenant_id: user_role.tenant_id.clone(),
})
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum Origin {
#[serde(rename = "sign_in_with_sso")]
SignInWithSSO,
SignIn,
SignUp,
MagicLink,
VerifyEmail,
AcceptInvitationFromEmail,
ResetPassword,
}
impl Origin {
fn get_flows(&self) -> &'static [UserFlow] {
match self {
Self::SignInWithSSO => &SIGNIN_WITH_SSO_FLOW,
Self::SignIn => &SIGNIN_FLOW,
Self::SignUp => &SIGNUP_FLOW,
Self::VerifyEmail => &VERIFY_EMAIL_FLOW,
Self::MagicLink => &MAGIC_LINK_FLOW,
Self::AcceptInvitationFromEmail => &ACCEPT_INVITATION_FROM_EMAIL_FLOW,
Self::ResetPassword => &RESET_PASSWORD_FLOW,
}
}
}
const SIGNIN_WITH_SSO_FLOW: [UserFlow; 2] = [
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const SIGNIN_FLOW: [UserFlow; 4] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const SIGNUP_FLOW: [UserFlow; 4] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const MAGIC_LINK_FLOW: [UserFlow; 5] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::VerifyEmail),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const VERIFY_EMAIL_FLOW: [UserFlow; 5] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::VerifyEmail),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 6] = [
UserFlow::SPTFlow(SPTFlow::AuthSelect),
UserFlow::SPTFlow(SPTFlow::SSO),
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::AcceptInvitationFromEmail),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const RESET_PASSWORD_FLOW: [UserFlow; 2] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::ResetPassword),
];
pub struct CurrentFlow {
origin: Origin,
current_flow_index: usize,
path: Vec<TokenPurpose>,
tenant_id: Option<id_type::TenantId>,
}
impl CurrentFlow {
pub fn new(
token: auth::UserFromSinglePurposeToken,
current_flow: UserFlow,
) -> UserResult<Self> {
let flows = token.origin.get_flows();
let index = flows
.iter()
.position(|flow| flow == ¤t_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,
})
}
pub async fn next(self, user: UserFromStorage, state: &SessionState) -> UserResult<NextFlow> {
let flows = self.origin.get_flows();
let remaining_flows = flows.iter().skip(self.current_flow_index + 1);
for flow in remaining_flows {
if flow
.is_required(
&user,
&self.path,
state,
self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
)
.await?
{
return Ok(NextFlow {
origin: self.origin.clone(),
next_flow: *flow,
user,
path: self.path,
tenant_id: self.tenant_id,
});
}
}
Err(UserErrors::InternalServerError.into())
}
}
pub struct NextFlow {
origin: Origin,
next_flow: UserFlow,
user: UserFromStorage,
path: Vec<TokenPurpose>,
tenant_id: Option<id_type::TenantId>,
}
impl NextFlow {
pub async fn from_origin(
origin: Origin,
user: UserFromStorage,
state: &SessionState,
) -> UserResult<Self> {
let flows = origin.get_flows();
let path = vec![];
for flow in flows {
if flow
.is_required(&user, &path, state, &state.tenant.tenant_id)
.await?
{
return Ok(Self {
origin,
next_flow: *flow,
user,
path,
tenant_id: Some(state.tenant.tenant_id.clone()),
});
}
}
Err(UserErrors::InternalServerError.into())
}
pub fn get_flow(&self) -> UserFlow {
self.next_flow
}
pub async fn get_token(&self, state: &SessionState) -> UserResult<Secret<String>> {
match self.next_flow {
UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await,
UserFlow::JWTFlow(jwt_flow) => {
#[cfg(feature = "email")]
{
self.user.get_verification_days_left(state)?;
}
let user_role = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: self.user.get_user_id(),
tenant_id: self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: Some(1),
})
.await
.change_context(UserErrors::InternalServerError)?
.pop()
.ok_or(UserErrors::InternalServerError)?;
utils::user_role::set_role_info_in_cache_by_user_role(state, &user_role).await;
jwt_flow.generate_jwt(state, self, &user_role).await
}
}
}
pub async fn get_token_with_user_role(
&self,
state: &SessionState,
user_role: &UserRole,
) -> UserResult<Secret<String>> {
match self.next_flow {
UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await,
UserFlow::JWTFlow(jwt_flow) => {
#[cfg(feature = "email")]
{
self.user.get_verification_days_left(state)?;
}
utils::user_role::set_role_info_in_cache_by_user_role(state, user_role).await;
jwt_flow.generate_jwt(state, self, user_role).await
}
}
}
pub async fn skip(self, user: UserFromStorage, state: &SessionState) -> UserResult<Self> {
let flows = self.origin.get_flows();
let index = flows
.iter()
.position(|flow| flow == &self.get_flow())
.ok_or(UserErrors::InternalServerError)?;
let remaining_flows = flows.iter().skip(index + 1);
for flow in remaining_flows {
if flow
.is_required(&user, &self.path, state, &state.tenant.tenant_id)
.await?
{
return Ok(Self {
origin: self.origin.clone(),
next_flow: *flow,
user,
path: self.path,
tenant_id: Some(state.tenant.tenant_id.clone()),
});
}
}
Err(UserErrors::InternalServerError.into())
}
}
impl From<UserFlow> for TokenPurpose {
fn from(value: UserFlow) -> Self {
match value {
UserFlow::SPTFlow(flow) => flow.into(),
UserFlow::JWTFlow(flow) => flow.into(),
}
}
}
impl From<SPTFlow> for TokenPurpose {
fn from(value: SPTFlow) -> Self {
match value {
SPTFlow::AuthSelect => Self::AuthSelect,
SPTFlow::SSO => Self::SSO,
SPTFlow::TOTP => Self::TOTP,
SPTFlow::VerifyEmail => Self::VerifyEmail,
SPTFlow::AcceptInvitationFromEmail => Self::AcceptInvitationFromEmail,
SPTFlow::MerchantSelect => Self::AcceptInvite,
SPTFlow::ResetPassword => Self::ResetPassword,
SPTFlow::ForceSetPassword => Self::ForceSetPassword,
}
}
}
impl From<JWTFlow> for TokenPurpose {
fn from(value: JWTFlow) -> Self {
match value {
JWTFlow::UserInfo => Self::UserInfo,
}
}
}
impl From<SPTFlow> for UserFlow {
fn from(value: SPTFlow) -> Self {
Self::SPTFlow(value)
}
}
impl From<JWTFlow> for UserFlow {
fn from(value: JWTFlow) -> Self {
Self::JWTFlow(value)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/domain/user/user_authentication_method.rs | crates/router/src/types/domain/user/user_authentication_method.rs | use std::sync::LazyLock;
use common_enums::{Owner, UserAuthType};
use diesel_models::UserAuthenticationMethod;
pub static DEFAULT_USER_AUTH_METHOD: LazyLock<UserAuthenticationMethod> =
LazyLock::new(|| UserAuthenticationMethod {
id: String::from("hyperswitch_default"),
auth_id: String::from("hyperswitch"),
owner_id: String::from("hyperswitch"),
owner_type: Owner::Tenant,
auth_type: UserAuthType::Password,
private_config: None,
public_config: None,
allow_signup: true,
created_at: common_utils::date_time::now(),
last_modified_at: common_utils::date_time::now(),
email_domain: String::from("hyperswitch"),
});
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/domain/user/oidc.rs | crates/router/src/types/domain/user/oidc.rs | use api_models::oidc::Scope;
use common_utils::pii;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthCodeData {
pub sub: String,
pub client_id: String,
pub redirect_uri: String,
pub scope: Vec<Scope>,
pub nonce: Option<String>,
pub email: pii::Email,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/domain/user/dashboard_metadata.rs | crates/router/src/types/domain/user/dashboard_metadata.rs | use api_models::user::dashboard_metadata as api;
use diesel_models::enums::DashboardMetadata as DBEnum;
use masking::Secret;
use time::PrimitiveDateTime;
pub enum MetaData {
ProductionAgreement(ProductionAgreementValue),
SetupProcessor(api::SetupProcessor),
ConfigureEndpoint(bool),
SetupComplete(bool),
FirstProcessorConnected(api::ProcessorConnected),
SecondProcessorConnected(api::ProcessorConnected),
ConfiguredRouting(api::ConfiguredRouting),
TestPayment(api::TestPayment),
IntegrationMethod(api::IntegrationMethod),
ConfigurationType(api::ConfigurationType),
IntegrationCompleted(bool),
StripeConnected(api::ProcessorConnected),
PaypalConnected(api::ProcessorConnected),
SPRoutingConfigured(api::ConfiguredRouting),
Feedback(api::Feedback),
ProdIntent(api::ProdIntent),
SPTestPayment(bool),
DownloadWoocom(bool),
ConfigureWoocom(bool),
SetupWoocomWebhook(bool),
IsMultipleConfiguration(bool),
IsChangePasswordRequired(bool),
OnboardingSurvey(api::OnboardingSurvey),
ReconStatus(api::ReconStatus),
}
impl From<&MetaData> for DBEnum {
fn from(value: &MetaData) -> Self {
match value {
MetaData::ProductionAgreement(_) => Self::ProductionAgreement,
MetaData::SetupProcessor(_) => Self::SetupProcessor,
MetaData::ConfigureEndpoint(_) => Self::ConfigureEndpoint,
MetaData::SetupComplete(_) => Self::SetupComplete,
MetaData::FirstProcessorConnected(_) => Self::FirstProcessorConnected,
MetaData::SecondProcessorConnected(_) => Self::SecondProcessorConnected,
MetaData::ConfiguredRouting(_) => Self::ConfiguredRouting,
MetaData::TestPayment(_) => Self::TestPayment,
MetaData::IntegrationMethod(_) => Self::IntegrationMethod,
MetaData::ConfigurationType(_) => Self::ConfigurationType,
MetaData::IntegrationCompleted(_) => Self::IntegrationCompleted,
MetaData::StripeConnected(_) => Self::StripeConnected,
MetaData::PaypalConnected(_) => Self::PaypalConnected,
MetaData::SPRoutingConfigured(_) => Self::SpRoutingConfigured,
MetaData::Feedback(_) => Self::Feedback,
MetaData::ProdIntent(_) => Self::ProdIntent,
MetaData::SPTestPayment(_) => Self::SpTestPayment,
MetaData::DownloadWoocom(_) => Self::DownloadWoocom,
MetaData::ConfigureWoocom(_) => Self::ConfigureWoocom,
MetaData::SetupWoocomWebhook(_) => Self::SetupWoocomWebhook,
MetaData::IsMultipleConfiguration(_) => Self::IsMultipleConfiguration,
MetaData::IsChangePasswordRequired(_) => Self::IsChangePasswordRequired,
MetaData::OnboardingSurvey(_) => Self::OnboardingSurvey,
MetaData::ReconStatus(_) => Self::ReconStatus,
}
}
}
#[derive(Debug, serde::Serialize)]
pub struct ProductionAgreementValue {
pub version: String,
pub ip_address: Secret<String, common_utils::pii::IpAddress>,
pub timestamp: PrimitiveDateTime,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/api_keys.rs | crates/router/src/types/api/api_keys.rs | pub use api_models::api_keys::{
ApiKeyExpiration, CreateApiKeyRequest, CreateApiKeyResponse, ListApiKeyConstraints,
RetrieveApiKeyResponse, RevokeApiKeyResponse, UpdateApiKeyRequest,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/mandates.rs | crates/router/src/types/api/mandates.rs | use ::payment_methods::controller::PaymentMethodsController;
use api_models::mandates;
pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse};
use common_utils::ext_traits::OptionExt;
use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payment_methods,
},
newtype,
routes::SessionState,
types::{
api, domain,
storage::{self, enums as storage_enums},
},
};
newtype!(
pub MandateCardDetails = mandates::MandateCardDetails,
derives = (Default, Debug, Deserialize, Serialize)
);
#[async_trait::async_trait]
pub(crate) trait MandateResponseExt: Sized {
async fn from_db_mandate(
state: &SessionState,
key_store: domain::MerchantKeyStore,
mandate: storage::Mandate,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<Self>;
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl MandateResponseExt for MandateResponse {
async fn from_db_mandate(
state: &SessionState,
key_store: domain::MerchantKeyStore,
mandate: storage::Mandate,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<Self> {
let db = &*state.store;
let payment_method = db
.find_payment_method(
&key_store,
&mandate.payment_method_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let pm = payment_method
.get_payment_method_type()
.get_required_value("payment_method")
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("payment_method not found")?;
let card = if pm == storage_enums::PaymentMethod::Card {
// if locker is disabled , decrypt the payment method data
let card_details = if state.conf.locker.locker_enabled {
let card = payment_methods::cards::get_card_from_locker(
state,
&payment_method.customer_id,
&payment_method.merchant_id,
payment_method
.locker_id
.as_ref()
.unwrap_or(payment_method.get_id()),
)
.await?
.get_card();
payment_methods::transformers::get_card_detail(&payment_method, card)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card details")?
} else {
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account.clone(),
key_store,
None,
);
payment_methods::cards::PmCards {
state,
provider: platform.get_provider(),
}
.get_card_details_without_locker_fallback(&payment_method)
.await?
};
Some(MandateCardDetails::from(card_details).into_inner())
} else {
None
};
let payment_method_type = payment_method
.get_payment_method_subtype()
.map(|pmt| pmt.to_string());
let user_agent = mandate.get_user_agent_extended().unwrap_or_default();
Ok(Self {
mandate_id: mandate.mandate_id,
customer_acceptance: Some(api::payments::CustomerAcceptance {
acceptance_type: if mandate.customer_ip_address.is_some() {
api::payments::AcceptanceType::Online
} else {
api::payments::AcceptanceType::Offline
},
accepted_at: mandate.customer_accepted_at,
online: Some(api::payments::OnlineMandate {
ip_address: mandate.customer_ip_address,
user_agent,
}),
}),
card,
status: mandate.mandate_status,
payment_method: pm.to_string(),
payment_method_type,
payment_method_id: mandate.payment_method_id,
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl MandateResponseExt for MandateResponse {
async fn from_db_mandate(
state: &SessionState,
key_store: domain::MerchantKeyStore,
mandate: storage::Mandate,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<Self> {
todo!()
}
}
#[cfg(feature = "v1")]
impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails {
fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self {
mandates::MandateCardDetails {
last4_digits: card_details_from_locker.last4_digits,
card_exp_month: card_details_from_locker.expiry_month.clone(),
card_exp_year: card_details_from_locker.expiry_year.clone(),
card_holder_name: card_details_from_locker.card_holder_name,
card_token: card_details_from_locker.card_token,
scheme: card_details_from_locker.scheme,
issuer_country: card_details_from_locker.issuer_country,
card_fingerprint: card_details_from_locker.card_fingerprint,
card_isin: card_details_from_locker.card_isin,
card_issuer: card_details_from_locker.card_issuer,
card_network: card_details_from_locker.card_network,
card_type: card_details_from_locker.card_type,
nick_name: card_details_from_locker.nick_name,
}
.into()
}
}
#[cfg(feature = "v2")]
impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails {
fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self {
mandates::MandateCardDetails {
last4_digits: card_details_from_locker.last4_digits,
card_exp_month: card_details_from_locker.expiry_month.clone(),
card_exp_year: card_details_from_locker.expiry_year.clone(),
card_holder_name: card_details_from_locker.card_holder_name,
card_token: None,
scheme: None,
issuer_country: card_details_from_locker
.issuer_country
.map(|country| country.to_string()),
card_fingerprint: card_details_from_locker.card_fingerprint,
card_isin: card_details_from_locker.card_isin,
card_issuer: card_details_from_locker.card_issuer,
card_network: card_details_from_locker.card_network,
card_type: card_details_from_locker
.card_type
.as_ref()
.map(|c| c.to_string()),
nick_name: card_details_from_locker.nick_name,
}
.into()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/refunds_v2.rs | crates/router/src/types/api/refunds_v2.rs | pub use hyperswitch_interfaces::api::refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/connector_onboarding.rs | crates/router/src/types/api/connector_onboarding.rs | pub mod paypal;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/fraud_check.rs | crates/router/src/types/api/fraud_check.rs | use std::str::FromStr;
use api_models::enums;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::fraud_check::{
Checkout, Fulfillment, RecordReturn, Sale, Transaction,
};
pub use hyperswitch_interfaces::api::fraud_check::{
FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale,
FraudCheckTransaction,
};
pub use super::fraud_check_v2::{
FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2,
FraudCheckTransactionV2, FraudCheckV2,
};
use super::{ConnectorData, SessionConnectorDatas};
use crate::{
connector,
core::{errors, payments::ActionType},
services::connector_integration_interface::ConnectorEnum,
};
#[derive(Clone)]
pub struct FraudCheckConnectorData {
pub connector: ConnectorEnum,
pub connector_name: enums::FrmConnectors,
}
pub enum ConnectorCallType {
PreDetermined(ConnectorRoutingData),
Retryable(Vec<ConnectorRoutingData>),
SessionMultiple(SessionConnectorDatas),
}
#[derive(Clone)]
pub struct ConnectorRoutingData {
pub connector_data: ConnectorData,
pub network: Option<common_enums::CardNetwork>,
// action_type is used for mandates currently
pub action_type: Option<ActionType>,
}
impl FraudCheckConnectorData {
pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector_name = enums::FrmConnectors::from_str(name)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| {
format!("unable to parse connector: {:?}", name.to_string())
})?;
let connector = Self::convert_connector(connector_name)?;
Ok(Self {
connector,
connector_name,
})
}
fn convert_connector(
connector_name: enums::FrmConnectors,
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match connector_name {
enums::FrmConnectors::Signifyd => {
Ok(ConnectorEnum::Old(Box::new(&connector::Signifyd)))
}
enums::FrmConnectors::Riskified => {
Ok(ConnectorEnum::Old(Box::new(connector::Riskified::new())))
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/payments_v2.rs | crates/router/src/types/api/payments_v2.rs | pub use hyperswitch_interfaces::api::payments_v2::{
ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2,
PaymentAuthorizeV2, PaymentCaptureV2, PaymentExtendAuthorizationV2,
PaymentIncrementalAuthorizationV2, PaymentPostCaptureVoidV2, PaymentPostSessionTokensV2,
PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2,
PaymentUpdateMetadataV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2,
PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/payouts_v2.rs | crates/router/src/types/api/payouts_v2.rs | pub use api_models::payouts::{
AchBankTransfer, BacsBankTransfer, Bank as BankPayout, CardPayout, PayoutActionRequest,
PayoutAttemptResponse, PayoutCreateRequest, PayoutCreateResponse, PayoutListConstraints,
PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, PayoutMethodData,
PayoutRequest, PayoutRetrieveBody, PayoutRetrieveRequest, PixBankTransfer, SepaBankTransfer,
Wallet as WalletPayout,
};
pub use hyperswitch_domain_models::router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync,
};
pub use hyperswitch_interfaces::api::payouts_v2::{
PayoutCancelV2, PayoutCreateV2, PayoutEligibilityV2, PayoutFulfillV2, PayoutQuoteV2,
PayoutRecipientAccountV2, PayoutRecipientV2, PayoutSyncV2,
};
use crate::types::api as api_types;
pub trait PayoutsV2:
api_types::ConnectorCommon
+ PayoutCancelV2
+ PayoutCreateV2
+ PayoutEligibilityV2
+ PayoutFulfillV2
+ PayoutQuoteV2
+ PayoutRecipientV2
+ PayoutSyncV2
+ PayoutRecipientAccountV2
{
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/refunds.rs | crates/router/src/types/api/refunds.rs | #[cfg(feature = "v1")]
pub use api_models::refunds::RefundRequest;
pub use api_models::refunds::{
RefundListRequest, RefundListResponse, RefundResponse, RefundStatus, RefundType,
RefundUpdateRequest, RefundsRetrieveBody, RefundsRetrieveRequest,
};
#[cfg(feature = "v2")]
pub use api_models::refunds::{RefundMetadataUpdateRequest, RefundsCreateRequest};
pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync};
pub use hyperswitch_interfaces::api::refunds::{Refund, RefundExecute, RefundSync};
use crate::types::{storage::enums as storage_enums, transformers::ForeignFrom};
impl ForeignFrom<storage_enums::RefundStatus> for RefundStatus {
fn foreign_from(status: storage_enums::RefundStatus) -> Self {
match status {
storage_enums::RefundStatus::Failure
| storage_enums::RefundStatus::TransactionFailure => Self::Failed,
storage_enums::RefundStatus::ManualReview => Self::Review,
storage_enums::RefundStatus::Pending => Self::Pending,
storage_enums::RefundStatus::Success => Self::Succeeded,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/routing.rs | crates/router/src/types/api/routing.rs | pub use api_models::{
enums as api_enums,
routing::{
ConnectorVolumeSplit, RoutableChoiceKind, RoutableConnectorChoice, RoutingAlgorithmKind,
RoutingAlgorithmRef, RoutingConfigRequest, RoutingDictionary, RoutingDictionaryRecord,
StaticRoutingAlgorithm, StraightThroughAlgorithm,
},
};
use super::types::api as api_oss;
pub struct SessionRoutingChoice {
pub connector: api_oss::ConnectorData,
pub payment_method_type: api_enums::PaymentMethodType,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorVolumeSplitV0 {
pub connector: RoutableConnectorChoice,
pub split: u8,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RoutingAlgorithmV0 {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplitV0>),
Custom { timestamp: i64 },
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FrmRoutingAlgorithm {
pub data: String,
#[serde(rename = "type")]
pub algorithm_type: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/webhook_events.rs | crates/router/src/types/api/webhook_events.rs | pub use api_models::webhook_events::{
EventListConstraints, EventListConstraintsInternal, EventListItemResponse,
EventListRequestInternal, EventRetrieveResponse, OutgoingWebhookRequestContent,
OutgoingWebhookResponseContent, TotalEventsResponse, WebhookDeliveryAttemptListRequestInternal,
WebhookDeliveryRetryRequestInternal,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/customers.rs | crates/router/src/types/api/customers.rs | use api_models::customers;
pub use api_models::customers::{
CustomerDeleteResponse, CustomerListRequest, CustomerListRequestWithConstraints,
CustomerListResponse, CustomerRequest, CustomerUpdateRequest, CustomerUpdateRequestInternal,
};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::customer;
use serde::Serialize;
#[cfg(feature = "v1")]
use super::payments;
use crate::{
newtype,
types::{domain, ForeignFrom},
};
newtype!(
pub CustomerResponse = customers::CustomerResponse,
derives = (Debug, Clone, Serialize)
);
impl common_utils::events::ApiEventMetric for CustomerResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
self.0.get_api_event_type()
}
}
#[cfg(feature = "v1")]
impl ForeignFrom<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResponse {
fn foreign_from((cust, address): (domain::Customer, Option<payments::AddressDetails>)) -> Self {
customers::CustomerResponse {
customer_id: cust.customer_id,
name: cust.name,
email: cust.email,
phone: cust.phone,
phone_country_code: cust.phone_country_code,
description: cust.description,
created_at: cust.created_at,
metadata: cust.metadata,
address,
default_payment_method_id: cust.default_payment_method_id,
tax_registration_id: cust.tax_registration_id,
}
.into()
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<customer::Customer> for CustomerResponse {
fn foreign_from(cust: domain::Customer) -> Self {
customers::CustomerResponse {
id: cust.id,
merchant_reference_id: cust.merchant_reference_id,
connector_customer_ids: cust.connector_customer,
name: cust.name,
email: cust.email,
phone: cust.phone,
phone_country_code: cust.phone_country_code,
description: cust.description,
created_at: cust.created_at,
metadata: cust.metadata,
default_billing_address: None,
default_shipping_address: None,
default_payment_method_id: cust.default_payment_method_id,
tax_registration_id: cust.tax_registration_id,
}
.into()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/poll.rs | crates/router/src/types/api/poll.rs | #[derive(Default, Debug, serde::Deserialize, serde::Serialize)]
pub struct PollId {
pub poll_id: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/disputes.rs | crates/router/src/types/api/disputes.rs | pub use hyperswitch_interfaces::{
api::disputes::{
AcceptDispute, DefendDispute, Dispute, DisputeSync, FetchDisputes, SubmitEvidence,
},
disputes::DisputePayload,
};
use masking::{Deserialize, Serialize};
use crate::types;
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct DisputeId {
pub dispute_id: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DisputeFetchQueryData {
pub fetch_from: String,
pub fetch_till: String,
}
pub use hyperswitch_domain_models::router_flow_types::dispute::{
Accept, Defend, Dsync, Evidence, Fetch,
};
pub use super::disputes_v2::{
AcceptDisputeV2, DefendDisputeV2, DisputeSyncV2, DisputeV2, FetchDisputesV2, SubmitEvidenceV2,
};
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct DisputeEvidence {
pub cancellation_policy: Option<String>,
pub customer_communication: Option<String>,
pub customer_signature: Option<String>,
pub receipt: Option<String>,
pub refund_policy: Option<String>,
pub service_documentation: Option<String>,
pub shipping_documentation: Option<String>,
pub invoice_showing_distinct_transactions: Option<String>,
pub recurring_transaction_agreement: Option<String>,
pub uncategorized_file: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct AttachEvidenceRequest {
pub create_file_request: types::api::CreateFileRequest,
pub evidence_type: EvidenceType,
}
#[derive(Debug, serde::Deserialize, strum::Display, strum::EnumString, Clone, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum EvidenceType {
CancellationPolicy,
CustomerCommunication,
CustomerSignature,
Receipt,
RefundPolicy,
ServiceDocumentation,
ShippingDocumentation,
InvoiceShowingDistinctTransactions,
RecurringTransactionAgreement,
UncategorizedFile,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ProcessDisputePTData {
pub connector_name: String,
pub dispute_payload: types::DisputeSyncResponse,
pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct DisputeListPTData {
pub connector_name: String,
pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_id: common_utils::id_type::ProfileId,
pub created_from: time::PrimitiveDateTime,
pub created_till: time::PrimitiveDateTime,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/feature_matrix.rs | crates/router/src/types/api/feature_matrix.rs | use std::str::FromStr;
use error_stack::{report, ResultExt};
use crate::{
connector,
core::errors::{self, CustomResult},
services::connector_integration_interface::ConnectorEnum,
types::api::enums,
};
#[derive(Clone)]
pub struct FeatureMatrixConnectorData {}
impl FeatureMatrixConnectorData {
pub fn convert_connector(
connector_name: &str,
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match enums::Connector::from_str(connector_name) {
Ok(name) => match name {
enums::Connector::Aci => Ok(ConnectorEnum::Old(Box::new(connector::Aci::new()))),
enums::Connector::Adyen => {
Ok(ConnectorEnum::Old(Box::new(connector::Adyen::new())))
}
enums::Connector::Affirm => {
Ok(ConnectorEnum::Old(Box::new(connector::Affirm::new())))
}
enums::Connector::Adyenplatform => Ok(ConnectorEnum::Old(Box::new(
connector::Adyenplatform::new(),
))),
enums::Connector::Airwallex => {
Ok(ConnectorEnum::Old(Box::new(connector::Airwallex::new())))
}
enums::Connector::Amazonpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Amazonpay::new())))
}
enums::Connector::Archipel => {
Ok(ConnectorEnum::Old(Box::new(connector::Archipel::new())))
}
enums::Connector::Authipay => {
Ok(ConnectorEnum::Old(Box::new(connector::Authipay::new())))
}
enums::Connector::Authorizedotnet => Ok(ConnectorEnum::Old(Box::new(
connector::Authorizedotnet::new(),
))),
enums::Connector::Bambora => {
Ok(ConnectorEnum::Old(Box::new(connector::Bambora::new())))
}
enums::Connector::Bamboraapac => {
Ok(ConnectorEnum::Old(Box::new(connector::Bamboraapac::new())))
}
enums::Connector::Bankofamerica => Ok(ConnectorEnum::Old(Box::new(
connector::Bankofamerica::new(),
))),
enums::Connector::Barclaycard => {
Ok(ConnectorEnum::Old(Box::new(connector::Barclaycard::new())))
}
enums::Connector::Billwerk => {
Ok(ConnectorEnum::Old(Box::new(connector::Billwerk::new())))
}
enums::Connector::Bitpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Bitpay::new())))
}
enums::Connector::Blackhawknetwork => Ok(ConnectorEnum::Old(Box::new(
connector::Blackhawknetwork::new(),
))),
enums::Connector::Bluesnap => {
Ok(ConnectorEnum::Old(Box::new(connector::Bluesnap::new())))
}
enums::Connector::Calida => {
Ok(ConnectorEnum::Old(Box::new(connector::Calida::new())))
}
enums::Connector::Boku => Ok(ConnectorEnum::Old(Box::new(connector::Boku::new()))),
enums::Connector::Braintree => {
Ok(ConnectorEnum::Old(Box::new(connector::Braintree::new())))
}
enums::Connector::Breadpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Breadpay::new())))
}
enums::Connector::Cashtocode => {
Ok(ConnectorEnum::Old(Box::new(connector::Cashtocode::new())))
}
enums::Connector::Celero => {
Ok(ConnectorEnum::Old(Box::new(connector::Celero::new())))
}
enums::Connector::Chargebee => {
Ok(ConnectorEnum::Old(Box::new(connector::Chargebee::new())))
}
enums::Connector::Checkbook => {
Ok(ConnectorEnum::Old(Box::new(connector::Checkbook::new())))
}
enums::Connector::Checkout => {
Ok(ConnectorEnum::Old(Box::new(connector::Checkout::new())))
}
enums::Connector::Coinbase => {
Ok(ConnectorEnum::Old(Box::new(connector::Coinbase::new())))
}
enums::Connector::Coingate => {
Ok(ConnectorEnum::Old(Box::new(connector::Coingate::new())))
}
enums::Connector::Cryptopay => {
Ok(ConnectorEnum::Old(Box::new(connector::Cryptopay::new())))
}
enums::Connector::CtpMastercard => {
Ok(ConnectorEnum::Old(Box::new(&connector::CtpMastercard)))
}
enums::Connector::Custombilling => Ok(ConnectorEnum::Old(Box::new(
connector::Custombilling::new(),
))),
enums::Connector::CtpVisa => Ok(ConnectorEnum::Old(Box::new(
connector::UnifiedAuthenticationService::new(),
))),
enums::Connector::Cybersource => {
Ok(ConnectorEnum::Old(Box::new(connector::Cybersource::new())))
}
enums::Connector::Datatrans => {
Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new())))
}
enums::Connector::Deutschebank => {
Ok(ConnectorEnum::Old(Box::new(connector::Deutschebank::new())))
}
enums::Connector::Digitalvirgo => {
Ok(ConnectorEnum::Old(Box::new(connector::Digitalvirgo::new())))
}
enums::Connector::Dlocal => {
Ok(ConnectorEnum::Old(Box::new(connector::Dlocal::new())))
}
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector1 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<1>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector2 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<2>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector3 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<3>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector4 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<4>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector5 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<5>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector6 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<6>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector7 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<7>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyBillingConnector => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<8>::new(),
))),
enums::Connector::Dwolla => {
Ok(ConnectorEnum::Old(Box::new(connector::Dwolla::new())))
}
enums::Connector::Ebanx => {
Ok(ConnectorEnum::Old(Box::new(connector::Ebanx::new())))
}
enums::Connector::Elavon => {
Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new())))
}
enums::Connector::Facilitapay => {
Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay::new())))
}
enums::Connector::Finix => {
Ok(ConnectorEnum::Old(Box::new(connector::Finix::new())))
}
enums::Connector::Fiserv => {
Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new())))
}
enums::Connector::Fiservemea => {
Ok(ConnectorEnum::Old(Box::new(connector::Fiservemea::new())))
}
enums::Connector::Fiuu => Ok(ConnectorEnum::Old(Box::new(connector::Fiuu::new()))),
enums::Connector::Forte => {
Ok(ConnectorEnum::Old(Box::new(connector::Forte::new())))
}
enums::Connector::Flexiti => {
Ok(ConnectorEnum::Old(Box::new(connector::Flexiti::new())))
}
enums::Connector::Getnet => {
Ok(ConnectorEnum::Old(Box::new(connector::Getnet::new())))
}
enums::Connector::Gigadat => {
Ok(ConnectorEnum::Old(Box::new(connector::Gigadat::new())))
}
enums::Connector::Globalpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Globalpay::new())))
}
enums::Connector::Globepay => {
Ok(ConnectorEnum::Old(Box::new(connector::Globepay::new())))
}
enums::Connector::Gocardless => {
Ok(ConnectorEnum::Old(Box::new(connector::Gocardless::new())))
}
enums::Connector::Hipay => {
Ok(ConnectorEnum::Old(Box::new(connector::Hipay::new())))
}
enums::Connector::Helcim => {
Ok(ConnectorEnum::Old(Box::new(connector::Helcim::new())))
}
enums::Connector::HyperswitchVault => {
Ok(ConnectorEnum::Old(Box::new(&connector::HyperswitchVault)))
}
enums::Connector::Iatapay => {
Ok(ConnectorEnum::Old(Box::new(connector::Iatapay::new())))
}
enums::Connector::Inespay => {
Ok(ConnectorEnum::Old(Box::new(connector::Inespay::new())))
}
enums::Connector::Itaubank => {
Ok(ConnectorEnum::Old(Box::new(connector::Itaubank::new())))
}
enums::Connector::Jpmorgan => {
Ok(ConnectorEnum::Old(Box::new(connector::Jpmorgan::new())))
}
enums::Connector::Juspaythreedsserver => Ok(ConnectorEnum::Old(Box::new(
connector::Juspaythreedsserver::new(),
))),
enums::Connector::Klarna => {
Ok(ConnectorEnum::Old(Box::new(connector::Klarna::new())))
}
enums::Connector::Loonio => {
Ok(ConnectorEnum::Old(Box::new(connector::Loonio::new())))
}
enums::Connector::Mollie => {
// enums::Connector::Moneris => Ok(ConnectorEnum::Old(Box::new(connector::Moneris))),
Ok(ConnectorEnum::Old(Box::new(connector::Mollie::new())))
}
enums::Connector::Moneris => {
Ok(ConnectorEnum::Old(Box::new(connector::Moneris::new())))
}
enums::Connector::Nexixpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Nexixpay::new())))
}
enums::Connector::Nmi => Ok(ConnectorEnum::Old(Box::new(connector::Nmi::new()))),
enums::Connector::Nomupay => {
Ok(ConnectorEnum::Old(Box::new(connector::Nomupay::new())))
}
enums::Connector::Noon => Ok(ConnectorEnum::Old(Box::new(connector::Noon::new()))),
enums::Connector::Nordea => {
Ok(ConnectorEnum::Old(Box::new(connector::Nordea::new())))
}
enums::Connector::Novalnet => {
Ok(ConnectorEnum::Old(Box::new(connector::Novalnet::new())))
}
enums::Connector::Nuvei => {
Ok(ConnectorEnum::Old(Box::new(connector::Nuvei::new())))
}
enums::Connector::Opennode => {
Ok(ConnectorEnum::Old(Box::new(connector::Opennode::new())))
}
enums::Connector::Phonepe => {
Ok(ConnectorEnum::Old(Box::new(connector::Phonepe::new())))
}
enums::Connector::Paybox => {
Ok(ConnectorEnum::Old(Box::new(connector::Paybox::new())))
}
enums::Connector::Paytm => {
Ok(ConnectorEnum::Old(Box::new(connector::Paytm::new())))
}
// "payeezy" => Ok(ConnectorIntegrationEnum::Old(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage
// enums::Connector::Payload => {
// Ok(ConnectorEnum::Old(Box::new(connector::Paybload::new())))
// }
enums::Connector::Payload => {
Ok(ConnectorEnum::Old(Box::new(connector::Payload::new())))
}
enums::Connector::Payjustnow => {
Ok(ConnectorEnum::Old(Box::new(connector::Payjustnow::new())))
}
enums::Connector::Payjustnowinstore => Ok(ConnectorEnum::Old(Box::new(
connector::Payjustnowinstore::new(),
))),
enums::Connector::Payme => {
Ok(ConnectorEnum::Old(Box::new(connector::Payme::new())))
}
enums::Connector::Payone => {
Ok(ConnectorEnum::Old(Box::new(connector::Payone::new())))
}
enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))),
enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new(
connector::Peachpayments::new(),
))),
enums::Connector::Placetopay => {
Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new())))
}
enums::Connector::Powertranz => {
Ok(ConnectorEnum::Old(Box::new(connector::Powertranz::new())))
}
enums::Connector::Prophetpay => {
Ok(ConnectorEnum::Old(Box::new(&connector::Prophetpay)))
}
enums::Connector::Razorpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Razorpay::new())))
}
enums::Connector::Rapyd => {
Ok(ConnectorEnum::Old(Box::new(connector::Rapyd::new())))
}
enums::Connector::Recurly => {
Ok(ConnectorEnum::New(Box::new(connector::Recurly::new())))
}
enums::Connector::Redsys => {
Ok(ConnectorEnum::Old(Box::new(connector::Redsys::new())))
}
enums::Connector::Santander => {
Ok(ConnectorEnum::Old(Box::new(connector::Santander::new())))
}
enums::Connector::Shift4 => {
Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new())))
}
enums::Connector::Square => Ok(ConnectorEnum::Old(Box::new(&connector::Square))),
enums::Connector::Stax => Ok(ConnectorEnum::Old(Box::new(&connector::Stax))),
enums::Connector::Stripe => {
Ok(ConnectorEnum::Old(Box::new(connector::Stripe::new())))
}
enums::Connector::Stripebilling => Ok(ConnectorEnum::Old(Box::new(
connector::Stripebilling::new(),
))),
enums::Connector::Wise => Ok(ConnectorEnum::Old(Box::new(connector::Wise::new()))),
enums::Connector::Worldline => {
Ok(ConnectorEnum::Old(Box::new(&connector::Worldline)))
}
enums::Connector::Worldpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Worldpay::new())))
}
enums::Connector::Worldpayvantiv => Ok(ConnectorEnum::Old(Box::new(
connector::Worldpayvantiv::new(),
))),
enums::Connector::Worldpayxml => {
Ok(ConnectorEnum::Old(Box::new(connector::Worldpayxml::new())))
}
enums::Connector::Xendit => {
Ok(ConnectorEnum::Old(Box::new(connector::Xendit::new())))
}
enums::Connector::Mifinity => {
Ok(ConnectorEnum::Old(Box::new(connector::Mifinity::new())))
}
enums::Connector::Multisafepay => {
Ok(ConnectorEnum::Old(Box::new(connector::Multisafepay::new())))
}
enums::Connector::Netcetera => {
Ok(ConnectorEnum::Old(Box::new(&connector::Netcetera)))
}
enums::Connector::Nexinets => {
Ok(ConnectorEnum::Old(Box::new(&connector::Nexinets)))
}
// enums::Connector::Nexixpay => {
// Ok(ConnectorEnum::Old(Box::new(&connector::Nexixpay)))
// }
enums::Connector::Paypal => {
Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new())))
}
enums::Connector::Paysafe => {
Ok(ConnectorEnum::Old(Box::new(connector::Paysafe::new())))
}
enums::Connector::Paystack => {
Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new())))
}
// enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))),
enums::Connector::Tesouro => {
Ok(ConnectorEnum::Old(Box::new(connector::Tesouro::new())))
}
enums::Connector::Tokenex => Ok(ConnectorEnum::Old(Box::new(&connector::Tokenex))),
enums::Connector::Tokenio => {
Ok(ConnectorEnum::Old(Box::new(connector::Tokenio::new())))
}
enums::Connector::Trustpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new())))
}
enums::Connector::Trustpayments => Ok(ConnectorEnum::Old(Box::new(
connector::Trustpayments::new(),
))),
enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(connector::Tsys::new()))),
// enums::Connector::UnifiedAuthenticationService => Ok(ConnectorEnum::Old(Box::new(
// connector::UnifiedAuthenticationService,
// ))),
enums::Connector::Vgs => Ok(ConnectorEnum::Old(Box::new(&connector::Vgs))),
enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))),
enums::Connector::Wellsfargo => {
Ok(ConnectorEnum::Old(Box::new(connector::Wellsfargo::new())))
}
// enums::Connector::Wellsfargopayout => {
// Ok(Box::new(connector::Wellsfargopayout::new()))
// }
enums::Connector::Zen => Ok(ConnectorEnum::Old(Box::new(&connector::Zen))),
enums::Connector::Zsl => Ok(ConnectorEnum::Old(Box::new(&connector::Zsl))),
enums::Connector::Plaid => {
Ok(ConnectorEnum::Old(Box::new(connector::Plaid::new())))
}
enums::Connector::Signifyd => {
Ok(ConnectorEnum::Old(Box::new(&connector::Signifyd)))
}
enums::Connector::Silverflow => {
Ok(ConnectorEnum::Old(Box::new(connector::Silverflow::new())))
}
enums::Connector::Zift => Ok(ConnectorEnum::Old(Box::new(connector::Zift::new()))),
enums::Connector::Riskified => {
Ok(ConnectorEnum::Old(Box::new(connector::Riskified::new())))
}
enums::Connector::Gpayments => {
Ok(ConnectorEnum::Old(Box::new(connector::Gpayments::new())))
}
enums::Connector::Threedsecureio => {
Ok(ConnectorEnum::Old(Box::new(&connector::Threedsecureio)))
}
enums::Connector::Taxjar => {
Ok(ConnectorEnum::Old(Box::new(connector::Taxjar::new())))
}
enums::Connector::Cardinal => {
Err(report!(errors::ConnectorError::InvalidConnectorName)
.attach_printable(format!("invalid connector name: {connector_name}")))
.change_context(errors::ApiErrorResponse::InternalServerError)
}
},
Err(_) => Err(report!(errors::ConnectorError::InvalidConnectorName)
.attach_printable(format!("invalid connector name: {connector_name}")))
.change_context(errors::ApiErrorResponse::InternalServerError),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/payment_link.rs | crates/router/src/types/api/payment_link.rs | pub use api_models::payments::RetrievePaymentLinkResponse;
use crate::{
consts::DEFAULT_SESSION_EXPIRY,
core::{errors::RouterResult, payment_link},
types::storage::{self},
};
#[async_trait::async_trait]
pub(crate) trait PaymentLinkResponseExt: Sized {
async fn from_db_payment_link(payment_link: storage::PaymentLink) -> RouterResult<Self>;
}
#[async_trait::async_trait]
impl PaymentLinkResponseExt for RetrievePaymentLinkResponse {
async fn from_db_payment_link(payment_link: storage::PaymentLink) -> RouterResult<Self> {
let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| {
payment_link
.created_at
.saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY))
});
let status = payment_link::check_payment_link_status(session_expiry);
Ok(Self {
link_to_pay: payment_link.link_to_pay,
payment_link_id: payment_link.payment_link_id,
amount: payment_link.amount,
description: payment_link.description,
created_at: payment_link.created_at,
merchant_id: payment_link.merchant_id,
expiry: payment_link.fulfilment_time,
currency: payment_link.currency,
status,
secure_link: payment_link.secure_link,
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/ephemeral_key.rs | crates/router/src/types/api/ephemeral_key.rs | pub use api_models::ephemeral_key::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/enums.rs | crates/router/src/types/api/enums.rs | pub use api_models::enums::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/webhooks.rs | crates/router/src/types/api/webhooks.rs | pub use api_models::webhooks::{
AuthenticationIdType, IncomingWebhookDetails, IncomingWebhookEvent, MerchantWebhookConfig,
ObjectReferenceId, OutgoingWebhook, OutgoingWebhookContent, WebhookFlow,
};
pub use hyperswitch_interfaces::webhooks::{IncomingWebhook, IncomingWebhookRequestDetails};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/admin.rs | crates/router/src/types/api/admin.rs | use std::collections::HashMap;
#[cfg(feature = "v2")]
pub use api_models::admin;
pub use api_models::{
admin::{
MaskedHeaders, MerchantAccountCreate, MerchantAccountDeleteResponse,
MerchantAccountResponse, MerchantAccountUpdate, MerchantConnectorCreate,
MerchantConnectorDeleteResponse, MerchantConnectorDetails, MerchantConnectorDetailsWrap,
MerchantConnectorId, MerchantConnectorResponse, MerchantDetails, MerchantId,
PaymentMethodsEnabled, ProfileCreate, ProfileResponse, ProfileUpdate, ToggleAllKVRequest,
ToggleAllKVResponse, ToggleKVRequest, ToggleKVResponse, WebhookDetails,
},
organization::{
OrganizationCreateRequest, OrganizationId, OrganizationResponse, OrganizationUpdateRequest,
},
};
use common_utils::{ext_traits::ValueExt, types::keymanager as km_types};
use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge};
use error_stack::ResultExt;
use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
use masking::{ExposeInterface, PeekInterface, Secret};
use crate::{
consts,
core::errors,
routes::SessionState,
types::{
domain::{
self,
types::{self as domain_types, AsyncLift},
},
transformers::{ForeignInto, ForeignTryFrom},
ForeignFrom,
},
utils,
};
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ProfileAcquirerConfigs {
pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
pub profile_id: common_utils::id_type::ProfileId,
}
impl From<ProfileAcquirerConfigs>
for Option<Vec<api_models::profile_acquirer::ProfileAcquirerResponse>>
{
fn from(item: ProfileAcquirerConfigs) -> Self {
item.acquirer_config_map.map(|config_map_val| {
let mut vec: Vec<_> = config_map_val.0.into_iter().collect();
vec.sort_by_key(|k| k.0.clone());
vec.into_iter()
.map(|(profile_acquirer_id, acquirer_config)| {
api_models::profile_acquirer::ProfileAcquirerResponse::from((
profile_acquirer_id,
&item.profile_id,
&acquirer_config,
))
})
.collect::<Vec<api_models::profile_acquirer::ProfileAcquirerResponse>>()
})
}
}
impl ForeignFrom<diesel_models::organization::Organization> for OrganizationResponse {
fn foreign_from(org: diesel_models::organization::Organization) -> Self {
Self {
#[cfg(feature = "v2")]
id: org.get_organization_id(),
#[cfg(feature = "v1")]
organization_id: org.get_organization_id(),
organization_name: org.get_organization_name(),
organization_details: org.organization_details,
metadata: org.metadata,
modified_at: org.modified_at,
created_at: org.created_at,
organization_type: org.organization_type,
}
}
}
#[cfg(feature = "v1")]
impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse {
type Error = error_stack::Report<errors::ParsingError>;
fn foreign_try_from(item: domain::MerchantAccount) -> Result<Self, Self::Error> {
let merchant_id = item.get_id().to_owned();
let primary_business_details: Vec<api_models::admin::PrimaryBusinessDetails> = item
.primary_business_details
.parse_value("primary_business_details")?;
let pm_collect_link_config: Option<api_models::admin::BusinessCollectLinkConfig> = item
.pm_collect_link_config
.map(|config| config.parse_value("pm_collect_link_config"))
.transpose()?;
Ok(Self {
merchant_id,
merchant_name: item.merchant_name,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_details: item.merchant_details,
webhook_details: item.webhook_details.clone().map(ForeignInto::foreign_into),
routing_algorithm: item.routing_algorithm,
sub_merchants_enabled: item.sub_merchants_enabled,
parent_merchant_id: item.parent_merchant_id,
publishable_key: Some(item.publishable_key),
metadata: item.metadata,
locker_id: item.locker_id,
primary_business_details,
frm_routing_algorithm: item.frm_routing_algorithm,
#[cfg(feature = "payouts")]
payout_routing_algorithm: item.payout_routing_algorithm,
organization_id: item.organization_id,
is_recon_enabled: item.is_recon_enabled,
default_profile: item.default_profile,
recon_status: item.recon_status,
pm_collect_link_config,
product_type: item.product_type,
merchant_account_type: item.merchant_account_type,
})
}
}
#[cfg(feature = "v2")]
impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse {
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(item: domain::MerchantAccount) -> Result<Self, Self::Error> {
use common_utils::ext_traits::OptionExt;
let id = item.get_id().to_owned();
let merchant_name = item
.merchant_name
.get_required_value("merchant_name")?
.into_inner();
Ok(Self {
id,
merchant_name,
merchant_details: item.merchant_details,
publishable_key: item.publishable_key,
metadata: item.metadata,
organization_id: item.organization_id,
recon_status: item.recon_status,
product_type: item.product_type,
})
}
}
#[cfg(feature = "v1")]
impl ForeignTryFrom<domain::Profile> for ProfileResponse {
type Error = error_stack::Report<errors::ParsingError>;
fn foreign_try_from(item: domain::Profile) -> Result<Self, Self::Error> {
let profile_id = item.get_id().to_owned();
let outgoing_webhook_custom_http_headers = item
.outgoing_webhook_custom_http_headers
.map(|headers| {
headers
.into_inner()
.expose()
.parse_value::<HashMap<String, Secret<String>>>(
"HashMap<String, Secret<String>>",
)
})
.transpose()?;
let masked_outgoing_webhook_custom_http_headers =
outgoing_webhook_custom_http_headers.map(MaskedHeaders::from_headers);
let card_testing_guard_config = item
.card_testing_guard_config
.or(Some(CardTestingGuardConfig::default()));
let (is_external_vault_enabled, external_vault_connector_details) =
item.external_vault_details.into();
Ok(Self {
merchant_id: item.merchant_id,
profile_id: profile_id.clone(),
profile_name: item.profile_name,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
webhook_details: item.webhook_details.map(ForeignInto::foreign_into),
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
intent_fulfillment_time: item.intent_fulfillment_time,
frm_routing_algorithm: item.frm_routing_algorithm,
#[cfg(feature = "payouts")]
payout_routing_algorithm: item.payout_routing_algorithm,
applepay_verified_domains: item.applepay_verified_domains,
payment_link_config: item.payment_link_config.map(ForeignInto::foreign_into),
session_expiry: item.session_expiry,
authentication_connector_details: item
.authentication_connector_details
.map(ForeignInto::foreign_into),
payout_link_config: item.payout_link_config.map(ForeignInto::foreign_into),
use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing,
extended_card_info_config: item
.extended_card_info_config
.map(|config| config.expose().parse_value("ExtendedCardInfoConfig"))
.transpose()?,
collect_shipping_details_from_wallet_connector: item
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: item
.collect_billing_details_from_wallet_connector,
always_collect_billing_details_from_wallet_connector: item
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: item
.always_collect_shipping_details_from_wallet_connector,
is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers: masked_outgoing_webhook_custom_http_headers,
tax_connector_id: item.tax_connector_id,
is_tax_connector_enabled: item.is_tax_connector_enabled,
is_network_tokenization_enabled: item.is_network_tokenization_enabled,
is_auto_retries_enabled: item.is_auto_retries_enabled,
max_auto_retries_enabled: item.max_auto_retries_enabled,
always_request_extended_authorization: item.always_request_extended_authorization,
is_click_to_pay_enabled: item.is_click_to_pay_enabled,
authentication_product_ids: item.authentication_product_ids,
card_testing_guard_config: card_testing_guard_config.map(ForeignInto::foreign_into),
is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled,
force_3ds_challenge: item.force_3ds_challenge,
is_debit_routing_enabled: Some(item.is_debit_routing_enabled),
merchant_business_country: item.merchant_business_country,
is_pre_network_tokenization_enabled: item.is_pre_network_tokenization_enabled,
acquirer_configs: ProfileAcquirerConfigs {
acquirer_config_map: item.acquirer_config_map.clone(),
profile_id: profile_id.clone(),
}
.into(),
is_iframe_redirection_enabled: item.is_iframe_redirection_enabled,
merchant_category_code: item.merchant_category_code,
merchant_country_code: item.merchant_country_code,
dispute_polling_interval: item.dispute_polling_interval,
is_manual_retry_enabled: item.is_manual_retry_enabled,
always_enable_overcapture: item.always_enable_overcapture,
is_external_vault_enabled,
external_vault_connector_details: external_vault_connector_details
.map(ForeignFrom::foreign_from),
billing_processor_id: item.billing_processor_id,
is_l2_l3_enabled: Some(item.is_l2_l3_enabled),
})
}
}
#[cfg(feature = "v2")]
impl ForeignTryFrom<domain::Profile> for ProfileResponse {
type Error = error_stack::Report<errors::ParsingError>;
fn foreign_try_from(item: domain::Profile) -> Result<Self, Self::Error> {
let id = item.get_id().to_owned();
let outgoing_webhook_custom_http_headers = item
.outgoing_webhook_custom_http_headers
.map(|headers| {
headers
.into_inner()
.expose()
.parse_value::<HashMap<String, Secret<String>>>(
"HashMap<String, Secret<String>>",
)
})
.transpose()?;
let order_fulfillment_time = item
.order_fulfillment_time
.map(admin::OrderFulfillmentTime::try_new)
.transpose()
.change_context(errors::ParsingError::IntegerOverflow)?;
let masked_outgoing_webhook_custom_http_headers =
outgoing_webhook_custom_http_headers.map(MaskedHeaders::from_headers);
let card_testing_guard_config = item
.card_testing_guard_config
.or(Some(CardTestingGuardConfig::default()));
Ok(Self {
merchant_id: item.merchant_id,
id,
profile_name: item.profile_name,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
webhook_details: item.webhook_details.map(ForeignInto::foreign_into),
metadata: item.metadata,
applepay_verified_domains: item.applepay_verified_domains,
payment_link_config: item.payment_link_config.map(ForeignInto::foreign_into),
session_expiry: item.session_expiry,
authentication_connector_details: item
.authentication_connector_details
.map(ForeignInto::foreign_into),
payout_link_config: item.payout_link_config.map(ForeignInto::foreign_into),
use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing,
extended_card_info_config: item
.extended_card_info_config
.map(|config| config.expose().parse_value("ExtendedCardInfoConfig"))
.transpose()?,
collect_shipping_details_from_wallet_connector_if_required: item
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector_if_required: item
.collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: item
.always_collect_shipping_details_from_wallet_connector,
always_collect_billing_details_from_wallet_connector: item
.always_collect_billing_details_from_wallet_connector,
is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers: masked_outgoing_webhook_custom_http_headers,
order_fulfillment_time,
order_fulfillment_time_origin: item.order_fulfillment_time_origin,
should_collect_cvv_during_payment: item.should_collect_cvv_during_payment,
tax_connector_id: item.tax_connector_id,
is_tax_connector_enabled: item.is_tax_connector_enabled,
is_network_tokenization_enabled: item.is_network_tokenization_enabled,
is_click_to_pay_enabled: item.is_click_to_pay_enabled,
authentication_product_ids: item.authentication_product_ids,
card_testing_guard_config: card_testing_guard_config.map(ForeignInto::foreign_into),
is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled,
is_debit_routing_enabled: Some(item.is_debit_routing_enabled),
merchant_business_country: item.merchant_business_country,
is_iframe_redirection_enabled: item.is_iframe_redirection_enabled,
is_external_vault_enabled: item.is_external_vault_enabled,
is_l2_l3_enabled: None,
external_vault_connector_details: item
.external_vault_connector_details
.map(ForeignInto::foreign_into),
merchant_category_code: item.merchant_category_code,
merchant_country_code: item.merchant_country_code,
split_txns_enabled: item.split_txns_enabled,
revenue_recovery_retry_algorithm_type: item.revenue_recovery_retry_algorithm_type,
billing_processor_id: item.billing_processor_id,
})
}
}
#[cfg(feature = "v1")]
pub async fn create_profile_from_merchant_account(
state: &SessionState,
merchant_account: domain::MerchantAccount,
request: ProfileCreate,
key_store: &MerchantKeyStore,
) -> Result<domain::Profile, error_stack::Report<errors::ApiErrorResponse>> {
use common_utils::ext_traits::AsyncExt;
use diesel_models::business_profile::CardTestingGuardConfig;
use crate::core;
// Generate a unique profile id
let profile_id = common_utils::generate_profile_id_of_default_length();
let merchant_id = merchant_account.get_id().to_owned();
let current_time = common_utils::date_time::now();
let webhook_details = request.webhook_details.map(ForeignInto::foreign_into);
let payment_response_hash_key = request
.payment_response_hash_key
.or(merchant_account.payment_response_hash_key)
.unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64));
let payment_link_config = request.payment_link_config.map(ForeignInto::foreign_into);
let key_manager_state = state.into();
let outgoing_webhook_custom_http_headers = request
.outgoing_webhook_custom_http_headers
.async_map(|headers| {
core::payment_methods::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 = request
.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 = request
.card_testing_guard_config
.map(CardTestingGuardConfig::foreign_from)
.or(Some(CardTestingGuardConfig::default()));
Ok(domain::Profile::from(domain::ProfileSetter {
profile_id,
merchant_id,
profile_name: request.profile_name.unwrap_or("default".to_string()),
created_at: current_time,
modified_at: current_time,
return_url: request
.return_url
.map(|return_url| return_url.to_string())
.or(merchant_account.return_url),
enable_payment_response_hash: request
.enable_payment_response_hash
.unwrap_or(merchant_account.enable_payment_response_hash),
payment_response_hash_key: Some(payment_response_hash_key),
redirect_to_merchant_with_http_post: request
.redirect_to_merchant_with_http_post
.unwrap_or(merchant_account.redirect_to_merchant_with_http_post),
webhook_details: webhook_details.or(merchant_account.webhook_details),
metadata: request.metadata,
routing_algorithm: None,
intent_fulfillment_time: request
.intent_fulfillment_time
.map(i64::from)
.or(merchant_account.intent_fulfillment_time)
.or(Some(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME)),
frm_routing_algorithm: request
.frm_routing_algorithm
.or(merchant_account.frm_routing_algorithm),
#[cfg(feature = "payouts")]
payout_routing_algorithm: request
.payout_routing_algorithm
.or(merchant_account.payout_routing_algorithm),
#[cfg(not(feature = "payouts"))]
payout_routing_algorithm: None,
is_recon_enabled: merchant_account.is_recon_enabled,
applepay_verified_domains: request.applepay_verified_domains,
payment_link_config,
session_expiry: request
.session_expiry
.map(i64::from)
.or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)),
authentication_connector_details: request
.authentication_connector_details
.map(ForeignInto::foreign_into),
payout_link_config,
is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
use_billing_as_payment_method_billing: request
.use_billing_as_payment_method_billing
.or(Some(true)),
collect_shipping_details_from_wallet_connector: request
.collect_shipping_details_from_wallet_connector
.or(Some(false)),
collect_billing_details_from_wallet_connector: request
.collect_billing_details_from_wallet_connector
.or(Some(false)),
always_collect_billing_details_from_wallet_connector: request
.always_collect_billing_details_from_wallet_connector
.or(Some(false)),
always_collect_shipping_details_from_wallet_connector: request
.always_collect_shipping_details_from_wallet_connector
.or(Some(false)),
outgoing_webhook_custom_http_headers,
tax_connector_id: request.tax_connector_id,
is_tax_connector_enabled: request.is_tax_connector_enabled,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: request.is_network_tokenization_enabled,
is_auto_retries_enabled: request.is_auto_retries_enabled.unwrap_or_default(),
max_auto_retries_enabled: request.max_auto_retries_enabled.map(i16::from),
always_request_extended_authorization: request.always_request_extended_authorization,
is_click_to_pay_enabled: request.is_click_to_pay_enabled,
authentication_product_ids: request.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(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: request.is_clear_pan_retries_enabled.unwrap_or_default(),
force_3ds_challenge: request.force_3ds_challenge.unwrap_or_default(),
is_debit_routing_enabled: request.is_debit_routing_enabled.unwrap_or_default(),
merchant_business_country: request.merchant_business_country,
is_iframe_redirection_enabled: request.is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled: request
.is_pre_network_tokenization_enabled
.unwrap_or_default(),
merchant_category_code: request.merchant_category_code,
merchant_country_code: request.merchant_country_code,
dispute_polling_interval: request.dispute_polling_interval,
is_manual_retry_enabled: request.is_manual_retry_enabled,
always_enable_overcapture: request.always_enable_overcapture,
external_vault_details: domain::ExternalVaultDetails::try_from((
request.is_external_vault_enabled,
request
.external_vault_connector_details
.map(ForeignInto::foreign_into),
))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while generating external_vault_details")?,
billing_processor_id: request.billing_processor_id,
is_l2_l3_enabled: request.is_l2_l3_enabled.unwrap_or(false),
}))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/payouts.rs | crates/router/src/types/api/payouts.rs | pub use api_models::payouts::{
AchBankTransfer, BacsBankTransfer, Bank as BankPayout, BankRedirect as BankRedirectPayout,
CardPayout, Passthrough as PassthroughPayout, PaymentMethodTypeInfo, PayoutActionRequest,
PayoutAttemptResponse, PayoutCreateRequest, PayoutCreateResponse,
PayoutEnabledPaymentMethodsInfo, PayoutLinkResponse, PayoutListConstraints,
PayoutListFilterConstraints, PayoutListFilters, PayoutListFiltersV2, PayoutListResponse,
PayoutMethodData, PayoutMethodDataResponse, PayoutRequest, PayoutRetrieveBody,
PayoutRetrieveRequest, PayoutsManualUpdateRequest, PixBankTransfer,
RequiredFieldsOverrideRequest, SepaBankTransfer, Wallet as WalletPayout,
};
pub use hyperswitch_domain_models::router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync,
};
pub use hyperswitch_interfaces::api::payouts::{
PayoutCancel, PayoutCreate, PayoutEligibility, PayoutFulfill, PayoutQuote, PayoutRecipient,
PayoutRecipientAccount, PayoutSync, Payouts,
};
pub use super::payouts_v2::{
PayoutCancelV2, PayoutCreateV2, PayoutEligibilityV2, PayoutFulfillV2, PayoutQuoteV2,
PayoutRecipientAccountV2, PayoutRecipientV2, PayoutSyncV2, PayoutsV2,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/files_v2.rs | crates/router/src/types/api/files_v2.rs | pub use hyperswitch_domain_models::router_flow_types::files::{Retrieve, Upload};
pub use hyperswitch_interfaces::api::files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/fraud_check_v2.rs | crates/router/src/types/api/fraud_check_v2.rs | pub use hyperswitch_domain_models::router_flow_types::fraud_check::{
Checkout, Fulfillment, RecordReturn, Sale, Transaction,
};
pub use hyperswitch_interfaces::api::fraud_check_v2::{
FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2,
FraudCheckTransactionV2, FraudCheckV2,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/authentication_v2.rs | crates/router/src/types/api/authentication_v2.rs | pub use hyperswitch_domain_models::router_request_types::authentication::MessageCategory;
pub use hyperswitch_interfaces::api::authentication_v2::ExternalAuthenticationV2;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/verify_connector.rs | crates/router/src/types/api/verify_connector.rs | pub mod paypal;
pub mod stripe;
use error_stack::ResultExt;
use crate::{
consts,
core::errors,
services::{
self,
connector_integration_interface::{BoxedConnectorIntegrationInterface, ConnectorEnum},
},
types::{self, api, api::ConnectorCommon, domain, storage::enums as storage_enums},
SessionState,
};
#[derive(Clone)]
pub struct VerifyConnectorData {
pub connector: ConnectorEnum,
pub connector_auth: types::ConnectorAuthType,
pub card_details: domain::Card,
}
impl VerifyConnectorData {
fn get_payment_authorize_data(&self) -> types::PaymentsAuthorizeData {
types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(self.card_details.clone()),
email: None,
customer_name: None,
amount: 1000,
minor_amount: common_utils::types::MinorUnit::new(1000),
confirm: true,
order_tax_amount: None,
currency: storage_enums::Currency::USD,
metadata: None,
mandate_id: None,
webhook_url: None,
customer_id: None,
off_session: None,
browser_info: None,
session_token: None,
order_details: None,
order_category: None,
capture_method: None,
enrolled_for_3ds: false,
router_return_url: None,
surcharge_details: None,
setup_future_usage: None,
payment_experience: None,
payment_method_type: None,
setup_mandate_details: None,
complete_authorize_url: None,
related_transaction_id: None,
request_extended_authorization: None,
request_incremental_authorization: false,
authentication_data: None,
customer_acceptance: None,
split_payments: None,
merchant_order_reference_id: None,
integrity_object: None,
additional_payment_method_data: None,
shipping_cost: None,
merchant_account_id: None,
merchant_config_currency: None,
connector_testing_data: None,
order_id: None,
locale: None,
payment_channel: None,
enable_partial_authorization: None,
enable_overcapture: None,
is_stored_credential: None,
mit_category: None,
billing_descriptor: None,
tokenization: None,
partner_merchant_identifier_details: None,
}
}
fn get_router_data<F, R1, R2>(
&self,
state: &SessionState,
request_data: R1,
access_token: Option<types::AccessToken>,
) -> types::RouterData<F, R1, R2> {
let attempt_id =
common_utils::generate_id_with_default_len(consts::VERIFY_CONNECTOR_ID_PREFIX);
types::RouterData {
flow: std::marker::PhantomData,
status: storage_enums::AttemptStatus::Started,
request: request_data,
response: Err(errors::ApiErrorResponse::InternalServerError.into()),
connector: self.connector.id().to_string(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
test_mode: None,
attempt_id: attempt_id.clone(),
description: None,
customer_id: None,
tenant_id: state.tenant.tenant_id.clone(),
merchant_id: common_utils::id_type::MerchantId::default(),
reference_id: None,
access_token,
session_token: None,
payment_method: storage_enums::PaymentMethod::Card,
payment_method_type: None,
amount_captured: None,
minor_amount_captured: None,
preprocessing_id: None,
connector_customer: None,
connector_auth_type: self.connector_auth.clone(),
connector_meta_data: None,
connector_wallets_details: None,
payment_method_token: None,
connector_api_version: None,
recurring_mandate_payment_data: None,
payment_method_status: None,
connector_request_reference_id: attempt_id,
address: types::PaymentAddress::new(None, None, None, None),
payment_id: common_utils::id_type::PaymentId::default()
.get_string_repr()
.to_owned(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
payout_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
}
}
}
#[async_trait::async_trait]
pub trait VerifyConnector {
async fn verify(
state: &SessionState,
connector_data: VerifyConnectorData,
) -> errors::RouterResponse<()> {
let authorize_data = connector_data.get_payment_authorize_data();
let access_token = Self::get_access_token(state, connector_data.clone()).await?;
let router_data = connector_data.get_router_data(state, authorize_data, access_token);
let request = connector_data
.connector
.get_connector_integration()
.build_request(&router_data, &state.conf.connectors)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Payment request cannot be built".to_string(),
})?
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
let response =
services::call_connector_api(&state.to_owned(), request, "verify_connector_request")
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match response {
Ok(_) => Ok(services::ApplicationResponse::StatusOk),
Err(error_response) => {
Self::handle_payment_error_response::<
api::Authorize,
types::PaymentFlowData,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>(
connector_data.connector.get_connector_integration(),
error_response,
)
.await
}
}
}
async fn get_access_token(
_state: &SessionState,
_connector_data: VerifyConnectorData,
) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> {
// AccessToken is None for the connectors without the AccessToken Flow.
// If a connector has that, then it should override this implementation.
Ok(None)
}
async fn handle_payment_error_response<F, ResourceCommonData, Req, Resp>(
// connector: &(dyn api::Connector + Sync),
connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>,
error_response: types::Response,
) -> errors::RouterResponse<()> {
let error = connector
.get_error_response(error_response, None)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
}
.into())
}
async fn handle_access_token_error_response<F, ResourceCommonData, Req, Resp>(
connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>,
error_response: types::Response,
) -> errors::RouterResult<Option<types::AccessToken>> {
let error = connector
.get_error_response(error_response, None)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
}
.into())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/payment_methods.rs | crates/router/src/types/api/payment_methods.rs | #[cfg(feature = "v2")]
pub use api_models::payment_methods::{
CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest,
CardNetworkTokenizeResponse, CardType, CustomerPaymentMethodResponseItem,
DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, GetTokenizePayloadResponse,
ListCountriesCurrenciesRequest, MigrateCardDetail, NetworkTokenDetailsPaymentMethod,
NetworkTokenDetailsResponse, NetworkTokenResponse, PaymentMethodCollectLinkRenderRequest,
PaymentMethodCollectLinkRequest, PaymentMethodCreate, PaymentMethodCreateData,
PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodIntentConfirm,
PaymentMethodIntentCreate, PaymentMethodListData, PaymentMethodListResponseForSession,
PaymentMethodMigrate, PaymentMethodMigrateResponse, PaymentMethodResponse,
PaymentMethodResponseData, PaymentMethodUpdate, PaymentMethodUpdateData, PaymentMethodsData,
ProxyCardDetails, RequestPaymentMethodTypes, TokenDataResponse, TokenDetailsResponse,
TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2,
TokenizedWalletValue1, TokenizedWalletValue2, TotalPaymentMethodCountResponse,
};
#[cfg(feature = "v1")]
pub use api_models::payment_methods::{
CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest,
CardNetworkTokenizeResponse, CustomerPaymentMethod, CustomerPaymentMethodUpdateResponse,
CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest,
GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest,
MigrateCardDetail, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest,
PaymentMethodCreate, PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId,
PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrate,
PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData,
TokenizeCardRequest, TokenizeDataRequest, TokenizePayloadEncrypted, TokenizePayloadRequest,
TokenizePaymentMethodRequest, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1,
TokenizedWalletValue2,
};
use error_stack::report;
use crate::core::{
errors::{self, RouterResult},
payments::helpers::validate_payment_method_type_against_payment_method,
};
#[cfg(feature = "v2")]
use crate::utils;
pub(crate) trait PaymentMethodCreateExt {
fn validate(&self) -> RouterResult<()>;
}
// convert self.payment_method_type to payment_method and compare it against self.payment_method
#[cfg(feature = "v1")]
impl PaymentMethodCreateExt for PaymentMethodCreate {
fn validate(&self) -> RouterResult<()> {
if let Some(pm) = self.payment_method {
if let Some(payment_method_type) = self.payment_method_type {
if !validate_payment_method_type_against_payment_method(pm, payment_method_type) {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid 'payment_method_type' provided".to_string()
})
.attach_printable("Invalid payment method type"));
}
}
}
Ok(())
}
}
#[cfg(feature = "v2")]
impl PaymentMethodCreateExt for PaymentMethodCreate {
fn validate(&self) -> RouterResult<()> {
utils::when(
!validate_payment_method_type_against_payment_method(
self.payment_method_type,
self.payment_method_subtype,
),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid 'payment_method_type' provided".to_string()
})
.attach_printable("Invalid payment method type"))
},
)?;
utils::when(
!Self::validate_payment_method_data_against_payment_method(
self.payment_method_type,
self.payment_method_data.clone(),
),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid 'payment_method_data' provided".to_string()
})
.attach_printable("Invalid payment method data"))
},
)?;
Ok(())
}
}
#[cfg(feature = "v2")]
impl PaymentMethodCreateExt for PaymentMethodIntentConfirm {
fn validate(&self) -> RouterResult<()> {
utils::when(
!validate_payment_method_type_against_payment_method(
self.payment_method_type,
self.payment_method_subtype,
),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid 'payment_method_type' provided".to_string()
})
.attach_printable("Invalid payment method type"))
},
)?;
utils::when(
!Self::validate_payment_method_data_against_payment_method(
self.payment_method_type,
self.payment_method_data.clone(),
),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid 'payment_method_data' provided".to_string()
})
.attach_printable("Invalid payment method data"))
},
)?;
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/authentication.rs | crates/router/src/types/api/authentication.rs | use std::str::FromStr;
use api_models::enums;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
pub use hyperswitch_domain_models::{
router_flow_types::authentication::{
Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall,
},
router_request_types::authentication::MessageCategory,
};
use crate::{connector, core::errors, services::connector_integration_interface::ConnectorEnum};
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]
pub struct AcquirerDetails {
pub acquirer_bin: String,
pub acquirer_merchant_mid: String,
pub acquirer_country_code: Option<String>,
}
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]
pub struct AuthenticationResponse {
pub trans_status: common_enums::TransactionStatus,
pub acs_url: Option<url::Url>,
pub challenge_request: Option<String>,
pub challenge_request_key: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
pub three_dsserver_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub error_message: Option<String>,
}
impl TryFrom<hyperswitch_domain_models::authentication::Authentication> for AuthenticationResponse {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(
authentication: hyperswitch_domain_models::authentication::Authentication,
) -> Result<Self, Self::Error> {
let trans_status = authentication
.trans_status
.unwrap_or(common_enums::TransactionStatus::Failure);
let acs_url = authentication
.acs_url
.map(|url| url::Url::from_str(&url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("not a valid URL")?;
Ok(Self {
trans_status,
acs_url,
challenge_request: authentication.challenge_request,
acs_reference_number: authentication.acs_reference_number,
acs_trans_id: authentication.acs_trans_id,
three_dsserver_trans_id: authentication.threeds_server_transaction_id,
acs_signed_content: authentication.acs_signed_content,
challenge_request_key: authentication.challenge_request_key,
error_message: authentication.error_message,
})
}
}
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]
pub struct PostAuthenticationResponse {
pub trans_status: String,
pub authentication_value: Option<masking::Secret<String>>,
pub eci: Option<String>,
}
#[derive(Clone)]
pub struct AuthenticationConnectorData {
pub connector: ConnectorEnum,
pub connector_name: enums::AuthenticationConnectors,
}
impl AuthenticationConnectorData {
pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector_name = enums::AuthenticationConnectors::from_str(name)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| format!("unable to parse connector: {name}"))?;
let connector = Self::convert_connector(connector_name)?;
Ok(Self {
connector,
connector_name,
})
}
fn convert_connector(
connector_name: enums::AuthenticationConnectors,
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match connector_name {
enums::AuthenticationConnectors::Threedsecureio => {
Ok(ConnectorEnum::Old(Box::new(&connector::Threedsecureio)))
}
enums::AuthenticationConnectors::Netcetera => {
Ok(ConnectorEnum::Old(Box::new(&connector::Netcetera)))
}
enums::AuthenticationConnectors::Gpayments => {
Ok(ConnectorEnum::Old(Box::new(connector::Gpayments::new())))
}
enums::AuthenticationConnectors::CtpMastercard => {
Ok(ConnectorEnum::Old(Box::new(&connector::CtpMastercard)))
}
enums::AuthenticationConnectors::CtpVisa => Ok(ConnectorEnum::Old(Box::new(
connector::UnifiedAuthenticationService::new(),
))),
enums::AuthenticationConnectors::UnifiedAuthenticationService => Ok(
ConnectorEnum::Old(Box::new(connector::UnifiedAuthenticationService::new())),
),
enums::AuthenticationConnectors::Juspaythreedsserver => Ok(ConnectorEnum::Old(
Box::new(connector::Juspaythreedsserver::new()),
)),
enums::AuthenticationConnectors::Cardinal => Ok(ConnectorEnum::Old(Box::new(
connector::UnifiedAuthenticationService::new(),
))),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/files.rs | crates/router/src/types/api/files.rs | use api_models::enums::FileUploadProvider;
pub use hyperswitch_domain_models::router_flow_types::files::{Retrieve, Upload};
pub use hyperswitch_interfaces::api::files::{FilePurpose, FileUpload, RetrieveFile, UploadFile};
use masking::{Deserialize, Serialize};
use serde_with::serde_as;
pub use super::files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2};
use crate::{
core::errors,
types::{self, transformers::ForeignTryFrom},
};
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct FileId {
pub file_id: String,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct FileRetrieveRequest {
pub file_id: String,
pub dispute_id: Option<String>,
}
#[derive(Debug)]
pub enum FileDataRequired {
Required,
NotRequired,
}
impl ForeignTryFrom<FileUploadProvider> for types::Connector {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(item: FileUploadProvider) -> Result<Self, Self::Error> {
match item {
FileUploadProvider::Stripe => Ok(Self::Stripe),
FileUploadProvider::Checkout => Ok(Self::Checkout),
FileUploadProvider::Worldpayvantiv => Ok(Self::Worldpayvantiv),
FileUploadProvider::Router => Err(errors::ApiErrorResponse::NotSupported {
message: "File upload provider is not a connector".to_owned(),
}
.into()),
}
}
}
impl ForeignTryFrom<&types::Connector> for FileUploadProvider {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(item: &types::Connector) -> Result<Self, Self::Error> {
match *item {
types::Connector::Stripe => Ok(Self::Stripe),
types::Connector::Checkout => Ok(Self::Checkout),
types::Connector::Worldpayvantiv => Ok(Self::Worldpayvantiv),
_ => Err(errors::ApiErrorResponse::NotSupported {
message: "Connector not supported as file provider".to_owned(),
}
.into()),
}
}
}
#[serde_as]
#[derive(Debug, Clone, serde::Serialize)]
pub struct CreateFileRequest {
pub file: Vec<u8>,
pub file_name: Option<String>,
pub file_size: i32,
#[serde_as(as = "serde_with::DisplayFromStr")]
pub file_type: mime::Mime,
pub purpose: FilePurpose,
pub dispute_id: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/disputes_v2.rs | crates/router/src/types/api/disputes_v2.rs | pub use hyperswitch_interfaces::api::disputes_v2::{
AcceptDisputeV2, DefendDisputeV2, DisputeSyncV2, DisputeV2, FetchDisputesV2, SubmitEvidenceV2,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/connector_mapping.rs | crates/router/src/types/api/connector_mapping.rs | use std::str::FromStr;
use error_stack::{report, ResultExt};
use hyperswitch_connectors::connectors::{Paytm, Phonepe};
use crate::{
configs::settings::Connectors,
connector,
core::errors::{self, CustomResult},
services::connector_integration_interface::ConnectorEnum,
types::{self, api::enums},
};
/// Routing algorithm will output merchant connector identifier instead of connector name
/// In order to support backwards compatibility for older routing algorithms and merchant accounts
/// the support for connector name is retained
#[derive(Clone, Debug)]
pub struct ConnectorData {
pub connector: ConnectorEnum,
pub connector_name: types::Connector,
pub get_token: GetToken,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
// Normal flow will call the connector and follow the flow specific operations (capture, authorize)
// SessionTokenFromMetadata will avoid calling the connector instead create the session token ( for sdk )
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum GetToken {
GpayMetadata,
SamsungPayMetadata,
AmazonPayMetadata,
ApplePayMetadata,
PaypalSdkMetadata,
PazeMetadata,
Connector,
}
impl ConnectorData {
pub fn get_connector_by_name(
_connectors: &Connectors,
name: &str,
connector_type: GetToken,
connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector = Self::convert_connector(name)?;
let connector_name = enums::Connector::from_str(name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("unable to parse connector name {name}"))?;
Ok(Self {
connector,
connector_name,
get_token: connector_type,
merchant_connector_id: connector_id,
})
}
#[cfg(feature = "payouts")]
pub fn get_payout_connector_by_name(
_connectors: &Connectors,
name: &str,
connector_type: GetToken,
connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector = Self::convert_connector(name)?;
let payout_connector_name = enums::PayoutConnectors::from_str(name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("unable to parse payout connector name {name}"))?;
let connector_name = enums::Connector::from(payout_connector_name);
Ok(Self {
connector,
connector_name,
get_token: connector_type,
merchant_connector_id: connector_id,
})
}
pub fn get_external_vault_connector_by_name(
_connectors: &Connectors,
connector: String,
connector_type: GetToken,
connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector_enum = Self::convert_connector(&connector)?;
let external_vault_connector_name = enums::VaultConnectors::from_str(&connector)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("unable to parse external vault connector name {connector:?}")
})?;
let connector_name = enums::Connector::from(external_vault_connector_name);
Ok(Self {
connector: connector_enum,
connector_name,
get_token: connector_type,
merchant_connector_id: connector_id,
})
}
pub fn convert_connector(
connector_name: &str,
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match enums::Connector::from_str(connector_name) {
Ok(name) => match name {
enums::Connector::Aci => Ok(ConnectorEnum::Old(Box::new(connector::Aci::new()))),
enums::Connector::Adyen => {
Ok(ConnectorEnum::Old(Box::new(connector::Adyen::new())))
}
enums::Connector::Affirm => {
Ok(ConnectorEnum::Old(Box::new(connector::Affirm::new())))
}
enums::Connector::Adyenplatform => Ok(ConnectorEnum::Old(Box::new(
connector::Adyenplatform::new(),
))),
enums::Connector::Airwallex => {
Ok(ConnectorEnum::Old(Box::new(connector::Airwallex::new())))
}
enums::Connector::Amazonpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Amazonpay::new())))
}
enums::Connector::Archipel => {
Ok(ConnectorEnum::Old(Box::new(connector::Archipel::new())))
}
enums::Connector::Authipay => {
Ok(ConnectorEnum::Old(Box::new(connector::Authipay::new())))
}
enums::Connector::Authorizedotnet => Ok(ConnectorEnum::Old(Box::new(
connector::Authorizedotnet::new(),
))),
enums::Connector::Bambora => {
Ok(ConnectorEnum::Old(Box::new(connector::Bambora::new())))
}
enums::Connector::Bamboraapac => {
Ok(ConnectorEnum::Old(Box::new(connector::Bamboraapac::new())))
}
enums::Connector::Bankofamerica => Ok(ConnectorEnum::Old(Box::new(
connector::Bankofamerica::new(),
))),
enums::Connector::Barclaycard => {
Ok(ConnectorEnum::Old(Box::new(connector::Barclaycard::new())))
}
enums::Connector::Billwerk => {
Ok(ConnectorEnum::Old(Box::new(connector::Billwerk::new())))
}
enums::Connector::Bitpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Bitpay::new())))
}
enums::Connector::Blackhawknetwork => Ok(ConnectorEnum::Old(Box::new(
connector::Blackhawknetwork::new(),
))),
enums::Connector::Bluesnap => {
Ok(ConnectorEnum::Old(Box::new(connector::Bluesnap::new())))
}
enums::Connector::Calida => {
Ok(ConnectorEnum::Old(Box::new(connector::Calida::new())))
}
enums::Connector::Boku => Ok(ConnectorEnum::Old(Box::new(connector::Boku::new()))),
enums::Connector::Braintree => {
Ok(ConnectorEnum::Old(Box::new(connector::Braintree::new())))
}
enums::Connector::Breadpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Breadpay::new())))
}
enums::Connector::Cashtocode => {
Ok(ConnectorEnum::Old(Box::new(connector::Cashtocode::new())))
}
enums::Connector::Celero => {
Ok(ConnectorEnum::Old(Box::new(connector::Celero::new())))
}
enums::Connector::Chargebee => {
Ok(ConnectorEnum::Old(Box::new(connector::Chargebee::new())))
}
enums::Connector::Checkbook => {
Ok(ConnectorEnum::Old(Box::new(connector::Checkbook::new())))
}
enums::Connector::Checkout => {
Ok(ConnectorEnum::Old(Box::new(connector::Checkout::new())))
}
enums::Connector::Coinbase => {
Ok(ConnectorEnum::Old(Box::new(connector::Coinbase::new())))
}
enums::Connector::Coingate => {
Ok(ConnectorEnum::Old(Box::new(connector::Coingate::new())))
}
enums::Connector::Zift => Ok(ConnectorEnum::Old(Box::new(connector::Zift::new()))),
enums::Connector::Cryptopay => {
Ok(ConnectorEnum::Old(Box::new(connector::Cryptopay::new())))
}
enums::Connector::CtpMastercard => {
Ok(ConnectorEnum::Old(Box::new(&connector::CtpMastercard)))
}
enums::Connector::Custombilling => Ok(ConnectorEnum::Old(Box::new(
connector::Custombilling::new(),
))),
enums::Connector::CtpVisa => Ok(ConnectorEnum::Old(Box::new(
connector::UnifiedAuthenticationService::new(),
))),
enums::Connector::Cybersource => {
Ok(ConnectorEnum::Old(Box::new(connector::Cybersource::new())))
}
enums::Connector::Datatrans => {
Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new())))
}
enums::Connector::Deutschebank => {
Ok(ConnectorEnum::Old(Box::new(connector::Deutschebank::new())))
}
enums::Connector::Digitalvirgo => {
Ok(ConnectorEnum::Old(Box::new(connector::Digitalvirgo::new())))
}
enums::Connector::Dlocal => {
Ok(ConnectorEnum::Old(Box::new(connector::Dlocal::new())))
}
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector1 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<1>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector2 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<2>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector3 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<3>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector4 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<4>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector5 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<5>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector6 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<6>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector7 => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<7>::new(),
))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyBillingConnector => Ok(ConnectorEnum::Old(Box::new(
connector::DummyConnector::<8>::new(),
))),
enums::Connector::Dwolla => {
Ok(ConnectorEnum::Old(Box::new(connector::Dwolla::new())))
}
enums::Connector::Ebanx => {
Ok(ConnectorEnum::Old(Box::new(connector::Ebanx::new())))
}
enums::Connector::Elavon => {
Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new())))
}
enums::Connector::Facilitapay => {
Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay::new())))
}
enums::Connector::Finix => {
Ok(ConnectorEnum::Old(Box::new(connector::Finix::new())))
}
enums::Connector::Fiserv => {
Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new())))
}
enums::Connector::Fiservemea => {
Ok(ConnectorEnum::Old(Box::new(connector::Fiservemea::new())))
}
enums::Connector::Fiuu => Ok(ConnectorEnum::Old(Box::new(connector::Fiuu::new()))),
enums::Connector::Flexiti => {
Ok(ConnectorEnum::Old(Box::new(connector::Flexiti::new())))
}
enums::Connector::Forte => {
Ok(ConnectorEnum::Old(Box::new(connector::Forte::new())))
}
enums::Connector::Getnet => {
Ok(ConnectorEnum::Old(Box::new(connector::Getnet::new())))
}
enums::Connector::Gigadat => {
Ok(ConnectorEnum::Old(Box::new(connector::Gigadat::new())))
}
enums::Connector::Globalpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Globalpay::new())))
}
enums::Connector::Globepay => {
Ok(ConnectorEnum::Old(Box::new(connector::Globepay::new())))
}
enums::Connector::Gocardless => {
Ok(ConnectorEnum::Old(Box::new(connector::Gocardless::new())))
}
enums::Connector::Hipay => {
Ok(ConnectorEnum::Old(Box::new(connector::Hipay::new())))
}
enums::Connector::Helcim => {
Ok(ConnectorEnum::Old(Box::new(connector::Helcim::new())))
}
enums::Connector::HyperswitchVault => {
Ok(ConnectorEnum::Old(Box::new(&connector::HyperswitchVault)))
}
enums::Connector::Iatapay => {
Ok(ConnectorEnum::Old(Box::new(connector::Iatapay::new())))
}
enums::Connector::Inespay => {
Ok(ConnectorEnum::Old(Box::new(connector::Inespay::new())))
}
enums::Connector::Itaubank => {
Ok(ConnectorEnum::Old(Box::new(connector::Itaubank::new())))
}
enums::Connector::Jpmorgan => {
Ok(ConnectorEnum::Old(Box::new(connector::Jpmorgan::new())))
}
enums::Connector::Juspaythreedsserver => Ok(ConnectorEnum::Old(Box::new(
connector::Juspaythreedsserver::new(),
))),
enums::Connector::Klarna => {
Ok(ConnectorEnum::Old(Box::new(connector::Klarna::new())))
}
enums::Connector::Loonio => {
Ok(ConnectorEnum::Old(Box::new(connector::Loonio::new())))
}
enums::Connector::Mollie => {
// enums::Connector::Moneris => Ok(ConnectorEnum::Old(Box::new(connector::Moneris))),
Ok(ConnectorEnum::Old(Box::new(connector::Mollie::new())))
}
enums::Connector::Moneris => {
Ok(ConnectorEnum::Old(Box::new(connector::Moneris::new())))
}
enums::Connector::Nexixpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Nexixpay::new())))
}
enums::Connector::Nmi => Ok(ConnectorEnum::Old(Box::new(connector::Nmi::new()))),
enums::Connector::Nomupay => {
Ok(ConnectorEnum::Old(Box::new(connector::Nomupay::new())))
}
enums::Connector::Noon => Ok(ConnectorEnum::Old(Box::new(connector::Noon::new()))),
enums::Connector::Nordea => {
Ok(ConnectorEnum::Old(Box::new(connector::Nordea::new())))
}
enums::Connector::Novalnet => {
Ok(ConnectorEnum::Old(Box::new(connector::Novalnet::new())))
}
enums::Connector::Nuvei => {
Ok(ConnectorEnum::Old(Box::new(connector::Nuvei::new())))
}
enums::Connector::Opennode => {
Ok(ConnectorEnum::Old(Box::new(connector::Opennode::new())))
}
enums::Connector::Paybox => {
Ok(ConnectorEnum::Old(Box::new(connector::Paybox::new())))
}
// "payeezy" => Ok(ConnectorIntegrationEnum::Old(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage
// enums::Connector::Payload => {
// Ok(ConnectorEnum::Old(Box::new(connector::Paybload::new())))
// }
enums::Connector::Payload => {
Ok(ConnectorEnum::Old(Box::new(connector::Payload::new())))
}
enums::Connector::Payjustnow => {
Ok(ConnectorEnum::Old(Box::new(connector::Payjustnow::new())))
}
enums::Connector::Payjustnowinstore => Ok(ConnectorEnum::Old(Box::new(
connector::Payjustnowinstore::new(),
))),
enums::Connector::Payme => {
Ok(ConnectorEnum::Old(Box::new(connector::Payme::new())))
}
enums::Connector::Payone => {
Ok(ConnectorEnum::Old(Box::new(connector::Payone::new())))
}
enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))),
enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new(
hyperswitch_connectors::connectors::Peachpayments::new(),
))),
enums::Connector::Placetopay => {
Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new())))
}
enums::Connector::Powertranz => {
Ok(ConnectorEnum::Old(Box::new(connector::Powertranz::new())))
}
enums::Connector::Prophetpay => {
Ok(ConnectorEnum::Old(Box::new(&connector::Prophetpay)))
}
enums::Connector::Razorpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Razorpay::new())))
}
enums::Connector::Rapyd => {
Ok(ConnectorEnum::Old(Box::new(connector::Rapyd::new())))
}
enums::Connector::Recurly => {
Ok(ConnectorEnum::New(Box::new(connector::Recurly::new())))
}
enums::Connector::Redsys => {
Ok(ConnectorEnum::Old(Box::new(connector::Redsys::new())))
}
enums::Connector::Santander => {
Ok(ConnectorEnum::Old(Box::new(connector::Santander::new())))
}
enums::Connector::Shift4 => {
Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new())))
}
enums::Connector::Silverflow => {
Ok(ConnectorEnum::Old(Box::new(connector::Silverflow::new())))
}
enums::Connector::Square => Ok(ConnectorEnum::Old(Box::new(&connector::Square))),
enums::Connector::Stax => Ok(ConnectorEnum::Old(Box::new(&connector::Stax))),
enums::Connector::Stripe => {
Ok(ConnectorEnum::Old(Box::new(connector::Stripe::new())))
}
enums::Connector::Stripebilling => Ok(ConnectorEnum::Old(Box::new(
connector::Stripebilling::new(),
))),
enums::Connector::Wise => Ok(ConnectorEnum::Old(Box::new(connector::Wise::new()))),
enums::Connector::Worldline => {
Ok(ConnectorEnum::Old(Box::new(&connector::Worldline)))
}
enums::Connector::Worldpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Worldpay::new())))
}
enums::Connector::Worldpayvantiv => Ok(ConnectorEnum::Old(Box::new(
connector::Worldpayvantiv::new(),
))),
enums::Connector::Worldpayxml => {
Ok(ConnectorEnum::Old(Box::new(connector::Worldpayxml::new())))
}
enums::Connector::Xendit => {
Ok(ConnectorEnum::Old(Box::new(connector::Xendit::new())))
}
enums::Connector::Mifinity => {
Ok(ConnectorEnum::Old(Box::new(connector::Mifinity::new())))
}
enums::Connector::Multisafepay => {
Ok(ConnectorEnum::Old(Box::new(connector::Multisafepay::new())))
}
enums::Connector::Netcetera => {
Ok(ConnectorEnum::Old(Box::new(&connector::Netcetera)))
}
enums::Connector::Nexinets => {
Ok(ConnectorEnum::Old(Box::new(&connector::Nexinets)))
}
// enums::Connector::Nexixpay => {
// Ok(ConnectorEnum::Old(Box::new(&connector::Nexixpay)))
// }
enums::Connector::Paypal => {
Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new())))
}
enums::Connector::Paysafe => {
Ok(ConnectorEnum::Old(Box::new(connector::Paysafe::new())))
}
enums::Connector::Paystack => {
Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new())))
}
// enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))),
enums::Connector::Tesouro => {
Ok(ConnectorEnum::Old(Box::new(connector::Tesouro::new())))
}
enums::Connector::Tokenex => Ok(ConnectorEnum::Old(Box::new(&connector::Tokenex))),
enums::Connector::Tokenio => {
Ok(ConnectorEnum::Old(Box::new(connector::Tokenio::new())))
}
enums::Connector::Trustpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new())))
}
enums::Connector::Trustpayments => Ok(ConnectorEnum::Old(Box::new(
connector::Trustpayments::new(),
))),
enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(connector::Tsys::new()))),
// enums::Connector::UnifiedAuthenticationService => Ok(ConnectorEnum::Old(Box::new(
// connector::UnifiedAuthenticationService,
// ))),
enums::Connector::Vgs => Ok(ConnectorEnum::Old(Box::new(&connector::Vgs))),
enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))),
enums::Connector::Wellsfargo => {
Ok(ConnectorEnum::Old(Box::new(connector::Wellsfargo::new())))
}
// enums::Connector::Wellsfargopayout => {
// Ok(Box::new(connector::Wellsfargopayout::new()))
// }
enums::Connector::Zen => Ok(ConnectorEnum::Old(Box::new(&connector::Zen))),
enums::Connector::Zsl => Ok(ConnectorEnum::Old(Box::new(&connector::Zsl))),
enums::Connector::Plaid => {
Ok(ConnectorEnum::Old(Box::new(connector::Plaid::new())))
}
enums::Connector::Signifyd
| enums::Connector::Riskified
| enums::Connector::Gpayments
| enums::Connector::Threedsecureio
| enums::Connector::Cardinal
| enums::Connector::Taxjar => {
Err(report!(errors::ConnectorError::InvalidConnectorName)
.attach_printable(format!("invalid connector name: {connector_name}")))
.change_context(errors::ApiErrorResponse::InternalServerError)
}
enums::Connector::Phonepe => Ok(ConnectorEnum::Old(Box::new(Phonepe::new()))),
enums::Connector::Paytm => Ok(ConnectorEnum::Old(Box::new(Paytm::new()))),
},
Err(_) => Err(report!(errors::ConnectorError::InvalidConnectorName)
.attach_printable(format!("invalid connector name: {connector_name}")))
.change_context(errors::ApiErrorResponse::InternalServerError),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/configs.rs | crates/router/src/types/api/configs.rs | #[derive(Clone, serde::Serialize, Debug, serde::Deserialize)]
pub struct Config {
pub key: String,
pub value: String,
}
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]
pub struct ConfigUpdate {
#[serde(skip_deserializing)]
pub key: String,
pub value: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/cards.rs | crates/router/src/types/api/cards.rs | rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false | |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/payments.rs | crates/router/src/types/api/payments.rs | #[cfg(feature = "v2")]
pub use api_models::payments::{
PaymentAttemptListRequest, PaymentAttemptListResponse, PaymentsConfirmIntentRequest,
PaymentsCreateIntentRequest, PaymentsIntentResponse, PaymentsUpdateIntentRequest,
RecoveryPaymentsCreate,
};
#[cfg(feature = "v1")]
pub use api_models::payments::{
PaymentListFilterConstraints, PaymentListResponse, PaymentListResponseV2, PaymentRetrieveBody,
PaymentRetrieveBodyWithCredentials, PaymentsEligibilityRequest,
};
pub use api_models::{
feature_matrix::{
ConnectorFeatureMatrixResponse, FeatureMatrixListResponse, FeatureMatrixRequest,
},
payments::{
Address, AddressDetails, Amount, ApplepayPaymentMethod, AuthenticationForStartResponse,
Card, CryptoData, CustomerDetails, CustomerDetailsResponse, HyperswitchVaultSessionDetails,
MandateAmountData, MandateData, MandateTransactionType, MandateType,
MandateValidationFields, NextActionType, OpenBankingSessionToken, PayLaterData,
PaymentIdType, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2,
PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp,
PaymentsAggregateResponse, PaymentsApproveRequest, PaymentsCancelPostCaptureRequest,
PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest,
PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse,
PaymentsExtendAuthorizationRequest, PaymentsExternalAuthenticationRequest,
PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest,
PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse,
PaymentsRedirectRequest, PaymentsRedirectionResponse, PaymentsRejectRequest,
PaymentsRequest, PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest,
PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest,
PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse, PgRedirectResponse,
PhoneDetails, RedirectionResponse, SessionToken, UrlDetails, VaultSessionDetails,
VerifyRequest, VerifyResponse, VgsSessionDetails, WalletData,
},
};
pub use common_types::payments::{AcceptanceType, CustomerAcceptance, OnlineMandate};
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::payments::{
Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize,
CreateConnectorCustomer, CreateOrder, ExtendAuthorization, ExternalVaultProxy,
IncrementalAuthorization, InitPayment, PSync, PaymentCreateIntent, PaymentGetIntent,
PaymentMethodToken, PaymentUpdateIntent, PostCaptureVoid, PostProcessing, PostSessionTokens,
PreProcessing, RecordAttempt, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata,
Void,
};
pub use hyperswitch_interfaces::api::payments::{
ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize,
PaymentAuthorizeSessionToken, PaymentCapture, PaymentIncrementalAuthorization,
PaymentPostCaptureVoid, PaymentPostSessionTokens, PaymentReject, PaymentSession,
PaymentSessionUpdate, PaymentSync, PaymentToken, PaymentUpdateMetadata, PaymentVoid,
PaymentsCompleteAuthorize, PaymentsCreateOrder, PaymentsPostProcessing, PaymentsPreProcessing,
TaxCalculation,
};
pub use super::payments_v2::{
ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2,
PaymentAuthorizeV2, PaymentCaptureV2, PaymentExtendAuthorizationV2,
PaymentIncrementalAuthorizationV2, PaymentPostCaptureVoidV2, PaymentPostSessionTokensV2,
PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2,
PaymentUpdateMetadataV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2,
PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2,
};
use crate::core::errors;
pub trait PaymentIdTypeExt {
#[cfg(feature = "v1")]
fn get_payment_intent_id(
&self,
) -> errors::CustomResult<common_utils::id_type::PaymentId, errors::ValidationError>;
#[cfg(feature = "v2")]
fn get_payment_intent_id(
&self,
) -> errors::CustomResult<common_utils::id_type::GlobalPaymentId, errors::ValidationError>;
}
impl PaymentIdTypeExt for PaymentIdType {
#[cfg(feature = "v1")]
fn get_payment_intent_id(
&self,
) -> errors::CustomResult<common_utils::id_type::PaymentId, errors::ValidationError> {
match self {
Self::PaymentIntentId(id) => Ok(id.clone()),
Self::ConnectorTransactionId(_)
| Self::PaymentAttemptId(_)
| Self::PreprocessingId(_) => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "payment_id",
})
.attach_printable("Expected payment intent ID but got connector transaction ID"),
}
}
#[cfg(feature = "v2")]
fn get_payment_intent_id(
&self,
) -> errors::CustomResult<common_utils::id_type::GlobalPaymentId, errors::ValidationError> {
match self {
Self::PaymentIntentId(id) => Ok(id.clone()),
Self::ConnectorTransactionId(_)
| Self::PaymentAttemptId(_)
| Self::PreprocessingId(_) => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "payment_id",
})
.attach_printable("Expected payment intent ID but got connector transaction ID"),
}
}
}
pub(crate) trait MandateValidationFieldsExt {
fn validate_and_get_mandate_type(
&self,
) -> errors::CustomResult<Option<MandateTransactionType>, errors::ValidationError>;
}
impl MandateValidationFieldsExt for MandateValidationFields {
fn validate_and_get_mandate_type(
&self,
) -> errors::CustomResult<Option<MandateTransactionType>, errors::ValidationError> {
match (&self.mandate_data, &self.recurring_details) {
(None, None) => Ok(None),
(Some(_), Some(_)) => Err(errors::ValidationError::InvalidValue {
message: "Expected one out of recurring_details and mandate_data but got both"
.to_string(),
}
.into()),
(_, Some(_)) => Ok(Some(MandateTransactionType::RecurringMandateTransaction)),
(Some(_), _) => Ok(Some(MandateTransactionType::NewMandateTransaction)),
}
}
}
#[cfg(feature = "v1")]
#[cfg(test)]
mod payments_test {
use super::*;
#[allow(dead_code)]
fn card() -> Card {
Card {
card_number: "1234432112344321".to_string().try_into().unwrap(),
card_exp_month: "12".to_string().into(),
card_exp_year: "99".to_string().into(),
card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())),
card_cvc: "123".to_string().into(),
card_issuer: Some("HDFC".to_string()),
card_network: Some(api_models::enums::CardNetwork::Visa),
bank_code: None,
card_issuing_country: None,
card_issuing_country_code: None,
card_type: None,
nick_name: Some(masking::Secret::new("nick_name".into())),
}
}
#[allow(dead_code)]
fn payments_request() -> PaymentsRequest {
PaymentsRequest {
amount: Some(Amount::from(common_utils::types::MinorUnit::new(200))),
payment_method_data: Some(PaymentMethodDataRequest {
payment_method_data: Some(PaymentMethodData::Card(card())),
billing: None,
}),
..PaymentsRequest::default()
}
}
//#[test] // FIXME: Fix test
#[allow(dead_code)]
fn verify_payments_request() {
let pay_req = payments_request();
let serialized =
serde_json::to_string(&pay_req).expect("error serializing payments request");
let _deserialized_pay_req: PaymentsRequest =
serde_json::from_str(&serialized).expect("error de-serializing payments response");
//assert_eq!(pay_req, deserialized_pay_req)
}
// Intended to test the serialization and deserialization of the enum PaymentIdType
#[test]
fn test_connector_id_type() {
let sample_1 = PaymentIdType::PaymentIntentId(
common_utils::id_type::PaymentId::try_from(std::borrow::Cow::Borrowed(
"test_234565430uolsjdnf48i0",
))
.unwrap(),
);
let s_sample_1 = serde_json::to_string(&sample_1).unwrap();
let ds_sample_1 = serde_json::from_str::<PaymentIdType>(&s_sample_1).unwrap();
assert_eq!(ds_sample_1, sample_1)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/bank_accounts.rs | crates/router/src/types/api/bank_accounts.rs | rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false | |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/verify_connector/stripe.rs | crates/router/src/types/api/verify_connector/stripe.rs | use error_stack::ResultExt;
use router_env::env;
use super::VerifyConnector;
use crate::{
connector, core::errors, services, types,
types::api::verify_connector::BoxedConnectorIntegrationInterface,
};
#[async_trait::async_trait]
impl VerifyConnector for connector::Stripe {
async fn handle_payment_error_response<F, ResourceCommonData, Req, Resp>(
connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>,
error_response: types::Response,
) -> errors::RouterResponse<()> {
let error = connector
.get_error_response(error_response, None)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match (env::which(), error.code.as_str()) {
// In situations where an attempt is made to process a payment using a
// Stripe production key along with a test card (which verify_connector is using),
// Stripe will respond with a "card_declined" error. In production,
// when this scenario occurs we will send back an "Ok" response.
(env::Env::Production, "card_declined") => Ok(services::ApplicationResponse::StatusOk),
_ => Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
}
.into()),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/verify_connector/paypal.rs | crates/router/src/types/api/verify_connector/paypal.rs | use error_stack::ResultExt;
use super::{VerifyConnector, VerifyConnectorData};
use crate::{
connector,
core::errors,
routes::SessionState,
services,
types::{self, api},
};
#[async_trait::async_trait]
impl VerifyConnector for connector::Paypal {
async fn get_access_token(
state: &SessionState,
connector_data: VerifyConnectorData,
) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> {
let token_data: types::AccessTokenRequestData =
connector_data.connector_auth.clone().try_into()?;
let router_data = connector_data.get_router_data(state, token_data, None);
let request = connector_data
.connector
.get_connector_integration()
.build_request(&router_data, &state.conf.connectors)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Payment request cannot be built".to_string(),
})?
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
let response = services::call_connector_api(&state.to_owned(), request, "get_access_token")
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match response {
Ok(res) => Some(
connector_data
.connector
.get_connector_integration()
.handle_response(&router_data, None, res)
.change_context(errors::ApiErrorResponse::InternalServerError)?
.response
.map_err(|_| errors::ApiErrorResponse::InternalServerError.into()),
)
.transpose(),
Err(response_data) => {
Self::handle_access_token_error_response::<
api::AccessTokenAuth,
types::AccessTokenFlowData,
types::AccessTokenRequestData,
types::AccessToken,
>(
connector_data.connector.get_connector_integration(),
response_data,
)
.await
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/types/api/connector_onboarding/paypal.rs | crates/router/src/types/api/connector_onboarding/paypal.rs | use api_models::connector_onboarding as api;
use error_stack::ResultExt;
use crate::core::errors::{ApiErrorResponse, RouterResult};
#[derive(serde::Deserialize, Debug)]
pub struct HateoasLink {
pub href: String,
pub rel: String,
pub method: String,
}
#[derive(serde::Deserialize, Debug)]
pub struct PartnerReferralResponse {
pub links: Vec<HateoasLink>,
}
#[derive(serde::Serialize, Debug)]
pub struct PartnerReferralRequest {
pub tracking_id: String,
pub operations: Vec<PartnerReferralOperations>,
pub products: Vec<PayPalProducts>,
pub capabilities: Vec<PayPalCapabilities>,
pub partner_config_override: PartnerConfigOverride,
pub legal_consents: Vec<LegalConsent>,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayPalProducts {
Ppcp,
AdvancedVaulting,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayPalCapabilities {
PaypalWalletVaultingAdvanced,
}
#[derive(serde::Serialize, Debug)]
pub struct PartnerReferralOperations {
pub operation: PayPalReferralOperationType,
pub api_integration_preference: PartnerReferralIntegrationPreference,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayPalReferralOperationType {
ApiIntegration,
}
#[derive(serde::Serialize, Debug)]
pub struct PartnerReferralIntegrationPreference {
pub rest_api_integration: PartnerReferralRestApiIntegration,
}
#[derive(serde::Serialize, Debug)]
pub struct PartnerReferralRestApiIntegration {
pub integration_method: IntegrationMethod,
pub integration_type: PayPalIntegrationType,
pub third_party_details: PartnerReferralThirdPartyDetails,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum IntegrationMethod {
Paypal,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayPalIntegrationType {
ThirdParty,
}
#[derive(serde::Serialize, Debug)]
pub struct PartnerReferralThirdPartyDetails {
pub features: Vec<PayPalFeatures>,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayPalFeatures {
Payment,
Refund,
Vault,
AccessMerchantInformation,
BillingAgreement,
ReadSellerDispute,
}
#[derive(serde::Serialize, Debug)]
pub struct PartnerConfigOverride {
pub partner_logo_url: String,
pub return_url: String,
}
#[derive(serde::Serialize, Debug)]
pub struct LegalConsent {
#[serde(rename = "type")]
pub consent_type: LegalConsentType,
pub granted: bool,
}
#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LegalConsentType {
ShareDataConsent,
}
impl PartnerReferralRequest {
pub fn new(tracking_id: String, return_url: String) -> Self {
Self {
tracking_id,
operations: vec![PartnerReferralOperations {
operation: PayPalReferralOperationType::ApiIntegration,
api_integration_preference: PartnerReferralIntegrationPreference {
rest_api_integration: PartnerReferralRestApiIntegration {
integration_method: IntegrationMethod::Paypal,
integration_type: PayPalIntegrationType::ThirdParty,
third_party_details: PartnerReferralThirdPartyDetails {
features: vec![
PayPalFeatures::Payment,
PayPalFeatures::Refund,
PayPalFeatures::Vault,
PayPalFeatures::AccessMerchantInformation,
PayPalFeatures::BillingAgreement,
PayPalFeatures::ReadSellerDispute,
],
},
},
},
}],
products: vec![PayPalProducts::Ppcp, PayPalProducts::AdvancedVaulting],
capabilities: vec![PayPalCapabilities::PaypalWalletVaultingAdvanced],
partner_config_override: PartnerConfigOverride {
partner_logo_url: "https://hyperswitch.io/img/websiteIcon.svg".to_string(),
return_url,
},
legal_consents: vec![LegalConsent {
consent_type: LegalConsentType::ShareDataConsent,
granted: true,
}],
}
}
}
#[derive(serde::Deserialize, Debug)]
pub struct SellerStatusResponse {
pub merchant_id: common_utils::id_type::MerchantId,
pub links: Vec<HateoasLink>,
}
#[derive(serde::Deserialize, Debug)]
pub struct SellerStatusDetailsResponse {
pub merchant_id: common_utils::id_type::MerchantId,
pub primary_email_confirmed: bool,
pub payments_receivable: bool,
pub products: Vec<SellerStatusProducts>,
}
#[derive(serde::Deserialize, Debug)]
pub struct SellerStatusProducts {
pub name: String,
pub vetting_status: Option<VettingStatus>,
}
#[derive(serde::Deserialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VettingStatus {
NeedMoreData,
Subscribed,
Denied,
}
impl SellerStatusResponse {
pub fn extract_merchant_details_url(self, paypal_base_url: &str) -> RouterResult<String> {
self.links
.first()
.and_then(|link| link.href.strip_prefix('/'))
.map(|link| format!("{paypal_base_url}{link}"))
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Merchant details not received in onboarding status")
}
}
impl SellerStatusDetailsResponse {
pub fn check_payments_receivable(&self) -> Option<api::PayPalOnboardingStatus> {
if !self.payments_receivable {
return Some(api::PayPalOnboardingStatus::PaymentsNotReceivable);
}
None
}
pub fn check_ppcp_custom_status(&self) -> Option<api::PayPalOnboardingStatus> {
match self.get_ppcp_custom_status() {
Some(VettingStatus::Denied) => Some(api::PayPalOnboardingStatus::PpcpCustomDenied),
Some(VettingStatus::Subscribed) => None,
_ => Some(api::PayPalOnboardingStatus::MorePermissionsNeeded),
}
}
fn check_email_confirmation(&self) -> Option<api::PayPalOnboardingStatus> {
if !self.primary_email_confirmed {
return Some(api::PayPalOnboardingStatus::EmailNotVerified);
}
None
}
pub async fn get_eligibility_status(&self) -> RouterResult<api::PayPalOnboardingStatus> {
Ok(self
.check_payments_receivable()
.or(self.check_email_confirmation())
.or(self.check_ppcp_custom_status())
.unwrap_or(api::PayPalOnboardingStatus::Success(
api::PayPalOnboardingDone {
payer_id: self.get_payer_id(),
},
)))
}
fn get_ppcp_custom_status(&self) -> Option<VettingStatus> {
self.products
.iter()
.find(|product| product.name == "PPCP_CUSTOM")
.and_then(|ppcp_custom| ppcp_custom.vetting_status.clone())
}
fn get_payer_id(&self) -> common_utils::id_type::MerchantId {
self.merchant_id.to_owned()
}
}
impl PartnerReferralResponse {
pub fn extract_action_url(self) -> RouterResult<String> {
Ok(self
.links
.into_iter()
.find(|hateoas_link| hateoas_link.rel == "action_url")
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get action_url from paypal response")?
.href)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/events/routing_api_logs.rs | crates/router/src/events/routing_api_logs.rs | pub use hyperswitch_interfaces::events::routing_api_logs::RoutingEvent;
use super::EventType;
use crate::services::kafka::KafkaMessage;
impl KafkaMessage for RoutingEvent {
fn event_type(&self) -> EventType {
EventType::RoutingApiLogs
}
fn key(&self) -> String {
format!(
"{}-{}-{}",
self.get_merchant_id(),
self.get_profile_id(),
self.get_payment_id()
)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/events/connector_api_logs.rs | crates/router/src/events/connector_api_logs.rs | pub use hyperswitch_interfaces::events::connector_api_logs::ConnectorEvent;
use super::EventType;
use crate::services::kafka::KafkaMessage;
impl KafkaMessage for ConnectorEvent {
fn event_type(&self) -> EventType {
EventType::ConnectorApiLogs
}
fn key(&self) -> String {
self.request_id.clone()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/events/audit_events.rs | crates/router/src/events/audit_events.rs | use api_models::payments::Amount;
use common_utils::types::MinorUnit;
use diesel_models::fraud_check::FraudCheck;
use events::{Event, EventInfo};
use serde::Serialize;
use time::PrimitiveDateTime;
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "event_type")]
pub enum AuditEventType {
Error {
error_message: String,
},
PaymentCreated,
ConnectorDecided,
ConnectorCalled,
RefundCreated,
RefundSuccess,
RefundFail,
PaymentConfirm {
client_src: Option<String>,
client_ver: Option<String>,
frm_message: Box<Option<FraudCheck>>,
},
PaymentCancelled {
cancellation_reason: Option<String>,
},
PaymentCapture {
capture_amount: Option<MinorUnit>,
multiple_capture_count: Option<i16>,
},
PaymentUpdate {
amount: Amount,
},
PaymentApprove,
PaymentCreate,
PaymentStatus,
PaymentCompleteAuthorize,
PaymentReject {
error_code: Option<String>,
error_message: Option<String>,
},
}
#[derive(Debug, Clone, Serialize)]
pub struct AuditEvent {
#[serde(flatten)]
event_type: AuditEventType,
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
}
impl AuditEvent {
pub fn new(event_type: AuditEventType) -> Self {
Self {
event_type,
created_at: common_utils::date_time::now(),
}
}
}
impl Event for AuditEvent {
type EventType = super::EventType;
fn timestamp(&self) -> PrimitiveDateTime {
self.created_at
}
fn identifier(&self) -> String {
let event_type = match &self.event_type {
AuditEventType::Error { .. } => "error",
AuditEventType::PaymentCreated => "payment_created",
AuditEventType::PaymentConfirm { .. } => "payment_confirm",
AuditEventType::ConnectorDecided => "connector_decided",
AuditEventType::ConnectorCalled => "connector_called",
AuditEventType::PaymentCapture { .. } => "payment_capture",
AuditEventType::RefundCreated => "refund_created",
AuditEventType::RefundSuccess => "refund_success",
AuditEventType::RefundFail => "refund_fail",
AuditEventType::PaymentCancelled { .. } => "payment_cancelled",
AuditEventType::PaymentUpdate { .. } => "payment_update",
AuditEventType::PaymentApprove => "payment_approve",
AuditEventType::PaymentCreate => "payment_create",
AuditEventType::PaymentStatus => "payment_status",
AuditEventType::PaymentCompleteAuthorize => "payment_complete_authorize",
AuditEventType::PaymentReject { .. } => "payment_rejected",
};
format!(
"{event_type}-{}",
self.timestamp().assume_utc().unix_timestamp_nanos()
)
}
fn class(&self) -> Self::EventType {
super::EventType::AuditEvent
}
}
impl EventInfo for AuditEvent {
type Data = Self;
fn data(&self) -> error_stack::Result<Self::Data, events::EventsError> {
Ok(self.clone())
}
fn key(&self) -> String {
"event".to_string()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/events/outgoing_webhook_logs.rs | crates/router/src/events/outgoing_webhook_logs.rs | use api_models::{enums::EventType as OutgoingWebhookEventType, webhooks::OutgoingWebhookContent};
use common_enums::WebhookDeliveryAttempt;
use serde::Serialize;
use serde_json::Value;
use time::OffsetDateTime;
use super::EventType;
use crate::services::kafka::KafkaMessage;
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct OutgoingWebhookEvent {
tenant_id: common_utils::id_type::TenantId,
merchant_id: common_utils::id_type::MerchantId,
event_id: String,
event_type: OutgoingWebhookEventType,
#[serde(flatten)]
content: Option<OutgoingWebhookEventContent>,
is_error: bool,
error: Option<Value>,
created_at_timestamp: i128,
initial_attempt_id: Option<String>,
status_code: Option<u16>,
delivery_attempt: Option<WebhookDeliveryAttempt>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "outgoing_webhook_event_type", rename_all = "snake_case")]
pub enum OutgoingWebhookEventContent {
#[cfg(feature = "v1")]
Payment {
payment_id: common_utils::id_type::PaymentId,
content: Value,
},
#[cfg(feature = "v2")]
Payment {
payment_id: common_utils::id_type::GlobalPaymentId,
content: Value,
},
Payout {
payout_id: common_utils::id_type::PayoutId,
content: Value,
},
#[cfg(feature = "v1")]
Refund {
payment_id: common_utils::id_type::PaymentId,
refund_id: String,
content: Value,
},
#[cfg(feature = "v2")]
Refund {
payment_id: common_utils::id_type::GlobalPaymentId,
refund_id: common_utils::id_type::GlobalRefundId,
content: Value,
},
#[cfg(feature = "v1")]
Dispute {
payment_id: common_utils::id_type::PaymentId,
attempt_id: String,
dispute_id: String,
content: Value,
},
#[cfg(feature = "v2")]
Dispute {
payment_id: common_utils::id_type::GlobalPaymentId,
attempt_id: String,
dispute_id: String,
content: Value,
},
Mandate {
payment_method_id: String,
mandate_id: String,
content: Value,
},
Subscription {
subscription_id: common_utils::id_type::SubscriptionId,
invoice_id: Option<common_utils::id_type::InvoiceId>,
payment_id: Option<common_utils::id_type::PaymentId>,
content: Value,
},
}
pub trait OutgoingWebhookEventMetric {
fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent>;
}
#[cfg(feature = "v1")]
impl OutgoingWebhookEventMetric for OutgoingWebhookContent {
fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> {
match self {
Self::PaymentDetails(payment_payload) => Some(OutgoingWebhookEventContent::Payment {
payment_id: payment_payload.payment_id.clone(),
content: masking::masked_serialize(&payment_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::RefundDetails(refund_payload) => Some(OutgoingWebhookEventContent::Refund {
payment_id: refund_payload.payment_id.clone(),
refund_id: refund_payload.get_refund_id_as_string(),
content: masking::masked_serialize(&refund_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::DisputeDetails(dispute_payload) => Some(OutgoingWebhookEventContent::Dispute {
payment_id: dispute_payload.payment_id.clone(),
attempt_id: dispute_payload.attempt_id.clone(),
dispute_id: dispute_payload.dispute_id.clone(),
content: masking::masked_serialize(&dispute_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::MandateDetails(mandate_payload) => Some(OutgoingWebhookEventContent::Mandate {
payment_method_id: mandate_payload.payment_method_id.clone(),
mandate_id: mandate_payload.mandate_id.clone(),
content: masking::masked_serialize(&mandate_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
#[cfg(feature = "payouts")]
Self::PayoutDetails(payout_payload) => Some(OutgoingWebhookEventContent::Payout {
payout_id: payout_payload.payout_id.clone(),
content: masking::masked_serialize(&payout_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::SubscriptionDetails(subscription) => {
Some(OutgoingWebhookEventContent::Subscription {
subscription_id: subscription.id.clone(),
invoice_id: subscription.get_optional_invoice_id(),
payment_id: subscription.get_optional_payment_id(),
content: masking::masked_serialize(&subscription)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
})
}
}
}
}
#[cfg(feature = "v2")]
impl OutgoingWebhookEventMetric for OutgoingWebhookContent {
fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> {
match self {
Self::PaymentDetails(payment_payload) => Some(OutgoingWebhookEventContent::Payment {
payment_id: payment_payload.id.clone(),
content: masking::masked_serialize(&payment_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::RefundDetails(refund_payload) => Some(OutgoingWebhookEventContent::Refund {
payment_id: refund_payload.payment_id.clone(),
refund_id: refund_payload.id.clone(),
content: masking::masked_serialize(&refund_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::DisputeDetails(dispute_payload) => {
//TODO: add support for dispute outgoing webhook
todo!()
}
Self::MandateDetails(mandate_payload) => Some(OutgoingWebhookEventContent::Mandate {
payment_method_id: mandate_payload.payment_method_id.clone(),
mandate_id: mandate_payload.mandate_id.clone(),
content: masking::masked_serialize(&mandate_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
#[cfg(feature = "payouts")]
Self::PayoutDetails(payout_payload) => Some(OutgoingWebhookEventContent::Payout {
payout_id: payout_payload.payout_id.clone(),
content: masking::masked_serialize(&payout_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
}
}
}
impl OutgoingWebhookEvent {
#[allow(clippy::too_many_arguments)]
pub fn new(
tenant_id: common_utils::id_type::TenantId,
merchant_id: common_utils::id_type::MerchantId,
event_id: String,
event_type: OutgoingWebhookEventType,
content: Option<OutgoingWebhookEventContent>,
error: Option<Value>,
initial_attempt_id: Option<String>,
status_code: Option<u16>,
delivery_attempt: Option<WebhookDeliveryAttempt>,
) -> Self {
Self {
tenant_id,
merchant_id,
event_id,
event_type,
content,
is_error: error.is_some(),
error,
created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
initial_attempt_id,
status_code,
delivery_attempt,
}
}
}
impl KafkaMessage for OutgoingWebhookEvent {
fn event_type(&self) -> EventType {
EventType::OutgoingWebhookLogs
}
fn key(&self) -> String {
self.event_id.clone()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/events/api_logs.rs | crates/router/src/events/api_logs.rs | use actix_web::HttpRequest;
pub use common_utils::events::{ApiEventMetric, ApiEventsType};
use common_utils::impl_api_event_type;
use router_env::{types::FlowMetric, RequestId};
use serde::Serialize;
use time::OffsetDateTime;
use super::EventType;
#[cfg(feature = "dummy_connector")]
use crate::routes::dummy_connector::types::{
DummyConnectorPaymentCompleteRequest, DummyConnectorPaymentConfirmRequest,
DummyConnectorPaymentRequest, DummyConnectorPaymentResponse,
DummyConnectorPaymentRetrieveRequest, DummyConnectorRefundRequest,
DummyConnectorRefundResponse, DummyConnectorRefundRetrieveRequest,
};
use crate::{
core::payments::PaymentsRedirectResponseData,
services::{authentication::AuthenticationType, kafka::KafkaMessage},
types::api::{
AttachEvidenceRequest, Config, ConfigUpdate, CreateFileRequest, DisputeFetchQueryData,
DisputeId, FileId, FileRetrieveRequest, PollId,
},
};
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct ApiEvent {
tenant_id: common_utils::id_type::TenantId,
merchant_id: Option<common_utils::id_type::MerchantId>,
api_flow: String,
created_at_timestamp: i128,
request_id: String,
latency: u128,
status_code: i64,
#[serde(flatten)]
auth_type: AuthenticationType,
request: String,
user_agent: Option<String>,
ip_addr: Option<String>,
url_path: String,
response: Option<String>,
error: Option<serde_json::Value>,
#[serde(flatten)]
event_type: ApiEventsType,
hs_latency: Option<u128>,
http_method: String,
#[serde(flatten)]
infra_components: Option<serde_json::Value>,
}
impl ApiEvent {
#[allow(clippy::too_many_arguments)]
pub fn new(
tenant_id: common_utils::id_type::TenantId,
merchant_id: Option<common_utils::id_type::MerchantId>,
api_flow: &impl FlowMetric,
request_id: &RequestId,
latency: u128,
status_code: i64,
request: serde_json::Value,
response: Option<serde_json::Value>,
hs_latency: Option<u128>,
auth_type: AuthenticationType,
error: Option<serde_json::Value>,
event_type: ApiEventsType,
http_req: &HttpRequest,
http_method: &http::Method,
infra_components: Option<serde_json::Value>,
) -> Self {
Self {
tenant_id,
merchant_id,
api_flow: api_flow.to_string(),
created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
request_id: request_id.to_string(),
latency,
status_code,
request: request.to_string(),
response: response.map(|resp| resp.to_string()),
auth_type,
error,
ip_addr: http_req
.connection_info()
.realip_remote_addr()
.map(ToOwned::to_owned),
user_agent: http_req
.headers()
.get("user-agent")
.and_then(|user_agent_value| user_agent_value.to_str().ok().map(ToOwned::to_owned)),
url_path: http_req.path().to_string(),
event_type,
hs_latency,
http_method: http_method.to_string(),
infra_components,
}
}
}
impl KafkaMessage for ApiEvent {
fn event_type(&self) -> EventType {
EventType::ApiLogs
}
fn key(&self) -> String {
self.request_id.clone()
}
}
impl_api_event_type!(
Miscellaneous,
(
Config,
CreateFileRequest,
FileId,
FileRetrieveRequest,
AttachEvidenceRequest,
DisputeFetchQueryData,
ConfigUpdate
)
);
#[cfg(feature = "dummy_connector")]
impl_api_event_type!(
Miscellaneous,
(
DummyConnectorPaymentCompleteRequest,
DummyConnectorPaymentRequest,
DummyConnectorPaymentResponse,
DummyConnectorPaymentRetrieveRequest,
DummyConnectorPaymentConfirmRequest,
DummyConnectorRefundRetrieveRequest,
DummyConnectorRefundResponse,
DummyConnectorRefundRequest
)
);
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsRedirectResponseData {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentRedirectionResponse {
connector: self.connector.clone(),
payment_id: match &self.resource_id {
api_models::payments::PaymentIdType::PaymentIntentId(id) => Some(id.clone()),
_ => None,
},
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsRedirectResponseData {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentRedirectionResponse {
payment_id: self.payment_id.clone(),
})
}
}
impl ApiEventMetric for DisputeId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Dispute {
dispute_id: self.dispute_id.clone(),
})
}
}
impl ApiEventMetric for PollId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Poll {
poll_id: self.poll_id.clone(),
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/events/event_logger.rs | crates/router/src/events/event_logger.rs | use std::collections::HashMap;
use events::{EventsError, Message, MessagingInterface};
use masking::ErasedMaskSerialize;
use time::PrimitiveDateTime;
use super::EventType;
use crate::services::{kafka::KafkaMessage, logger};
#[derive(Clone, Debug, Default)]
pub struct EventLogger {}
impl EventLogger {
#[track_caller]
pub(super) fn log_event<T: KafkaMessage>(&self, event: &T) {
logger::info!(event = ?event.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? event.event_type(), event_id =? event.key(), log_type =? "event");
}
}
impl MessagingInterface for EventLogger {
type MessageClass = EventType;
fn send_message<T>(
&self,
data: T,
metadata: HashMap<String, String>,
_timestamp: PrimitiveDateTime,
) -> error_stack::Result<(), EventsError>
where
T: Message<Class = Self::MessageClass> + ErasedMaskSerialize,
{
logger::info!(event =? data.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? data.get_message_class(), event_id =? data.identifier(), log_type =? "event", metadata = ?metadata);
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/configs/settings.rs | crates/router/src/configs/settings.rs | use std::{
collections::{HashMap, HashSet},
path::PathBuf,
sync::Arc,
};
#[cfg(feature = "olap")]
use analytics::{opensearch::OpenSearchConfig, ReportConfig};
use api_models::enums;
use common_enums;
use common_utils::{ext_traits::ConfigExt, id_type, types::user::EmailThemeConfig};
use config::{Environment, File};
use error_stack::ResultExt;
#[cfg(feature = "email")]
use external_services::email::EmailSettings;
use external_services::{
crm::CrmManagerConfig,
file_storage::FileStorageConfig,
grpc_client::GrpcClientSettings,
managers::{
encryption_management::EncryptionManagementConfig,
secrets_management::SecretsManagementConfig,
},
superposition::SuperpositionClientConfig,
};
pub use hyperswitch_interfaces::{
configs::{
Connectors, GlobalTenant, InternalMerchantIdProfileIdAuthSettings, InternalServicesConfig,
Tenant, TenantUserConfig,
},
secrets_interface::secret_state::{
RawSecret, SecretState, SecretStateContainer, SecuredSecret,
},
types::{ComparisonServiceConfig, Proxy},
};
use masking::{Maskable, Secret};
pub use payment_methods::configs::settings::{
BankRedirectConfig, BanksVector, ConnectorBankNames, ConnectorFields, EligiblePaymentMethods,
Mandates, PaymentMethodAuth, PaymentMethodType, RequiredFieldFinal, RequiredFields,
SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate,
SupportedPaymentMethodsForMandate, ZeroMandates,
};
use redis_interface::RedisSettings;
pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};
use rust_decimal::Decimal;
use scheduler::SchedulerSettings;
use serde::Deserialize;
use storage_impl::config::QueueStrategy;
#[cfg(feature = "olap")]
use crate::analytics::{AnalyticsConfig, AnalyticsProvider};
#[cfg(feature = "v2")]
use crate::types::storage::revenue_recovery;
use crate::{
configs,
core::errors::{ApplicationError, ApplicationResult},
env::{self, Env},
events::EventsConfig,
headers, logger,
routes::app,
AppState,
};
pub const REQUIRED_FIELDS_CONFIG_FILE: &str = "payment_required_fields_v2.toml";
#[derive(clap::Parser, Default)]
#[cfg_attr(feature = "vergen", command(version = router_env::version!()))]
pub struct CmdLineConf {
/// Config file.
/// Application will look for "config/config.toml" if this option isn't specified.
#[arg(short = 'f', long, value_name = "FILE")]
pub config_path: Option<PathBuf>,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct Settings<S: SecretState> {
pub server: Server,
pub application_source: common_enums::ApplicationSource,
pub proxy: Proxy,
pub env: Env,
pub chat: SecretStateContainer<ChatSettings, S>,
pub master_database: SecretStateContainer<Database, S>,
#[cfg(feature = "olap")]
pub replica_database: SecretStateContainer<Database, S>,
pub redis: RedisSettings,
pub log: Log,
pub secrets: SecretStateContainer<Secrets, S>,
pub fallback_merchant_ids_api_key_auth: Option<FallbackMerchantIds>,
pub locker: Locker,
pub key_manager: SecretStateContainer<KeyManagerConfig, S>,
pub connectors: Connectors,
pub forex_api: SecretStateContainer<ForexApi, S>,
pub refund: Refund,
pub eph_key: EphemeralConfig,
pub scheduler: Option<SchedulerSettings>,
#[cfg(feature = "kv_store")]
pub drainer: DrainerSettings,
pub jwekey: SecretStateContainer<Jwekey, S>,
pub webhooks: WebhooksSettings,
pub pm_filters: ConnectorFilters,
pub bank_config: BankRedirectConfig,
pub api_keys: SecretStateContainer<ApiKeys, S>,
pub file_storage: FileStorageConfig,
pub encryption_management: EncryptionManagementConfig,
pub secrets_management: SecretsManagementConfig,
pub tokenization: TokenizationConfig,
pub connector_customer: ConnectorCustomer,
#[cfg(feature = "dummy_connector")]
pub dummy_connector: DummyConnector,
#[cfg(feature = "email")]
pub email: EmailSettings,
pub user: UserSettings,
pub oidc: SecretStateContainer<OidcSettings, S>,
pub crm: CrmManagerConfig,
pub cors: CorsSettings,
pub mandates: Mandates,
pub zero_mandates: ZeroMandates,
pub network_transaction_id_supported_connectors: NetworkTransactionIdSupportedConnectors,
pub list_dispute_supported_connectors: ListDiputeSupportedConnectors,
pub required_fields: RequiredFields,
pub delayed_session_response: DelayedSessionConfig,
pub webhook_source_verification_call: WebhookSourceVerificationCall,
pub billing_connectors_payment_sync: BillingConnectorPaymentsSyncCall,
pub billing_connectors_invoice_sync: BillingConnectorInvoiceSyncCall,
pub payment_method_auth: SecretStateContainer<PaymentMethodAuth, S>,
pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig,
#[cfg(feature = "payouts")]
pub payouts: Payouts,
pub payout_method_filters: ConnectorFilters,
pub l2_l3_data_config: L2L3DataConfig,
pub debit_routing_config: DebitRoutingConfig,
pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>,
pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>,
pub google_pay_decrypt_keys: Option<GooglePayDecryptConfig>,
pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors,
pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>,
pub lock_settings: LockSettings,
pub temp_locker_enable_config: TempLockerEnableConfig,
pub generic_link: GenericLink,
pub payment_link: PaymentLink,
#[cfg(feature = "olap")]
pub analytics: SecretStateContainer<AnalyticsConfig, S>,
#[cfg(feature = "kv_store")]
pub kv_config: KvConfig,
#[cfg(feature = "frm")]
pub frm: Frm,
#[cfg(feature = "olap")]
pub report_download_config: ReportConfig,
#[cfg(feature = "olap")]
pub opensearch: OpenSearchConfig,
pub events: EventsConfig,
#[cfg(feature = "olap")]
pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>,
pub unmasked_headers: UnmaskedHeaders,
pub multitenancy: Multitenancy,
pub saved_payment_methods: EligiblePaymentMethods,
pub user_auth_methods: SecretStateContainer<UserAuthMethodSettings, S>,
pub decision: Option<DecisionConfig>,
pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList,
pub grpc_client: GrpcClientSettings,
#[cfg(feature = "v2")]
pub cell_information: CellInformation,
pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks,
pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>,
pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors,
pub theme: ThemeSettings,
pub platform: Platform,
pub authentication_providers: AuthenticationProviders,
pub open_router: OpenRouter,
#[cfg(feature = "v2")]
pub revenue_recovery: revenue_recovery::RevenueRecoverySettings,
pub clone_connector_allowlist: Option<CloneConnectorAllowlistConfig>,
pub merchant_id_auth: MerchantIdAuthSettings,
pub preprocessing_flow_config: Option<PreProcessingFlowConfig>,
pub internal_merchant_id_profile_id_auth: InternalMerchantIdProfileIdAuthSettings,
#[serde(default)]
pub infra_values: Option<HashMap<String, String>>,
#[serde(default)]
pub enhancement: Option<HashMap<String, String>>,
pub superposition: SecretStateContainer<SuperpositionClientConfig, S>,
pub proxy_status_mapping: ProxyStatusMapping,
pub trace_header: TraceHeaderConfig,
pub internal_services: InternalServicesConfig,
pub comparison_service: Option<ComparisonServiceConfig>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct PreProcessingFlowConfig {
#[serde(default, deserialize_with = "deserialize_hashset")]
pub authentication_bloated_connectors: HashSet<enums::Connector>,
#[serde(default, deserialize_with = "deserialize_hashset")]
pub order_create_bloated_connectors: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DebitRoutingConfig {
#[serde(deserialize_with = "deserialize_hashmap")]
pub connector_supported_debit_networks: HashMap<enums::Connector, HashSet<enums::CardNetwork>>,
#[serde(deserialize_with = "deserialize_hashset")]
pub supported_currencies: HashSet<enums::Currency>,
#[serde(deserialize_with = "deserialize_hashset")]
pub supported_connectors: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct OpenRouter {
pub dynamic_routing_enabled: bool,
pub static_routing_enabled: bool,
pub url: String,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct CloneConnectorAllowlistConfig {
#[serde(deserialize_with = "deserialize_merchant_ids")]
pub merchant_ids: HashSet<id_type::MerchantId>,
#[serde(deserialize_with = "deserialize_hashset")]
pub connector_names: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct Platform {
pub enabled: bool,
pub allow_connected_merchants: bool,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct ChatSettings {
pub enabled: bool,
pub hyperswitch_ai_host: String,
pub encryption_key: Secret<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Multitenancy {
pub tenants: TenantConfig,
pub enabled: bool,
pub global_tenant: GlobalTenant,
}
impl Multitenancy {
pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> {
&self.tenants.0
}
pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> {
self.tenants
.0
.values()
.map(|tenant| tenant.tenant_id.clone())
.collect()
}
pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> {
self.tenants.0.get(tenant_id)
}
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DecisionConfig {
pub base_url: String,
}
#[derive(Debug, Clone, Default)]
pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>);
impl TenantConfig {
/// # Panics
///
/// Panics if Failed to create event handler
pub async fn get_store_interface_map(
&self,
storage_impl: &app::StorageImpl,
conf: &configs::Settings,
cache_store: Arc<storage_impl::redis::RedisStore>,
testable: bool,
) -> HashMap<id_type::TenantId, Box<dyn app::StorageInterface>> {
#[allow(clippy::expect_used)]
let event_handler = conf
.events
.get_event_handler()
.await
.expect("Failed to create event handler");
futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async {
let store = Box::pin(AppState::get_store_interface(
storage_impl,
&event_handler,
conf,
tenant,
cache_store.clone(),
testable,
))
.await
.get_storage_interface();
(tenant_name.clone(), store)
}))
.await
.into_iter()
.collect()
}
/// # Panics
///
/// Panics if Failed to create event handler
pub async fn get_accounts_store_interface_map(
&self,
storage_impl: &app::StorageImpl,
conf: &configs::Settings,
cache_store: Arc<storage_impl::redis::RedisStore>,
testable: bool,
) -> HashMap<id_type::TenantId, Box<dyn app::AccountsStorageInterface>> {
#[allow(clippy::expect_used)]
let event_handler = conf
.events
.get_event_handler()
.await
.expect("Failed to create event handler");
futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async {
let store = Box::pin(AppState::get_store_interface(
storage_impl,
&event_handler,
conf,
tenant,
cache_store.clone(),
testable,
))
.await
.get_accounts_storage_interface();
(tenant_name.clone(), store)
}))
.await
.into_iter()
.collect()
}
#[cfg(feature = "olap")]
pub async fn get_pools_map(
&self,
analytics_config: &AnalyticsConfig,
) -> HashMap<id_type::TenantId, AnalyticsProvider> {
futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async {
(
tenant_name.clone(),
AnalyticsProvider::from_conf(analytics_config, tenant).await,
)
}))
.await
.into_iter()
.collect()
}
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct L2L3DataConfig {
pub enabled: bool,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct UnmaskedHeaders {
#[serde(deserialize_with = "deserialize_hashset")]
pub keys: HashSet<String>,
}
#[cfg(feature = "frm")]
#[derive(Debug, Deserialize, Clone, Default)]
pub struct Frm {
pub enabled: bool,
}
#[derive(Debug, Deserialize, Clone)]
pub struct KvConfig {
pub ttl: u32,
pub soft_kill: Option<bool>,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct KeyManagerConfig {
pub enabled: bool,
pub url: String,
#[cfg(feature = "keymanager_mtls")]
pub cert: Secret<String>,
#[cfg(feature = "keymanager_mtls")]
pub ca: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct GenericLink {
pub payment_method_collect: GenericLinkEnvConfig,
pub payout_link: GenericLinkEnvConfig,
}
#[derive(Debug, Deserialize, Clone)]
pub struct GenericLinkEnvConfig {
pub sdk_url: url::Url,
pub expiry: u32,
pub ui_config: GenericLinkEnvUiConfig,
#[serde(deserialize_with = "deserialize_hashmap")]
pub enabled_payment_methods: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>,
}
impl Default for GenericLinkEnvConfig {
fn default() -> Self {
Self {
#[allow(clippy::expect_used)]
sdk_url: url::Url::parse("http://localhost:9050/HyperLoader.js")
.expect("Failed to parse default SDK URL"),
expiry: 900,
ui_config: GenericLinkEnvUiConfig::default(),
enabled_payment_methods: HashMap::default(),
}
}
}
#[derive(Debug, Deserialize, Clone)]
pub struct GenericLinkEnvUiConfig {
pub logo: url::Url,
pub merchant_name: Secret<String>,
pub theme: String,
}
#[allow(clippy::panic)]
impl Default for GenericLinkEnvUiConfig {
fn default() -> Self {
Self {
#[allow(clippy::expect_used)]
logo: url::Url::parse("https://hyperswitch.io/favicon.ico")
.expect("Failed to parse default logo URL"),
merchant_name: Secret::new("HyperSwitch".to_string()),
theme: "#4285F4".to_string(),
}
}
}
#[derive(Debug, Deserialize, Clone)]
pub struct PaymentLink {
pub sdk_url: url::Url,
}
impl Default for PaymentLink {
fn default() -> Self {
Self {
#[allow(clippy::expect_used)]
sdk_url: url::Url::parse("https://beta.hyperswitch.io/v0/HyperLoader.js")
.expect("Failed to parse default SDK URL"),
}
}
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct ForexApi {
pub api_key: Secret<String>,
pub fallback_api_key: Secret<String>,
pub data_expiration_delay_in_seconds: u32,
pub redis_lock_timeout_in_seconds: u32,
pub redis_ttl_in_seconds: u32,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DefaultExchangeRates {
pub base_currency: String,
pub conversion: HashMap<String, Conversion>,
pub timestamp: i64,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct Conversion {
#[serde(with = "rust_decimal::serde::str")]
pub to_factor: Decimal,
#[serde(with = "rust_decimal::serde::str")]
pub from_factor: Decimal,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct ApplepayMerchantConfigs {
pub merchant_cert: Secret<String>,
pub merchant_cert_key: Secret<String>,
pub common_merchant_identifier: Secret<String>,
pub applepay_endpoint: String,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct MultipleApiVersionSupportedConnectors {
#[serde(deserialize_with = "deserialize_hashset")]
pub supported_connectors: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(transparent)]
pub struct TokenizationConfig(pub HashMap<String, PaymentMethodTokenFilter>);
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(transparent)]
pub struct TempLockerEnableConfig(pub HashMap<String, TempLockerEnablePaymentMethodFilter>);
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ConnectorCustomer {
#[cfg(feature = "payouts")]
#[serde(deserialize_with = "deserialize_hashset")]
pub payout_connector_list: HashSet<enums::PayoutConnectors>,
}
#[cfg(feature = "dummy_connector")]
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DummyConnector {
pub enabled: bool,
pub payment_ttl: i64,
pub payment_duration: u64,
pub payment_tolerance: u64,
pub payment_retrieve_duration: u64,
pub payment_retrieve_tolerance: u64,
pub payment_complete_duration: i64,
pub payment_complete_tolerance: i64,
pub refund_ttl: i64,
pub refund_duration: u64,
pub refund_tolerance: u64,
pub refund_retrieve_duration: u64,
pub refund_retrieve_tolerance: u64,
pub authorize_ttl: i64,
pub assets_base_url: String,
pub default_return_url: String,
pub slack_invite_url: String,
pub discord_invite_url: String,
}
#[derive(Debug, Deserialize, Clone)]
pub struct CorsSettings {
#[serde(default, deserialize_with = "deserialize_hashset")]
pub origins: HashSet<String>,
#[serde(default)]
pub wildcard_origin: bool,
pub max_age: usize,
#[serde(deserialize_with = "deserialize_hashset")]
pub allowed_methods: HashSet<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct AuthenticationProviders {
#[serde(deserialize_with = "deserialize_connector_list")]
pub click_to_pay: HashSet<enums::Connector>,
}
fn deserialize_connector_list<'a, D>(deserializer: D) -> Result<HashSet<enums::Connector>, D::Error>
where
D: serde::Deserializer<'a>,
{
use serde::de::Error;
#[derive(Deserialize)]
struct Wrapper {
connector_list: String,
}
let wrapper = Wrapper::deserialize(deserializer)?;
wrapper
.connector_list
.split(',')
.map(|s| s.trim().parse().map_err(D::Error::custom))
.collect()
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct NetworkTransactionIdSupportedConnectors {
#[serde(deserialize_with = "deserialize_hashset")]
pub connector_list: HashSet<enums::Connector>,
}
/// Connectors that support only dispute list API for syncing disputes with Hyperswitch
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ListDiputeSupportedConnectors {
#[serde(deserialize_with = "deserialize_hashset")]
pub connector_list: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct NetworkTokenizationSupportedCardNetworks {
#[serde(deserialize_with = "deserialize_hashset")]
pub card_networks: HashSet<enums::CardNetwork>,
}
#[derive(Debug, Deserialize, Clone)]
pub struct NetworkTokenizationService {
pub generate_token_url: url::Url,
pub fetch_token_url: url::Url,
pub token_service_api_key: Secret<String>,
pub public_key: Secret<String>,
pub private_key: Secret<String>,
pub key_id: String,
pub delete_token_url: url::Url,
pub check_token_status_url: url::Url,
pub webhook_source_verification_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct PaymentMethodTokenFilter {
#[serde(deserialize_with = "deserialize_hashset")]
pub payment_method: HashSet<diesel_models::enums::PaymentMethod>,
pub payment_method_type: Option<PaymentMethodTypeTokenFilter>,
pub long_lived_token: bool,
pub apple_pay_pre_decrypt_flow: Option<ApplePayPreDecryptFlow>,
pub google_pay_pre_decrypt_flow: Option<GooglePayPreDecryptFlow>,
pub flow: Option<PaymentFlow>,
}
#[derive(Debug, Deserialize, Clone, PartialEq)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum PaymentFlow {
Mandates,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum ApplePayPreDecryptFlow {
#[default]
ConnectorTokenization,
NetworkTokenization,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum GooglePayPreDecryptFlow {
#[default]
ConnectorTokenization,
NetworkTokenization,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct TempLockerEnablePaymentMethodFilter {
#[serde(deserialize_with = "deserialize_hashset")]
pub payment_method: HashSet<diesel_models::enums::PaymentMethod>,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(
deny_unknown_fields,
tag = "type",
content = "list",
rename_all = "snake_case"
)]
pub enum PaymentMethodTypeTokenFilter {
#[serde(deserialize_with = "deserialize_hashset")]
EnableOnly(HashSet<diesel_models::enums::PaymentMethodType>),
#[serde(deserialize_with = "deserialize_hashset")]
DisableOnly(HashSet<diesel_models::enums::PaymentMethodType>),
#[default]
AllAccepted,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(transparent)]
pub struct ConnectorFilters(pub HashMap<String, PaymentMethodFilters>);
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(transparent)]
pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCountryFlowFilter>);
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)]
#[serde(untagged)]
pub enum PaymentMethodFilterKey {
PaymentMethodType(enums::PaymentMethodType),
CardNetwork(enums::CardNetwork),
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct CurrencyCountryFlowFilter {
#[serde(deserialize_with = "deserialize_optional_hashset")]
pub currency: Option<HashSet<enums::Currency>>,
#[serde(deserialize_with = "deserialize_optional_hashset")]
pub country: Option<HashSet<enums::CountryAlpha2>>,
pub not_available_flows: Option<NotAvailableFlows>,
}
#[derive(Debug, Deserialize, Copy, Clone, Default)]
#[serde(default)]
pub struct NotAvailableFlows {
pub capture_method: Option<enums::CaptureMethod>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "v2", derive(Default))] // Configs are read from the config file in config/payout_required_fields.toml
pub struct PayoutRequiredFields(pub HashMap<enums::PaymentMethod, PaymentMethodType>);
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(default)]
pub struct Secrets {
pub jwt_secret: Secret<String>,
pub admin_api_key: Secret<String>,
pub master_enc_key: Secret<String>,
}
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(default)]
pub struct FallbackMerchantIds {
#[serde(deserialize_with = "deserialize_merchant_ids")]
pub merchant_ids: HashSet<id_type::MerchantId>,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct UserSettings {
pub password_validity_in_days: u16,
pub two_factor_auth_expiry_in_secs: i64,
pub totp_issuer_name: String,
pub base_url: String,
pub force_two_factor_auth: bool,
pub force_cookies: bool,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct OidcSettings {
pub key: HashMap<String, OidcKey>,
pub client: HashMap<String, OidcClient>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct OidcKey {
pub kid: String,
pub private_key: Secret<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct OidcClient {
pub client_id: String,
pub client_secret: Secret<String>,
pub redirect_uri: String,
}
impl OidcSettings {
pub fn get_client(&self, client_id: &str) -> Option<&OidcClient> {
self.client.values().find(|c| c.client_id == client_id)
}
pub fn get_signing_key(&self) -> Option<&OidcKey> {
self.key.values().next()
}
pub fn get_all_keys(&self) -> Vec<&OidcKey> {
self.key.values().collect()
}
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Locker {
pub host: String,
pub mock_locker: bool,
pub locker_signing_key_id: String,
pub locker_enabled: bool,
pub ttl_for_storage_in_secs: i64,
pub decryption_scheme: DecryptionScheme,
}
impl Locker {
pub fn get_host(&self, endpoint_path: &str) -> String {
let mut url = self.host.clone();
url.push_str(endpoint_path);
url
}
}
#[derive(Debug, Deserialize, Clone, Default)]
pub enum DecryptionScheme {
#[default]
#[serde(rename = "RSA-OAEP")]
RsaOaep,
#[serde(rename = "RSA-OAEP-256")]
RsaOaep256,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Refund {
pub max_attempts: usize,
pub max_age: i64,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct EphemeralConfig {
pub validity: i64,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct Jwekey {
pub vault_encryption_key: Secret<String>,
pub vault_private_key: Secret<String>,
pub tunnel_private_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Server {
pub port: u16,
pub workers: usize,
pub host: String,
pub request_body_limit: usize,
pub shutdown_timeout: u64,
#[cfg(feature = "tls")]
pub tls: Option<ServerTls>,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Database {
pub username: String,
pub password: Secret<String>,
pub host: String,
pub port: u16,
pub dbname: String,
pub pool_size: u32,
pub connection_timeout: u64,
pub queue_strategy: QueueStrategy,
pub min_idle: Option<u32>,
pub max_lifetime: Option<u64>,
}
impl From<Database> for storage_impl::config::Database {
fn from(val: Database) -> Self {
Self {
username: val.username,
password: val.password,
host: val.host,
port: val.port,
dbname: val.dbname,
pool_size: val.pool_size,
connection_timeout: val.connection_timeout,
queue_strategy: val.queue_strategy,
min_idle: val.min_idle,
max_lifetime: val.max_lifetime,
}
}
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct SupportedConnectors {
pub wallets: Vec<String>,
}
#[cfg(feature = "kv_store")]
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct DrainerSettings {
pub stream_name: String,
pub num_partitions: u8,
pub max_read_count: u64,
pub shutdown_interval: u32, // in milliseconds
pub loop_interval: u32, // in milliseconds
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct MerchantIdAuthSettings {
pub merchant_id_auth_enabled: bool,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct ProxyStatusMapping {
pub proxy_connector_http_status_code: bool,
}
impl ProxyStatusMapping {
pub fn extract_connector_http_status_code(
&self,
response_headers: &[(String, Maskable<String>)],
) -> Option<actix_web::http::StatusCode> {
self.proxy_connector_http_status_code
.then_some(response_headers)
.and_then(|headers| {
headers
.iter()
.find(|(key, _)| key.as_str() == headers::X_CONNECTOR_HTTP_STATUS_CODE)
})
.and_then(|(_, value)| {
value
.clone()
.into_inner()
.parse::<u16>()
.map_err(|err| {
logger::error!(
"Failed to parse connector_http_status_code from header: {:?}",
err
);
})
.ok()
})
.and_then(|code| {
actix_web::http::StatusCode::from_u16(code)
.map_err(|err| {
logger::error!(
"Invalid HTTP status code parsed from connector_http_status_code: {:?}",
err
);
})
.ok()
})
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct TraceHeaderConfig {
pub header_name: String,
pub id_reuse_strategy: router_env::IdReuse,
}
impl Default for TraceHeaderConfig {
fn default() -> Self {
Self {
header_name: common_utils::consts::X_REQUEST_ID.to_string(),
id_reuse_strategy: router_env::IdReuse::IgnoreIncoming,
}
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct WebhooksSettings {
pub outgoing_enabled: bool,
pub ignore_error: WebhookIgnoreErrorSettings,
pub redis_lock_expiry_seconds: u32,
}
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(default)]
pub struct WebhookIgnoreErrorSettings {
pub event_type: Option<bool>,
pub payment_not_found: Option<bool>,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct ApiKeys {
/// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating
/// hashes of API keys
pub hash_key: Secret<String>,
// Specifies the number of days before API key expiry when email reminders should be sent
#[cfg(feature = "email")]
pub expiry_reminder_days: Vec<u8>,
#[cfg(feature = "partial-auth")]
pub checksum_auth_context: Secret<String>,
#[cfg(feature = "partial-auth")]
pub checksum_auth_key: Secret<String>,
#[cfg(feature = "partial-auth")]
pub enable_partial_auth: bool,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DelayedSessionConfig {
#[serde(deserialize_with = "deserialize_hashset")]
pub connectors_with_delayed_session_response: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct WebhookSourceVerificationCall {
#[serde(deserialize_with = "deserialize_hashset")]
pub connectors_with_webhook_source_verification_call: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct BillingConnectorPaymentsSyncCall {
#[serde(deserialize_with = "deserialize_hashset")]
pub billing_connectors_which_require_payment_sync: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct BillingConnectorInvoiceSyncCall {
#[serde(deserialize_with = "deserialize_hashset")]
pub billing_connectors_which_requires_invoice_sync_call: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ApplePayDecryptConfig {
pub apple_pay_ppc: Secret<String>,
pub apple_pay_ppc_key: Secret<String>,
pub apple_pay_merchant_cert: Secret<String>,
pub apple_pay_merchant_cert_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct PazeDecryptConfig {
pub paze_private_key: Secret<String>,
pub paze_private_key_passphrase: Secret<String>,
}
#[derive(Debug, Deserialize, Clone)]
pub struct GooglePayDecryptConfig {
pub google_pay_root_signing_keys: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct LockerBasedRecipientConnectorList {
#[serde(deserialize_with = "deserialize_hashset")]
pub connector_list: HashSet<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ConnectorRequestReferenceIdConfig {
pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<id_type::MerchantId>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct UserAuthMethodSettings {
pub encryption_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct NetworkTokenizationSupportedConnectors {
#[serde(deserialize_with = "deserialize_hashset")]
pub connector_list: HashSet<enums::Connector>,
}
impl Settings<SecuredSecret> {
pub fn new() -> ApplicationResult<Self> {
Self::with_config_path(None)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/configs/secrets_transformers.rs | crates/router/src/configs/secrets_transformers.rs | use common_utils::{errors::CustomResult, ext_traits::AsyncExt};
use hyperswitch_interfaces::secrets_interface::{
secret_handler::SecretsHandler,
secret_state::{RawSecret, SecretStateContainer, SecuredSecret},
SecretManagementInterface, SecretsManagementError,
};
use crate::settings::{self, Settings};
#[async_trait::async_trait]
impl SecretsHandler for settings::Database {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let db = value.get_inner();
let db_password = secret_management_client
.get_secret(db.password.clone())
.await?;
Ok(value.transition_state(|db| Self {
password: db_password,
..db
}))
}
}
#[async_trait::async_trait]
impl SecretsHandler for settings::Jwekey {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let jwekey = value.get_inner();
let (vault_encryption_key, vault_private_key, tunnel_private_key) = tokio::try_join!(
secret_management_client.get_secret(jwekey.vault_encryption_key.clone()),
secret_management_client.get_secret(jwekey.vault_private_key.clone()),
secret_management_client.get_secret(jwekey.tunnel_private_key.clone())
)?;
Ok(value.transition_state(|_| Self {
vault_encryption_key,
vault_private_key,
tunnel_private_key,
}))
}
}
#[cfg(feature = "olap")]
#[async_trait::async_trait]
impl SecretsHandler for settings::ConnectorOnboarding {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let onboarding_config = &value.get_inner().paypal;
let (client_id, client_secret, partner_id) = tokio::try_join!(
secret_management_client.get_secret(onboarding_config.client_id.clone()),
secret_management_client.get_secret(onboarding_config.client_secret.clone()),
secret_management_client.get_secret(onboarding_config.partner_id.clone())
)?;
Ok(value.transition_state(|onboarding_config| Self {
paypal: settings::PayPalOnboarding {
client_id,
client_secret,
partner_id,
..onboarding_config.paypal
},
}))
}
}
#[async_trait::async_trait]
impl SecretsHandler for settings::ForexApi {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let forex_api = value.get_inner();
let (api_key, fallback_api_key) = tokio::try_join!(
secret_management_client.get_secret(forex_api.api_key.clone()),
secret_management_client.get_secret(forex_api.fallback_api_key.clone()),
)?;
Ok(value.transition_state(|forex_api| Self {
api_key,
fallback_api_key,
..forex_api
}))
}
}
#[async_trait::async_trait]
impl SecretsHandler for settings::ApiKeys {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let api_keys = value.get_inner();
let hash_key = secret_management_client
.get_secret(api_keys.hash_key.clone())
.await?;
#[cfg(feature = "email")]
let expiry_reminder_days = api_keys.expiry_reminder_days.clone();
#[cfg(feature = "partial-auth")]
let enable_partial_auth = api_keys.enable_partial_auth;
#[cfg(feature = "partial-auth")]
let (checksum_auth_context, checksum_auth_key) = {
if enable_partial_auth {
let checksum_auth_context = secret_management_client
.get_secret(api_keys.checksum_auth_context.clone())
.await?;
let checksum_auth_key = secret_management_client
.get_secret(api_keys.checksum_auth_key.clone())
.await?;
(checksum_auth_context, checksum_auth_key)
} else {
(String::new().into(), String::new().into())
}
};
Ok(value.transition_state(|_| Self {
hash_key,
#[cfg(feature = "email")]
expiry_reminder_days,
#[cfg(feature = "partial-auth")]
checksum_auth_key,
#[cfg(feature = "partial-auth")]
checksum_auth_context,
#[cfg(feature = "partial-auth")]
enable_partial_auth,
}))
}
}
#[async_trait::async_trait]
impl SecretsHandler for settings::ApplePayDecryptConfig {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let applepay_decrypt_keys = value.get_inner();
let (
apple_pay_ppc,
apple_pay_ppc_key,
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
) = tokio::try_join!(
secret_management_client.get_secret(applepay_decrypt_keys.apple_pay_ppc.clone()),
secret_management_client.get_secret(applepay_decrypt_keys.apple_pay_ppc_key.clone()),
secret_management_client
.get_secret(applepay_decrypt_keys.apple_pay_merchant_cert.clone()),
secret_management_client
.get_secret(applepay_decrypt_keys.apple_pay_merchant_cert_key.clone()),
)?;
Ok(value.transition_state(|_| Self {
apple_pay_ppc,
apple_pay_ppc_key,
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
}))
}
}
#[async_trait::async_trait]
impl SecretsHandler for settings::PazeDecryptConfig {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let paze_decrypt_keys = value.get_inner();
let (paze_private_key, paze_private_key_passphrase) = tokio::try_join!(
secret_management_client.get_secret(paze_decrypt_keys.paze_private_key.clone()),
secret_management_client
.get_secret(paze_decrypt_keys.paze_private_key_passphrase.clone()),
)?;
Ok(value.transition_state(|_| Self {
paze_private_key,
paze_private_key_passphrase,
}))
}
}
#[async_trait::async_trait]
impl SecretsHandler for settings::ApplepayMerchantConfigs {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let applepay_merchant_configs = value.get_inner();
let (merchant_cert, merchant_cert_key, common_merchant_identifier) = tokio::try_join!(
secret_management_client.get_secret(applepay_merchant_configs.merchant_cert.clone()),
secret_management_client
.get_secret(applepay_merchant_configs.merchant_cert_key.clone()),
secret_management_client
.get_secret(applepay_merchant_configs.common_merchant_identifier.clone()),
)?;
Ok(value.transition_state(|applepay_merchant_configs| Self {
merchant_cert,
merchant_cert_key,
common_merchant_identifier,
..applepay_merchant_configs
}))
}
}
#[async_trait::async_trait]
impl SecretsHandler for settings::KeyManagerConfig {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
_secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
#[cfg(feature = "keymanager_mtls")]
let keyconfig = value.get_inner();
#[cfg(feature = "keymanager_mtls")]
let ca = if keyconfig.enabled {
_secret_management_client
.get_secret(keyconfig.ca.clone())
.await?
} else {
keyconfig.ca.clone()
};
#[cfg(feature = "keymanager_mtls")]
let cert = if keyconfig.enabled {
_secret_management_client
.get_secret(keyconfig.cert.clone())
.await?
} else {
keyconfig.ca.clone()
};
Ok(value.transition_state(|keyconfig| Self {
#[cfg(feature = "keymanager_mtls")]
ca,
#[cfg(feature = "keymanager_mtls")]
cert,
..keyconfig
}))
}
}
#[async_trait::async_trait]
impl SecretsHandler for settings::Secrets {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let secrets = value.get_inner();
let (jwt_secret, admin_api_key, master_enc_key) = tokio::try_join!(
secret_management_client.get_secret(secrets.jwt_secret.clone()),
secret_management_client.get_secret(secrets.admin_api_key.clone()),
secret_management_client.get_secret(secrets.master_enc_key.clone())
)?;
Ok(value.transition_state(|_| Self {
jwt_secret,
admin_api_key,
master_enc_key,
}))
}
}
#[async_trait::async_trait]
impl SecretsHandler for settings::UserAuthMethodSettings {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let user_auth_methods = value.get_inner();
let encryption_key = secret_management_client
.get_secret(user_auth_methods.encryption_key.clone())
.await?;
Ok(value.transition_state(|_| Self { encryption_key }))
}
}
#[async_trait::async_trait]
impl SecretsHandler for settings::ChatSettings {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let chat_settings = value.get_inner();
let encryption_key = if chat_settings.enabled {
secret_management_client
.get_secret(chat_settings.encryption_key.clone())
.await?
} else {
chat_settings.encryption_key.clone()
};
Ok(value.transition_state(|chat_settings| Self {
encryption_key,
..chat_settings
}))
}
}
#[async_trait::async_trait]
impl SecretsHandler for settings::NetworkTokenizationService {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let network_tokenization = value.get_inner();
let token_service_api_key = secret_management_client
.get_secret(network_tokenization.token_service_api_key.clone())
.await?;
let public_key = secret_management_client
.get_secret(network_tokenization.public_key.clone())
.await?;
let private_key = secret_management_client
.get_secret(network_tokenization.private_key.clone())
.await?;
let webhook_source_verification_key = secret_management_client
.get_secret(network_tokenization.webhook_source_verification_key.clone())
.await?;
Ok(value.transition_state(|network_tokenization| Self {
public_key,
private_key,
token_service_api_key,
webhook_source_verification_key,
..network_tokenization
}))
}
}
#[async_trait::async_trait]
impl SecretsHandler for settings::OidcSettings {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let oidc_settings = value.get_inner();
let mut decrypted_keys = std::collections::HashMap::new();
for (key_id, oidc_key) in &oidc_settings.key {
let private_key = secret_management_client
.get_secret(oidc_key.private_key.clone())
.await?;
decrypted_keys.insert(
key_id.clone(),
settings::OidcKey {
kid: oidc_key.kid.clone(),
private_key,
},
);
}
let mut decrypted_clients = std::collections::HashMap::new();
for (client_key, oidc_client) in &oidc_settings.client {
let client_secret = secret_management_client
.get_secret(oidc_client.client_secret.clone())
.await?;
decrypted_clients.insert(
client_key.clone(),
settings::OidcClient {
client_id: oidc_client.client_id.clone(),
client_secret,
redirect_uri: oidc_client.redirect_uri.clone(),
},
);
}
Ok(value.transition_state(|_| Self {
key: decrypted_keys,
client: decrypted_clients,
}))
}
}
/// # Panics
///
/// Will panic even if kms decryption fails for at least one field
pub(crate) async fn fetch_raw_secrets(
conf: Settings<SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> Settings<RawSecret> {
#[allow(clippy::expect_used)]
let master_database =
settings::Database::convert_to_raw_secret(conf.master_database, secret_management_client)
.await
.expect("Failed to decrypt master database configuration");
#[cfg(feature = "olap")]
#[allow(clippy::expect_used)]
let analytics =
analytics::AnalyticsConfig::convert_to_raw_secret(conf.analytics, secret_management_client)
.await
.expect("Failed to decrypt analytics configuration");
#[cfg(feature = "olap")]
#[allow(clippy::expect_used)]
let replica_database =
settings::Database::convert_to_raw_secret(conf.replica_database, secret_management_client)
.await
.expect("Failed to decrypt replica database configuration");
#[allow(clippy::expect_used)]
let secrets = settings::Secrets::convert_to_raw_secret(conf.secrets, secret_management_client)
.await
.expect("Failed to decrypt secrets");
#[allow(clippy::expect_used)]
let forex_api =
settings::ForexApi::convert_to_raw_secret(conf.forex_api, secret_management_client)
.await
.expect("Failed to decrypt forex api configs");
#[allow(clippy::expect_used)]
let jwekey = settings::Jwekey::convert_to_raw_secret(conf.jwekey, secret_management_client)
.await
.expect("Failed to decrypt jwekey configs");
#[allow(clippy::expect_used)]
let api_keys =
settings::ApiKeys::convert_to_raw_secret(conf.api_keys, secret_management_client)
.await
.expect("Failed to decrypt api_keys configs");
#[cfg(feature = "olap")]
#[allow(clippy::expect_used)]
let connector_onboarding = settings::ConnectorOnboarding::convert_to_raw_secret(
conf.connector_onboarding,
secret_management_client,
)
.await
.expect("Failed to decrypt connector_onboarding configs");
#[allow(clippy::expect_used)]
let applepay_decrypt_keys = settings::ApplePayDecryptConfig::convert_to_raw_secret(
conf.applepay_decrypt_keys,
secret_management_client,
)
.await
.expect("Failed to decrypt applepay decrypt configs");
#[allow(clippy::expect_used)]
let paze_decrypt_keys = if let Some(paze_keys) = conf.paze_decrypt_keys {
Some(
settings::PazeDecryptConfig::convert_to_raw_secret(paze_keys, secret_management_client)
.await
.expect("Failed to decrypt paze decrypt configs"),
)
} else {
None
};
#[allow(clippy::expect_used)]
let applepay_merchant_configs = settings::ApplepayMerchantConfigs::convert_to_raw_secret(
conf.applepay_merchant_configs,
secret_management_client,
)
.await
.expect("Failed to decrypt applepay merchant configs");
#[allow(clippy::expect_used)]
let payment_method_auth = settings::PaymentMethodAuth::convert_to_raw_secret(
conf.payment_method_auth,
secret_management_client,
)
.await
.expect("Failed to decrypt payment method auth configs");
#[allow(clippy::expect_used)]
let key_manager = settings::KeyManagerConfig::convert_to_raw_secret(
conf.key_manager,
secret_management_client,
)
.await
.expect("Failed to decrypt keymanager configs");
#[allow(clippy::expect_used)]
let user_auth_methods = settings::UserAuthMethodSettings::convert_to_raw_secret(
conf.user_auth_methods,
secret_management_client,
)
.await
.expect("Failed to decrypt user_auth_methods configs");
#[allow(clippy::expect_used)]
let network_tokenization_service = conf
.network_tokenization_service
.async_map(|network_tokenization_service| async {
settings::NetworkTokenizationService::convert_to_raw_secret(
network_tokenization_service,
secret_management_client,
)
.await
.expect("Failed to decrypt network tokenization service configs")
})
.await;
#[allow(clippy::expect_used)]
let chat = settings::ChatSettings::convert_to_raw_secret(conf.chat, secret_management_client)
.await
.expect("Failed to decrypt chat configs");
#[allow(clippy::expect_used)]
let superposition =
external_services::superposition::SuperpositionClientConfig::convert_to_raw_secret(
conf.superposition,
secret_management_client,
)
.await
.expect("Failed to decrypt superposition config");
#[allow(clippy::expect_used)]
let oidc = settings::OidcSettings::convert_to_raw_secret(conf.oidc, secret_management_client)
.await
.expect("Failed to decrypt oidc configs");
Settings {
server: conf.server,
application_source: conf.application_source,
chat,
master_database,
redis: conf.redis,
log: conf.log,
#[cfg(feature = "kv_store")]
drainer: conf.drainer,
encryption_management: conf.encryption_management,
secrets_management: conf.secrets_management,
proxy: conf.proxy,
env: conf.env,
key_manager,
#[cfg(feature = "olap")]
replica_database,
secrets,
fallback_merchant_ids_api_key_auth: conf.fallback_merchant_ids_api_key_auth,
locker: conf.locker,
connectors: conf.connectors,
forex_api,
refund: conf.refund,
eph_key: conf.eph_key,
scheduler: conf.scheduler,
jwekey,
webhooks: conf.webhooks,
pm_filters: conf.pm_filters,
payout_method_filters: conf.payout_method_filters,
bank_config: conf.bank_config,
api_keys,
file_storage: conf.file_storage,
tokenization: conf.tokenization,
connector_customer: conf.connector_customer,
#[cfg(feature = "dummy_connector")]
dummy_connector: conf.dummy_connector,
#[cfg(feature = "email")]
email: conf.email,
user: conf.user,
oidc,
mandates: conf.mandates,
zero_mandates: conf.zero_mandates,
network_transaction_id_supported_connectors: conf
.network_transaction_id_supported_connectors,
list_dispute_supported_connectors: conf.list_dispute_supported_connectors,
required_fields: conf.required_fields,
delayed_session_response: conf.delayed_session_response,
webhook_source_verification_call: conf.webhook_source_verification_call,
billing_connectors_payment_sync: conf.billing_connectors_payment_sync,
billing_connectors_invoice_sync: conf.billing_connectors_invoice_sync,
payment_method_auth,
connector_request_reference_id_config: conf.connector_request_reference_id_config,
#[cfg(feature = "payouts")]
payouts: conf.payouts,
applepay_decrypt_keys,
paze_decrypt_keys,
google_pay_decrypt_keys: conf.google_pay_decrypt_keys,
multiple_api_version_supported_connectors: conf.multiple_api_version_supported_connectors,
applepay_merchant_configs,
lock_settings: conf.lock_settings,
temp_locker_enable_config: conf.temp_locker_enable_config,
generic_link: conf.generic_link,
payment_link: conf.payment_link,
#[cfg(feature = "olap")]
analytics,
#[cfg(feature = "olap")]
opensearch: conf.opensearch,
#[cfg(feature = "kv_store")]
kv_config: conf.kv_config,
#[cfg(feature = "frm")]
frm: conf.frm,
#[cfg(feature = "olap")]
report_download_config: conf.report_download_config,
events: conf.events,
#[cfg(feature = "olap")]
connector_onboarding,
cors: conf.cors,
unmasked_headers: conf.unmasked_headers,
saved_payment_methods: conf.saved_payment_methods,
multitenancy: conf.multitenancy,
user_auth_methods,
decision: conf.decision,
locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors,
grpc_client: conf.grpc_client,
crm: conf.crm,
#[cfg(feature = "v2")]
cell_information: conf.cell_information,
network_tokenization_supported_card_networks: conf
.network_tokenization_supported_card_networks,
network_tokenization_service,
network_tokenization_supported_connectors: conf.network_tokenization_supported_connectors,
theme: conf.theme,
platform: conf.platform,
l2_l3_data_config: conf.l2_l3_data_config,
preprocessing_flow_config: conf.preprocessing_flow_config.clone(),
authentication_providers: conf.authentication_providers,
open_router: conf.open_router,
#[cfg(feature = "v2")]
revenue_recovery: conf.revenue_recovery,
debit_routing_config: conf.debit_routing_config,
clone_connector_allowlist: conf.clone_connector_allowlist,
merchant_id_auth: conf.merchant_id_auth,
internal_merchant_id_profile_id_auth: conf.internal_merchant_id_profile_id_auth,
infra_values: conf.infra_values,
enhancement: conf.enhancement,
proxy_status_mapping: conf.proxy_status_mapping,
trace_header: conf.trace_header,
internal_services: conf.internal_services,
superposition,
comparison_service: conf.comparison_service,
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/configs/defaults.rs | crates/router/src/configs/defaults.rs | use std::collections::HashSet;
#[cfg(feature = "payouts")]
pub mod payout_required_fields;
impl Default for super::settings::Server {
fn default() -> Self {
Self {
port: 8080,
workers: num_cpus::get_physical(),
host: "localhost".into(),
request_body_limit: 16 * 1024, // POST request body is limited to 16KiB
shutdown_timeout: 30,
#[cfg(feature = "tls")]
tls: None,
}
}
}
impl Default for super::settings::CorsSettings {
fn default() -> Self {
Self {
origins: HashSet::from_iter(["http://localhost:8080".to_string()]),
allowed_methods: HashSet::from_iter(
["GET", "PUT", "POST", "DELETE"]
.into_iter()
.map(ToString::to_string),
),
wildcard_origin: false,
max_age: 30,
}
}
}
impl Default for super::settings::Database {
fn default() -> Self {
Self {
username: String::new(),
password: String::new().into(),
host: "localhost".into(),
port: 5432,
dbname: String::new(),
pool_size: 5,
connection_timeout: 10,
queue_strategy: Default::default(),
min_idle: None,
max_lifetime: None,
}
}
}
impl Default for super::settings::Locker {
fn default() -> Self {
Self {
host: "localhost".into(),
mock_locker: true,
locker_signing_key_id: "1".into(),
//true or false
locker_enabled: true,
//Time to live for storage entries in locker
ttl_for_storage_in_secs: 60 * 60 * 24 * 365 * 7,
decryption_scheme: Default::default(),
}
}
}
impl Default for super::settings::SupportedConnectors {
fn default() -> Self {
Self {
wallets: ["klarna", "braintree"].map(Into::into).into(),
/* cards: [
"adyen",
"authorizedotnet",
"braintree",
"checkout",
"cybersource",
"fiserv",
"rapyd",
"stripe",
]
.map(Into::into)
.into(), */
}
}
}
impl Default for super::settings::Refund {
fn default() -> Self {
Self {
max_attempts: 10,
max_age: 365,
}
}
}
impl Default for super::settings::EphemeralConfig {
fn default() -> Self {
Self { validity: 1 }
}
}
#[cfg(feature = "kv_store")]
impl Default for super::settings::DrainerSettings {
fn default() -> Self {
Self {
stream_name: "DRAINER_STREAM".into(),
num_partitions: 64,
max_read_count: 100,
shutdown_interval: 1000,
loop_interval: 100,
}
}
}
#[cfg(feature = "kv_store")]
impl Default for super::settings::KvConfig {
fn default() -> Self {
Self {
ttl: 900,
soft_kill: Some(false),
}
}
}
#[allow(clippy::derivable_impls)]
impl Default for super::settings::ApiKeys {
fn default() -> Self {
Self {
// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating
// hashes of API keys
hash_key: String::new().into(),
// Specifies the number of days before API key expiry when email reminders should be sent
#[cfg(feature = "email")]
expiry_reminder_days: vec![7, 3, 1],
// Hex-encoded key used for calculating checksum for partial auth
#[cfg(feature = "partial-auth")]
checksum_auth_key: String::new().into(),
// context used for blake3
#[cfg(feature = "partial-auth")]
checksum_auth_context: String::new().into(),
#[cfg(feature = "partial-auth")]
enable_partial_auth: false,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/configs/validations.rs | crates/router/src/configs/validations.rs | use common_utils::ext_traits::ConfigExt;
use masking::PeekInterface;
use storage_impl::errors::ApplicationError;
impl super::settings::Secrets {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(self.jwt_secret.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"JWT secret must not be empty".into(),
))
})?;
when(self.admin_api_key.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"admin API key must not be empty".into(),
))
})?;
when(self.master_enc_key.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Master encryption key must not be empty".into(),
))
})
}
}
impl super::settings::Locker {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(!self.mock_locker && self.host.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"locker host must not be empty when mock locker is disabled".into(),
))
})
}
}
impl super::settings::Server {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(self.host.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"server host must not be empty".into(),
))
})?;
when(self.workers == 0, || {
Err(ApplicationError::InvalidConfigurationValueError(
"number of workers must be greater than 0".into(),
))
})
}
}
impl super::settings::Database {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(self.host.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"database host must not be empty".into(),
))
})?;
when(self.dbname.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"database name must not be empty".into(),
))
})?;
when(self.username.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"database user username must not be empty".into(),
))
})?;
when(self.password.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"database user password must not be empty".into(),
))
})
}
}
impl super::settings::SupportedConnectors {
pub fn validate(&self) -> Result<(), ApplicationError> {
common_utils::fp_utils::when(self.wallets.is_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"list of connectors supporting wallets must not be empty".into(),
))
})
}
}
impl super::settings::CorsSettings {
pub fn validate(&self) -> Result<(), ApplicationError> {
common_utils::fp_utils::when(self.wildcard_origin && !self.origins.is_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Allowed Origins must be empty when wildcard origin is true".to_string(),
))
})?;
common_utils::fp_utils::when(!self.wildcard_origin && self.origins.is_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Allowed origins must not be empty. Please either enable wildcard origin or provide Allowed Origin".to_string(),
))
})
}
}
#[cfg(feature = "kv_store")]
impl super::settings::DrainerSettings {
pub fn validate(&self) -> Result<(), ApplicationError> {
common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"drainer stream name must not be empty".into(),
))
})
}
}
impl super::settings::ApiKeys {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(self.hash_key.peek().is_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"API key hashing key must not be empty".into(),
))
})?;
#[cfg(feature = "email")]
when(self.expiry_reminder_days.is_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"API key expiry reminder days must not be empty".into(),
))
})?;
Ok(())
}
}
impl super::settings::LockSettings {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(self.redis_lock_expiry_seconds.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"redis_lock_expiry_seconds must not be empty or 0".into(),
))
})?;
when(
self.delay_between_retries_in_milliseconds
.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"delay_between_retries_in_milliseconds must not be empty or 0".into(),
))
},
)?;
when(self.lock_retries.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"lock_retries must not be empty or 0".into(),
))
})
}
}
impl super::settings::WebhooksSettings {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(self.redis_lock_expiry_seconds.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"redis_lock_expiry_seconds must not be empty or 0".into(),
))
})
}
}
impl super::settings::GenericLinkEnvConfig {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(self.expiry == 0, || {
Err(ApplicationError::InvalidConfigurationValueError(
"link's expiry should not be 0".into(),
))
})
}
}
#[cfg(feature = "v2")]
impl super::settings::CellInformation {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::{fp_utils::when, id_type};
when(self == &Self::default(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"CellId cannot be set to a default".into(),
))
})
}
}
impl super::settings::NetworkTokenizationService {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(self.token_service_api_key.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"token_service_api_key must not be empty".into(),
))
})?;
when(self.public_key.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"public_key must not be empty".into(),
))
})?;
when(self.key_id.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"key_id must not be empty".into(),
))
})?;
when(self.private_key.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"private_key must not be empty".into(),
))
})?;
when(
self.webhook_source_verification_key.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"webhook_source_verification_key must not be empty".into(),
))
},
)
}
}
impl super::settings::PazeDecryptConfig {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(self.paze_private_key.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"paze_private_key must not be empty".into(),
))
})?;
when(
self.paze_private_key_passphrase.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"paze_private_key_passphrase must not be empty".into(),
))
},
)
}
}
impl super::settings::GooglePayDecryptConfig {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(
self.google_pay_root_signing_keys.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"google_pay_root_signing_keys must not be empty".into(),
))
},
)
}
}
impl super::settings::KeyManagerConfig {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
#[cfg(feature = "keymanager_mtls")]
when(
self.enabled && (self.ca.is_default_or_empty() || self.cert.is_default_or_empty()),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"Invalid CA or Certificate for Keymanager.".into(),
))
},
)?;
when(self.enabled && self.url.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Invalid URL for Keymanager".into(),
))
})
}
}
impl super::settings::Platform {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(!self.enabled && self.allow_connected_merchants, || {
Err(ApplicationError::InvalidConfigurationValueError(
"platform.allow_connected_merchants cannot be true when platform.enabled is false"
.into(),
))
})
}
}
impl super::settings::OpenRouter {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(
(self.dynamic_routing_enabled || self.static_routing_enabled)
&& self.url.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"OpenRouter base URL must not be empty when it is enabled".into(),
))
},
)
}
}
impl super::settings::ChatSettings {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(self.enabled && self.hyperswitch_ai_host.is_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"hyperswitch ai host must be set if chat is enabled".into(),
))
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/configs/defaults/payout_required_fields.rs | crates/router/src/configs/defaults/payout_required_fields.rs | use std::collections::HashMap;
use api_models::{
enums::{
CountryAlpha2, FieldType,
PaymentMethod::{BankRedirect, BankTransfer, Card, Wallet},
PaymentMethodType, PayoutConnectors,
},
payment_methods::RequiredFieldInfo,
};
use crate::settings::{
ConnectorFields, PaymentMethodType as PaymentMethodTypeInfo, PayoutRequiredFields,
RequiredFieldFinal,
};
#[cfg(feature = "v1")]
impl Default for PayoutRequiredFields {
fn default() -> Self {
Self(HashMap::from([
(
Card,
PaymentMethodTypeInfo(HashMap::from([
// Adyen
get_connector_payment_method_type_fields(
PayoutConnectors::Adyenplatform,
PaymentMethodType::Debit,
),
get_connector_payment_method_type_fields(
PayoutConnectors::Adyenplatform,
PaymentMethodType::Credit,
),
])),
),
(
BankTransfer,
PaymentMethodTypeInfo(HashMap::from([
// Adyen
get_connector_payment_method_type_fields(
PayoutConnectors::Adyenplatform,
PaymentMethodType::SepaBankTransfer,
),
// Ebanx
get_connector_payment_method_type_fields(
PayoutConnectors::Ebanx,
PaymentMethodType::Pix,
),
// Wise
get_connector_payment_method_type_fields(
PayoutConnectors::Wise,
PaymentMethodType::Bacs,
),
])),
),
(
Wallet,
PaymentMethodTypeInfo(HashMap::from([
// Adyen
get_connector_payment_method_type_fields(
PayoutConnectors::Adyenplatform,
PaymentMethodType::Paypal,
),
])),
),
(
// TODO: Refactor to support multiple connectors, each having its own set of required fields.
BankRedirect,
PaymentMethodTypeInfo(HashMap::from([{
let (pmt, mut gidadat_fields) = get_connector_payment_method_type_fields(
PayoutConnectors::Gigadat,
PaymentMethodType::Interac,
);
let (_, loonio_fields) = get_connector_payment_method_type_fields(
PayoutConnectors::Loonio,
PaymentMethodType::Interac,
);
gidadat_fields.fields.extend(loonio_fields.fields);
(pmt, gidadat_fields)
}])),
),
]))
}
}
fn get_billing_details_for_payment_method(
connector: PayoutConnectors,
payment_method_type: PaymentMethodType,
) -> HashMap<String, RequiredFieldInfo> {
match connector {
PayoutConnectors::Adyenplatform => {
let mut fields = HashMap::from([
(
"billing.address.line1".to_string(),
RequiredFieldInfo {
required_field: "billing.address.line1".to_string(),
display_name: "billing_address_line1".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.line2".to_string(),
RequiredFieldInfo {
required_field: "billing.address.line2".to_string(),
display_name: "billing_address_line2".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.city".to_string(),
RequiredFieldInfo {
required_field: "billing.address.city".to_string(),
display_name: "billing_address_city".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.country".to_string(),
RequiredFieldInfo {
required_field: "billing.address.country".to_string(),
display_name: "billing_address_country".to_string(),
field_type: FieldType::UserAddressCountry {
options: get_countries_for_connector(connector)
.iter()
.map(|country| country.to_string())
.collect::<Vec<String>>(),
},
value: None,
},
),
]);
// Add first_name for bank payouts only
if payment_method_type == PaymentMethodType::SepaBankTransfer {
fields.insert(
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "billing.address.first_name".to_string(),
display_name: "billing_address_first_name".to_string(),
field_type: FieldType::Text,
value: None,
},
);
}
fields
}
_ => get_billing_details(connector),
}
}
#[cfg(feature = "v1")]
fn get_connector_payment_method_type_fields(
connector: PayoutConnectors,
payment_method_type: PaymentMethodType,
) -> (PaymentMethodType, ConnectorFields) {
let mut common_fields = get_billing_details_for_payment_method(connector, payment_method_type);
match payment_method_type {
// Card
PaymentMethodType::Debit => {
common_fields.extend(get_card_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
PaymentMethodType::Credit => {
common_fields.extend(get_card_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
// Banks
PaymentMethodType::Bacs => {
common_fields.extend(get_bacs_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
PaymentMethodType::Pix => {
common_fields.extend(get_pix_bank_transfer_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
PaymentMethodType::SepaBankTransfer => {
common_fields.extend(get_sepa_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
// Wallets
PaymentMethodType::Paypal => {
common_fields.extend(get_paypal_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
// Bank Redirect
PaymentMethodType::Interac => {
common_fields.extend(get_interac_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
_ => (
payment_method_type,
ConnectorFields {
fields: HashMap::new(),
},
),
}
}
fn get_card_fields() -> HashMap<String, RequiredFieldInfo> {
HashMap::from([
(
"payout_method_data.card.card_number".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.card.card_number".to_string(),
display_name: "card_number".to_string(),
field_type: FieldType::UserCardNumber,
value: None,
},
),
(
"payout_method_data.card.expiry_month".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.card.expiry_month".to_string(),
display_name: "exp_month".to_string(),
field_type: FieldType::UserCardExpiryMonth,
value: None,
},
),
(
"payout_method_data.card.expiry_year".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.card.expiry_year".to_string(),
display_name: "exp_year".to_string(),
field_type: FieldType::UserCardExpiryYear,
value: None,
},
),
(
"payout_method_data.card.card_holder_name".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.card.card_holder_name".to_string(),
display_name: "card_holder_name".to_string(),
field_type: FieldType::UserFullName,
value: None,
},
),
])
}
fn get_bacs_fields() -> HashMap<String, RequiredFieldInfo> {
HashMap::from([
(
"payout_method_data.bank.bank_sort_code".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.bank.bank_sort_code".to_string(),
display_name: "bank_sort_code".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"payout_method_data.bank.bank_account_number".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.bank.bank_account_number".to_string(),
display_name: "bank_account_number".to_string(),
field_type: FieldType::Text,
value: None,
},
),
])
}
fn get_pix_bank_transfer_fields() -> HashMap<String, RequiredFieldInfo> {
HashMap::from([
(
"payout_method_data.bank.bank_account_number".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.bank.bank_account_number".to_string(),
display_name: "bank_account_number".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"payout_method_data.bank.pix_key".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.bank.pix_key".to_string(),
display_name: "pix_key".to_string(),
field_type: FieldType::Text,
value: None,
},
),
])
}
fn get_sepa_fields() -> HashMap<String, RequiredFieldInfo> {
HashMap::from([
(
"payout_method_data.bank.iban".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.bank.iban".to_string(),
display_name: "iban".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"payout_method_data.bank.bic".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.bank.bic".to_string(),
display_name: "bic".to_string(),
field_type: FieldType::Text,
value: None,
},
),
])
}
fn get_paypal_fields() -> HashMap<String, RequiredFieldInfo> {
HashMap::from([(
"payout_method_data.wallet.telephone_number".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.wallet.telephone_number".to_string(),
display_name: "telephone_number".to_string(),
field_type: FieldType::Text,
value: None,
},
)])
}
fn get_interac_fields() -> HashMap<String, RequiredFieldInfo> {
HashMap::from([(
"payout_method_data.bank_redirect.email".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.bank_redirect.email".to_string(),
display_name: "email".to_string(),
field_type: FieldType::Text,
value: None,
},
)])
}
fn get_countries_for_connector(connector: PayoutConnectors) -> Vec<CountryAlpha2> {
match connector {
PayoutConnectors::Adyenplatform => vec![
CountryAlpha2::ES,
CountryAlpha2::SK,
CountryAlpha2::AT,
CountryAlpha2::NL,
CountryAlpha2::DE,
CountryAlpha2::BE,
CountryAlpha2::FR,
CountryAlpha2::FI,
CountryAlpha2::PT,
CountryAlpha2::IE,
CountryAlpha2::EE,
CountryAlpha2::LT,
CountryAlpha2::LV,
CountryAlpha2::IT,
CountryAlpha2::CZ,
CountryAlpha2::DE,
CountryAlpha2::HU,
CountryAlpha2::NO,
CountryAlpha2::PL,
CountryAlpha2::SE,
CountryAlpha2::GB,
CountryAlpha2::CH,
],
PayoutConnectors::Stripe => vec![CountryAlpha2::US],
_ => vec![],
}
}
fn get_billing_details(connector: PayoutConnectors) -> HashMap<String, RequiredFieldInfo> {
match connector {
PayoutConnectors::Adyen => HashMap::from([
(
"billing.address.line1".to_string(),
RequiredFieldInfo {
required_field: "billing.address.line1".to_string(),
display_name: "billing_address_line1".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.line2".to_string(),
RequiredFieldInfo {
required_field: "billing.address.line2".to_string(),
display_name: "billing_address_line2".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.city".to_string(),
RequiredFieldInfo {
required_field: "billing.address.city".to_string(),
display_name: "billing_address_city".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.zip".to_string(),
RequiredFieldInfo {
required_field: "billing.address.zip".to_string(),
display_name: "billing_address_zip".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.country".to_string(),
RequiredFieldInfo {
required_field: "billing.address.country".to_string(),
display_name: "billing_address_country".to_string(),
field_type: FieldType::UserAddressCountry {
options: get_countries_for_connector(connector)
.iter()
.map(|country| country.to_string())
.collect::<Vec<String>>(),
},
value: None,
},
),
(
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "billing.address.first_name".to_string(),
display_name: "billing_address_first_name".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.last_name".to_string(),
RequiredFieldInfo {
required_field: "billing.address.last_name".to_string(),
display_name: "billing_address_last_name".to_string(),
field_type: FieldType::Text,
value: None,
},
),
]),
PayoutConnectors::Wise => HashMap::from([
(
"billing.address.line1".to_string(),
RequiredFieldInfo {
required_field: "billing.address.line1".to_string(),
display_name: "billing_address_line1".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.city".to_string(),
RequiredFieldInfo {
required_field: "billing.address.city".to_string(),
display_name: "billing_address_city".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.state".to_string(),
RequiredFieldInfo {
required_field: "billing.address.state".to_string(),
display_name: "billing_address_state".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.zip".to_string(),
RequiredFieldInfo {
required_field: "billing.address.zip".to_string(),
display_name: "billing_address_zip".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.country".to_string(),
RequiredFieldInfo {
required_field: "billing.address.country".to_string(),
display_name: "billing_address_country".to_string(),
field_type: FieldType::UserAddressCountry {
options: get_countries_for_connector(connector)
.iter()
.map(|country| country.to_string())
.collect::<Vec<String>>(),
},
value: None,
},
),
(
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "billing.address.first_name".to_string(),
display_name: "billing_address_first_name".to_string(),
field_type: FieldType::Text,
value: None,
},
),
]),
PayoutConnectors::Loonio => HashMap::from([
(
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "billing.address.first_name".to_string(),
display_name: "billing_address_first_name".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.last_name".to_string(),
RequiredFieldInfo {
required_field: "billing.address.last_name".to_string(),
display_name: "billing_address_last_name".to_string(),
field_type: FieldType::Text,
value: None,
},
),
]),
PayoutConnectors::Gigadat => HashMap::from([
(
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "billing.address.first_name".to_string(),
display_name: "billing_address_first_name".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.address.last_name".to_string(),
RequiredFieldInfo {
required_field: "billing.address.last_name".to_string(),
display_name: "billing_address_last_name".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"billing.phone.number".to_string(),
RequiredFieldInfo {
required_field: "billing.phone.number".to_string(),
display_name: "phone".to_string(),
field_type: FieldType::UserPhoneNumber,
value: None,
},
),
(
"billing.phone.country_code".to_string(),
RequiredFieldInfo {
required_field: "billing.phone.country_code".to_string(),
display_name: "dialing_code".to_string(),
field_type: FieldType::UserPhoneNumberCountryCode,
value: None,
},
),
]),
_ => HashMap::from([]),
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.