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/db/reverse_lookup.rs | crates/router/src/db/reverse_lookup.rs | use super::{MockDb, Store};
use crate::{
errors::{self, CustomResult},
types::storage::{
enums,
reverse_lookup::{ReverseLookup, ReverseLookupNew},
},
};
#[async_trait::async_trait]
pub trait ReverseLookupInterface {
async fn insert_reverse_lookup(
&self,
_new: ReverseLookupNew,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError>;
async fn get_lookup_by_lookup_id(
&self,
_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError>;
}
#[cfg(not(feature = "kv_store"))]
mod storage {
use error_stack::report;
use router_env::{instrument, tracing};
use super::{ReverseLookupInterface, Store};
use crate::{
connection,
errors::{self, CustomResult},
types::storage::{
enums,
reverse_lookup::{ReverseLookup, ReverseLookupNew},
},
};
#[async_trait::async_trait]
impl ReverseLookupInterface for Store {
#[instrument(skip_all)]
async fn insert_reverse_lookup(
&self,
new: ReverseLookupNew,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
new.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn get_lookup_by_lookup_id(
&self,
id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
ReverseLookup::find_by_lookup_id(id, &conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
}
#[cfg(feature = "kv_store")]
mod storage {
use error_stack::{report, ResultExt};
use redis_interface::SetnxReply;
use router_env::{instrument, tracing};
use storage_impl::redis::kv_store::{
decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey,
};
use super::{ReverseLookupInterface, Store};
use crate::{
connection,
core::errors::utils::RedisErrorExt,
errors::{self, CustomResult},
types::storage::{
enums, kv,
reverse_lookup::{ReverseLookup, ReverseLookupNew},
},
utils::db_utils,
};
#[async_trait::async_trait]
impl ReverseLookupInterface for Store {
#[instrument(skip_all)]
async fn insert_reverse_lookup(
&self,
new: ReverseLookupNew,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, ReverseLookup>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => {
let conn = connection::pg_connection_write(self).await?;
new.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
enums::MerchantStorageScheme::RedisKv => {
let created_rev_lookup = ReverseLookup {
lookup_id: new.lookup_id.clone(),
sk_id: new.sk_id.clone(),
pk_id: new.pk_id.clone(),
source: new.source.clone(),
updated_by: storage_scheme.to_string(),
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::ReverseLookUp(new)),
},
};
match Box::pin(kv_wrapper::<ReverseLookup, _, _>(
self,
KvOperation::SetNx(&created_rev_lookup, redis_entry),
PartitionKey::CombinationKey {
combination: &format!(
"reverse_lookup_{}",
&created_rev_lookup.lookup_id
),
},
))
.await
.map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))?
.try_into_setnx()
{
Ok(SetnxReply::KeySet) => Ok(created_rev_lookup),
Ok(SetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: "reverse_lookup",
key: Some(created_rev_lookup.lookup_id.clone()),
}
.into()),
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
}
}
#[instrument(skip_all)]
async fn get_lookup_by_lookup_id(
&self,
id: &str,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
let database_call = || async {
let conn = connection::pg_connection_read(self).await?;
ReverseLookup::find_by_lookup_id(id, &conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, ReverseLookup>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
let redis_fut = async {
Box::pin(kv_wrapper(
self,
KvOperation::<ReverseLookup>::Get,
PartitionKey::CombinationKey {
combination: &format!("reverse_lookup_{id}"),
},
))
.await?
.try_into_get()
};
Box::pin(db_utils::try_redis_get_else_try_database_get(
redis_fut,
database_call,
))
.await
}
}
}
}
}
#[async_trait::async_trait]
impl ReverseLookupInterface for MockDb {
async fn insert_reverse_lookup(
&self,
new: ReverseLookupNew,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
let reverse_lookup_insert = ReverseLookup::from(new);
self.reverse_lookups
.lock()
.await
.push(reverse_lookup_insert.clone());
Ok(reverse_lookup_insert)
}
async fn get_lookup_by_lookup_id(
&self,
lookup_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
self.reverse_lookups
.lock()
.await
.iter()
.find(|reverse_lookup| reverse_lookup.lookup_id == lookup_id)
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No reverse lookup found for lookup_id = {lookup_id}",
))
.into(),
)
.cloned()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/merchant_key_store.rs | crates/router/src/db/merchant_key_store.rs | pub use hyperswitch_domain_models::merchant_key_store::{self, MerchantKeyStoreInterface};
#[cfg(test)]
mod tests {
use std::{borrow::Cow, sync::Arc};
use common_utils::{
type_name,
types::keymanager::{Identifier, KeyManagerState},
};
use hyperswitch_domain_models::master_key::MasterKeyInterface;
use time::macros::datetime;
use tokio::sync::oneshot;
use crate::{
db::{merchant_key_store::MerchantKeyStoreInterface, MockDb},
routes::{
self,
app::{settings::Settings, StorageImpl},
},
services,
types::domain,
};
#[tokio::test]
async fn test_mock_db_merchant_key_store_interface() {
let conf = Settings::new().expect("invalid settings");
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let state = &Arc::new(app_state)
.get_session_state(
&common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let mock_db = MockDb::new(
&redis_interface::RedisSettings::default(),
KeyManagerState::new(),
)
.await
.expect("Failed to create mock DB");
let master_key = mock_db.get_master_key();
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("merchant1")).unwrap();
let identifier = Identifier::Merchant(merchant_id.clone());
let key_manager_state = &state.into();
let merchant_key1 = mock_db
.insert_merchant_key_store(
domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
key: domain::types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantKeyStore),
domain::types::CryptoOperation::EncryptLocally(
services::generate_aes256_key().unwrap().to_vec().into(),
),
identifier.clone(),
master_key,
)
.await
.and_then(|val| val.try_into_operation())
.unwrap(),
created_at: datetime!(2023-02-01 0:00),
},
&master_key.to_vec().into(),
)
.await
.unwrap();
let found_merchant_key1 = mock_db
.get_merchant_key_store_by_merchant_id(&merchant_id, &master_key.to_vec().into())
.await
.unwrap();
assert_eq!(found_merchant_key1.merchant_id, merchant_key1.merchant_id);
assert_eq!(found_merchant_key1.key, merchant_key1.key);
let insert_duplicate_merchant_key1_result = mock_db
.insert_merchant_key_store(
domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
key: domain::types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantKeyStore),
domain::types::CryptoOperation::EncryptLocally(
services::generate_aes256_key().unwrap().to_vec().into(),
),
identifier.clone(),
master_key,
)
.await
.and_then(|val| val.try_into_operation())
.unwrap(),
created_at: datetime!(2023-02-01 0:00),
},
&master_key.to_vec().into(),
)
.await;
assert!(insert_duplicate_merchant_key1_result.is_err());
let non_existent_merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("non_existent")).unwrap();
let find_non_existent_merchant_key_result = mock_db
.get_merchant_key_store_by_merchant_id(
&non_existent_merchant_id,
&master_key.to_vec().into(),
)
.await;
assert!(find_non_existent_merchant_key_result.is_err());
let find_merchant_key_with_incorrect_master_key_result = mock_db
.get_merchant_key_store_by_merchant_id(&merchant_id, &vec![0; 32].into())
.await;
assert!(find_merchant_key_with_incorrect_master_key_result.is_err());
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/user/theme.rs | crates/router/src/db/user/theme.rs | use common_utils::types::user::ThemeLineage;
use diesel_models::user::theme::{self as storage, ThemeUpdate};
use error_stack::report;
use super::MockDb;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
#[async_trait::async_trait]
pub trait ThemeInterface {
async fn insert_theme(
&self,
theme: storage::ThemeNew,
) -> CustomResult<storage::Theme, errors::StorageError>;
async fn find_theme_by_theme_id(
&self,
theme_id: String,
) -> CustomResult<storage::Theme, errors::StorageError>;
async fn find_most_specific_theme_in_lineage(
&self,
lineage: ThemeLineage,
) -> CustomResult<storage::Theme, errors::StorageError>;
async fn find_theme_by_lineage(
&self,
lineage: ThemeLineage,
) -> CustomResult<storage::Theme, errors::StorageError>;
async fn update_theme_by_theme_id(
&self,
theme_id: String,
theme_update: ThemeUpdate,
) -> CustomResult<storage::Theme, errors::StorageError>;
async fn delete_theme_by_theme_id(
&self,
theme_id: String,
) -> CustomResult<storage::Theme, errors::StorageError>;
async fn list_themes_at_and_under_lineage(
&self,
lineage: ThemeLineage,
) -> CustomResult<Vec<storage::Theme>, errors::StorageError>;
}
#[async_trait::async_trait]
impl ThemeInterface for Store {
async fn insert_theme(
&self,
theme: storage::ThemeNew,
) -> CustomResult<storage::Theme, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
theme
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn find_theme_by_theme_id(
&self,
theme_id: String,
) -> CustomResult<storage::Theme, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Theme::find_by_theme_id(&conn, theme_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn find_most_specific_theme_in_lineage(
&self,
lineage: ThemeLineage,
) -> CustomResult<storage::Theme, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Theme::find_most_specific_theme_in_lineage(&conn, lineage)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn find_theme_by_lineage(
&self,
lineage: ThemeLineage,
) -> CustomResult<storage::Theme, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Theme::find_by_lineage(&conn, lineage)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn update_theme_by_theme_id(
&self,
theme_id: String,
theme_update: ThemeUpdate,
) -> CustomResult<storage::Theme, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Theme::update_by_theme_id(&conn, theme_id, theme_update)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn delete_theme_by_theme_id(
&self,
theme_id: String,
) -> CustomResult<storage::Theme, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Theme::delete_by_theme_id(&conn, theme_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn list_themes_at_and_under_lineage(
&self,
lineage: ThemeLineage,
) -> CustomResult<Vec<storage::Theme>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Theme::find_all_by_lineage_hierarchy(&conn, lineage)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
fn check_theme_with_lineage(theme: &storage::Theme, lineage: &ThemeLineage) -> bool {
match lineage {
ThemeLineage::Tenant { tenant_id } => {
&theme.tenant_id == tenant_id
&& theme.org_id.is_none()
&& theme.merchant_id.is_none()
&& theme.profile_id.is_none()
}
ThemeLineage::Organization { tenant_id, org_id } => {
&theme.tenant_id == tenant_id
&& theme
.org_id
.as_ref()
.is_some_and(|org_id_inner| org_id_inner == org_id)
&& theme.merchant_id.is_none()
&& theme.profile_id.is_none()
}
ThemeLineage::Merchant {
tenant_id,
org_id,
merchant_id,
} => {
&theme.tenant_id == tenant_id
&& theme
.org_id
.as_ref()
.is_some_and(|org_id_inner| org_id_inner == org_id)
&& theme
.merchant_id
.as_ref()
.is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id)
&& theme.profile_id.is_none()
}
ThemeLineage::Profile {
tenant_id,
org_id,
merchant_id,
profile_id,
} => {
&theme.tenant_id == tenant_id
&& theme
.org_id
.as_ref()
.is_some_and(|org_id_inner| org_id_inner == org_id)
&& theme
.merchant_id
.as_ref()
.is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id)
&& theme
.profile_id
.as_ref()
.is_some_and(|profile_id_inner| profile_id_inner == profile_id)
}
}
}
fn check_theme_belongs_to_lineage_hierarchy(
theme: &storage::Theme,
lineage: &ThemeLineage,
) -> bool {
match lineage {
ThemeLineage::Tenant { tenant_id } => &theme.tenant_id == tenant_id,
ThemeLineage::Organization { tenant_id, org_id } => {
&theme.tenant_id == tenant_id
&& theme
.org_id
.as_ref()
.is_some_and(|org_id_inner| org_id_inner == org_id)
}
ThemeLineage::Merchant {
tenant_id,
org_id,
merchant_id,
} => {
&theme.tenant_id == tenant_id
&& theme
.org_id
.as_ref()
.is_some_and(|org_id_inner| org_id_inner == org_id)
&& theme
.merchant_id
.as_ref()
.is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id)
}
ThemeLineage::Profile {
tenant_id,
org_id,
merchant_id,
profile_id,
} => {
&theme.tenant_id == tenant_id
&& theme
.org_id
.as_ref()
.is_some_and(|org_id_inner| org_id_inner == org_id)
&& theme
.merchant_id
.as_ref()
.is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id)
&& theme
.profile_id
.as_ref()
.is_some_and(|profile_id_inner| profile_id_inner == profile_id)
}
}
}
#[async_trait::async_trait]
impl ThemeInterface for MockDb {
async fn insert_theme(
&self,
new_theme: storage::ThemeNew,
) -> CustomResult<storage::Theme, errors::StorageError> {
let mut themes = self.themes.lock().await;
for theme in themes.iter() {
if new_theme.theme_id == theme.theme_id {
return Err(errors::StorageError::DuplicateValue {
entity: "theme_id",
key: None,
}
.into());
}
if new_theme.tenant_id == theme.tenant_id
&& new_theme.org_id == theme.org_id
&& new_theme.merchant_id == theme.merchant_id
&& new_theme.profile_id == theme.profile_id
{
return Err(errors::StorageError::DuplicateValue {
entity: "lineage",
key: None,
}
.into());
}
}
let theme = storage::Theme {
theme_id: new_theme.theme_id,
tenant_id: new_theme.tenant_id,
org_id: new_theme.org_id,
merchant_id: new_theme.merchant_id,
profile_id: new_theme.profile_id,
created_at: new_theme.created_at,
last_modified_at: new_theme.last_modified_at,
entity_type: new_theme.entity_type,
theme_name: new_theme.theme_name,
email_primary_color: new_theme.email_primary_color,
email_foreground_color: new_theme.email_foreground_color,
email_background_color: new_theme.email_background_color,
email_entity_name: new_theme.email_entity_name,
email_entity_logo_url: new_theme.email_entity_logo_url,
};
themes.push(theme.clone());
Ok(theme)
}
async fn find_theme_by_theme_id(
&self,
theme_id: String,
) -> CustomResult<storage::Theme, errors::StorageError> {
let themes = self.themes.lock().await;
themes
.iter()
.find(|theme| theme.theme_id == theme_id)
.cloned()
.ok_or(
errors::StorageError::ValueNotFound(format!("Theme with id {theme_id} not found"))
.into(),
)
}
async fn find_most_specific_theme_in_lineage(
&self,
lineage: ThemeLineage,
) -> CustomResult<storage::Theme, errors::StorageError> {
let themes = self.themes.lock().await;
let lineages = lineage.get_same_and_higher_lineages();
themes
.iter()
.filter(|theme| {
lineages
.iter()
.any(|lineage| check_theme_with_lineage(theme, lineage))
})
.min_by_key(|theme| theme.entity_type)
.ok_or(
errors::StorageError::ValueNotFound("No theme found in lineage".to_string()).into(),
)
.cloned()
}
async fn find_theme_by_lineage(
&self,
lineage: ThemeLineage,
) -> CustomResult<storage::Theme, errors::StorageError> {
let themes = self.themes.lock().await;
themes
.iter()
.find(|theme| check_theme_with_lineage(theme, &lineage))
.cloned()
.ok_or(
errors::StorageError::ValueNotFound(format!(
"Theme with lineage {lineage:?} not found",
))
.into(),
)
}
async fn update_theme_by_theme_id(
&self,
theme_id: String,
theme_update: ThemeUpdate,
) -> CustomResult<storage::Theme, errors::StorageError> {
let mut themes = self.themes.lock().await;
themes
.iter_mut()
.find(|theme| theme.theme_id == theme_id)
.map(|theme| {
match theme_update {
ThemeUpdate::EmailConfig { email_config } => {
theme.email_primary_color = email_config.primary_color;
theme.email_foreground_color = email_config.foreground_color;
theme.email_background_color = email_config.background_color;
theme.email_entity_name = email_config.entity_name;
theme.email_entity_logo_url = email_config.entity_logo_url;
}
}
theme.clone()
})
.ok_or_else(|| {
report!(errors::StorageError::ValueNotFound(format!(
"Theme with id {theme_id} not found",
)))
})
}
async fn delete_theme_by_theme_id(
&self,
theme_id: String,
) -> CustomResult<storage::Theme, errors::StorageError> {
let mut themes = self.themes.lock().await;
let index = themes
.iter()
.position(|theme| theme.theme_id == theme_id)
.ok_or(errors::StorageError::ValueNotFound(format!(
"Theme with id {theme_id} not found"
)))?;
let theme = themes.remove(index);
Ok(theme)
}
async fn list_themes_at_and_under_lineage(
&self,
lineage: ThemeLineage,
) -> CustomResult<Vec<storage::Theme>, errors::StorageError> {
let themes = self.themes.lock().await;
let matching_themes: Vec<storage::Theme> = themes
.iter()
.filter(|theme| check_theme_belongs_to_lineage_hierarchy(theme, &lineage))
.cloned()
.collect();
Ok(matching_themes)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/user/sample_data.rs | crates/router/src/db/user/sample_data.rs | use common_utils::types::keymanager::KeyManagerState;
#[cfg(feature = "v1")]
use diesel_models::user::sample_data::PaymentAttemptBatchNew;
use diesel_models::{
dispute::{Dispute, DisputeNew},
errors::DatabaseError,
query::user::sample_data as sample_data_queries,
refund::{Refund, RefundNew},
};
use error_stack::{Report, ResultExt};
use futures::{future::try_join_all, FutureExt};
use hyperswitch_domain_models::{
behaviour::Conversion,
merchant_key_store::MerchantKeyStore,
payments::{payment_attempt::PaymentAttempt, PaymentIntent},
};
use storage_impl::errors::StorageError;
use crate::{connection::pg_connection_write, core::errors::CustomResult, services::Store};
#[async_trait::async_trait]
pub trait BatchSampleDataInterface {
#[cfg(feature = "v1")]
async fn insert_payment_intents_batch_for_sample_data(
&self,
state: &KeyManagerState,
batch: Vec<PaymentIntent>,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentIntent>, StorageError>;
#[cfg(feature = "v1")]
async fn insert_payment_attempts_batch_for_sample_data(
&self,
batch: Vec<PaymentAttemptBatchNew>,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError>;
#[cfg(feature = "v1")]
async fn insert_refunds_batch_for_sample_data(
&self,
batch: Vec<RefundNew>,
) -> CustomResult<Vec<Refund>, StorageError>;
#[cfg(feature = "v1")]
async fn insert_disputes_batch_for_sample_data(
&self,
batch: Vec<DisputeNew>,
) -> CustomResult<Vec<Dispute>, StorageError>;
#[cfg(feature = "v1")]
async fn delete_payment_intents_for_sample_data(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentIntent>, StorageError>;
#[cfg(feature = "v1")]
async fn delete_payment_attempts_for_sample_data(
&self,
merchant_id: &common_utils::id_type::MerchantId,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError>;
#[cfg(feature = "v1")]
async fn delete_refunds_for_sample_data(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<Refund>, StorageError>;
#[cfg(feature = "v1")]
async fn delete_disputes_for_sample_data(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<Dispute>, StorageError>;
}
#[async_trait::async_trait]
impl BatchSampleDataInterface for Store {
#[cfg(feature = "v1")]
async fn insert_payment_intents_batch_for_sample_data(
&self,
state: &KeyManagerState,
batch: Vec<PaymentIntent>,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
let conn = pg_connection_write(self)
.await
.change_context(StorageError::DatabaseConnectionError)?;
let new_intents = try_join_all(batch.into_iter().map(|payment_intent| async {
payment_intent
.construct_new()
.await
.change_context(StorageError::EncryptionError)
}))
.await?;
sample_data_queries::insert_payment_intents(&conn, new_intents)
.await
.map_err(diesel_error_to_data_error)
.map(|v| {
try_join_all(v.into_iter().map(|payment_intent| {
PaymentIntent::convert_back(
state,
payment_intent,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
}))
.map(|join_result| join_result.change_context(StorageError::DecryptionError))
})?
.await
}
#[cfg(feature = "v1")]
async fn insert_payment_attempts_batch_for_sample_data(
&self,
batch: Vec<PaymentAttemptBatchNew>,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
let conn = pg_connection_write(self)
.await
.change_context(StorageError::DatabaseConnectionError)?;
sample_data_queries::insert_payment_attempts(&conn, batch)
.await
.map_err(diesel_error_to_data_error)
.map(|v| {
try_join_all(v.into_iter().map(|payment_intent| {
PaymentAttempt::convert_back(
state,
payment_intent,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
}))
.map(|join_result| join_result.change_context(StorageError::DecryptionError))
})?
.await
}
#[cfg(feature = "v1")]
async fn insert_refunds_batch_for_sample_data(
&self,
batch: Vec<RefundNew>,
) -> CustomResult<Vec<Refund>, StorageError> {
let conn = pg_connection_write(self)
.await
.change_context(StorageError::DatabaseConnectionError)?;
sample_data_queries::insert_refunds(&conn, batch)
.await
.map_err(diesel_error_to_data_error)
}
#[cfg(feature = "v1")]
async fn insert_disputes_batch_for_sample_data(
&self,
batch: Vec<DisputeNew>,
) -> CustomResult<Vec<Dispute>, StorageError> {
let conn = pg_connection_write(self)
.await
.change_context(StorageError::DatabaseConnectionError)?;
sample_data_queries::insert_disputes(&conn, batch)
.await
.map_err(diesel_error_to_data_error)
}
#[cfg(feature = "v1")]
async fn delete_payment_intents_for_sample_data(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
let conn = pg_connection_write(self)
.await
.change_context(StorageError::DatabaseConnectionError)?;
sample_data_queries::delete_payment_intents(&conn, merchant_id)
.await
.map_err(diesel_error_to_data_error)
.map(|v| {
try_join_all(v.into_iter().map(|payment_intent| {
PaymentIntent::convert_back(
state,
payment_intent,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
}))
.map(|join_result| join_result.change_context(StorageError::DecryptionError))
})?
.await
}
#[cfg(feature = "v1")]
async fn delete_payment_attempts_for_sample_data(
&self,
merchant_id: &common_utils::id_type::MerchantId,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
let conn = pg_connection_write(self)
.await
.change_context(StorageError::DatabaseConnectionError)?;
sample_data_queries::delete_payment_attempts(&conn, merchant_id)
.await
.map_err(diesel_error_to_data_error)
.map(|res| {
try_join_all(res.into_iter().map(|res| {
PaymentAttempt::convert_back(
state,
res,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
}))
.map(|join_result| join_result.change_context(StorageError::DecryptionError))
})?
.await
}
#[cfg(feature = "v1")]
async fn delete_refunds_for_sample_data(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<Refund>, StorageError> {
let conn = pg_connection_write(self)
.await
.change_context(StorageError::DatabaseConnectionError)?;
sample_data_queries::delete_refunds(&conn, merchant_id)
.await
.map_err(diesel_error_to_data_error)
}
#[cfg(feature = "v1")]
async fn delete_disputes_for_sample_data(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<Dispute>, StorageError> {
let conn = pg_connection_write(self)
.await
.change_context(StorageError::DatabaseConnectionError)?;
sample_data_queries::delete_disputes(&conn, merchant_id)
.await
.map_err(diesel_error_to_data_error)
}
}
#[async_trait::async_trait]
impl BatchSampleDataInterface for storage_impl::MockDb {
#[cfg(feature = "v1")]
async fn insert_payment_intents_batch_for_sample_data(
&self,
_state: &KeyManagerState,
_batch: Vec<PaymentIntent>,
_key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn insert_payment_attempts_batch_for_sample_data(
&self,
_batch: Vec<PaymentAttemptBatchNew>,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn insert_refunds_batch_for_sample_data(
&self,
_batch: Vec<RefundNew>,
) -> CustomResult<Vec<Refund>, StorageError> {
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn insert_disputes_batch_for_sample_data(
&self,
_batch: Vec<DisputeNew>,
) -> CustomResult<Vec<Dispute>, StorageError> {
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn delete_payment_intents_for_sample_data(
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
_key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn delete_payment_attempts_for_sample_data(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn delete_refunds_for_sample_data(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<Refund>, StorageError> {
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn delete_disputes_for_sample_data(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<Dispute>, StorageError> {
Err(StorageError::MockDbError)?
}
}
// TODO: This error conversion is re-used from storage_impl and is not DRY when it should be
// Ideally the impl's here should be defined in that crate avoiding this re-definition
fn diesel_error_to_data_error(diesel_error: Report<DatabaseError>) -> Report<StorageError> {
let new_err = match diesel_error.current_context() {
DatabaseError::DatabaseConnectionError => StorageError::DatabaseConnectionError,
DatabaseError::NotFound => StorageError::ValueNotFound("Value not found".to_string()),
DatabaseError::UniqueViolation => StorageError::DuplicateValue {
entity: "entity ",
key: None,
},
err => StorageError::DatabaseError(error_stack::report!(*err)),
};
diesel_error.change_context(new_err)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/connector/utils.rs | crates/router/src/connector/utils.rs | use std::{
collections::{HashMap, HashSet},
ops::Deref,
str::FromStr,
sync::LazyLock,
};
#[cfg(feature = "payouts")]
use api_models::payouts::{self, PayoutVendorAccountDetails};
use api_models::{
enums::{CanadaStatesAbbreviation, UsStatesAbbreviation},
payments,
};
use base64::Engine;
use cards::NetworkToken;
use common_utils::{
date_time,
errors::{ParsingError, ReportSwitchExt},
ext_traits::StringExt,
id_type,
pii::{self, Email, IpAddress},
types::{AmountConvertor, MinorUnit},
};
use diesel_models::{enums, types::OrderDetailsWithAmount};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
use masking::{Deserialize, ExposeInterface, Secret};
use regex::Regex;
#[cfg(feature = "frm")]
use crate::types::fraud_check;
use crate::{
consts,
core::{
errors::{self, ApiErrorResponse, CustomResult},
payments::{types::AuthenticationData, PaymentData},
},
pii::PeekInterface,
types::{
self, api, domain,
storage::enums as storage_enums,
transformers::{ForeignFrom, ForeignTryFrom},
BrowserInformation, PaymentsCancelData, ResponseId,
},
utils::{OptionExt, ValueExt},
};
pub fn missing_field_err(
message: &'static str,
) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> {
Box::new(move || {
errors::ConnectorError::MissingRequiredField {
field_name: message,
}
.into()
})
}
type Error = error_stack::Report<errors::ConnectorError>;
pub trait AccessTokenRequestInfo {
fn get_request_id(&self) -> Result<Secret<String>, Error>;
}
impl AccessTokenRequestInfo for types::RefreshTokenRouterData {
fn get_request_id(&self) -> Result<Secret<String>, Error> {
self.request
.id
.clone()
.ok_or_else(missing_field_err("request.id"))
}
}
pub trait RouterData {
fn get_billing(&self) -> Result<&hyperswitch_domain_models::address::Address, Error>;
fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error>;
fn get_billing_phone(&self)
-> Result<&hyperswitch_domain_models::address::PhoneDetails, Error>;
fn get_description(&self) -> Result<String, Error>;
fn get_billing_address(
&self,
) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error>;
fn get_shipping_address(
&self,
) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error>;
fn get_shipping_address_with_phone_number(
&self,
) -> Result<&hyperswitch_domain_models::address::Address, Error>;
fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_session_token(&self) -> Result<String, Error>;
fn get_billing_first_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_full_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_last_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_line1(&self) -> Result<Secret<String>, Error>;
fn get_billing_city(&self) -> Result<String, Error>;
fn get_billing_email(&self) -> Result<Email, Error>;
fn get_billing_phone_number(&self) -> Result<Secret<String>, Error>;
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned;
fn is_three_ds(&self) -> bool;
fn get_payment_method_token(&self) -> Result<types::PaymentMethodToken, Error>;
fn get_customer_id(&self) -> Result<id_type::CustomerId, Error>;
fn get_connector_customer_id(&self) -> Result<String, Error>;
fn get_preprocessing_id(&self) -> Result<String, Error>;
fn get_recurring_mandate_payment_data(
&self,
) -> Result<types::RecurringMandatePaymentData, Error>;
#[cfg(feature = "payouts")]
fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>;
#[cfg(feature = "payouts")]
fn get_quote_id(&self) -> Result<String, Error>;
fn get_optional_billing(&self) -> Option<&hyperswitch_domain_models::address::Address>;
fn get_optional_shipping(&self) -> Option<&hyperswitch_domain_models::address::Address>;
fn get_optional_shipping_line1(&self) -> Option<Secret<String>>;
fn get_optional_shipping_line2(&self) -> Option<Secret<String>>;
fn get_optional_shipping_line3(&self) -> Option<Secret<String>>;
fn get_optional_shipping_city(&self) -> Option<String>;
fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2>;
fn get_optional_shipping_zip(&self) -> Option<Secret<String>>;
fn get_optional_shipping_state(&self) -> Option<Secret<String>>;
fn get_optional_shipping_first_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_last_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>>;
fn get_optional_shipping_email(&self) -> Option<Email>;
fn get_optional_billing_full_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_line1(&self) -> Option<Secret<String>>;
fn get_optional_billing_line2(&self) -> Option<Secret<String>>;
fn get_optional_billing_city(&self) -> Option<String>;
fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2>;
fn get_optional_billing_zip(&self) -> Option<Secret<String>>;
fn get_optional_billing_state(&self) -> Option<Secret<String>>;
fn get_optional_billing_first_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_last_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_phone_number(&self) -> Option<Secret<String>>;
fn get_optional_billing_email(&self) -> Option<Email>;
}
pub trait PaymentResponseRouterData {
fn get_attempt_status_for_db_update<F>(
&self,
payment_data: &PaymentData<F>,
amount_captured: Option<i64>,
amount_capturable: Option<i64>,
) -> CustomResult<enums::AttemptStatus, ApiErrorResponse>
where
F: Clone;
}
#[cfg(feature = "v1")]
impl<Flow, Request, Response> PaymentResponseRouterData
for types::RouterData<Flow, Request, Response>
where
Request: types::Capturable,
{
fn get_attempt_status_for_db_update<F>(
&self,
payment_data: &PaymentData<F>,
amount_captured: Option<i64>,
amount_capturable: Option<i64>,
) -> CustomResult<enums::AttemptStatus, ApiErrorResponse>
where
F: Clone,
{
match self.status {
enums::AttemptStatus::Voided => {
if payment_data.payment_intent.amount_captured > Some(MinorUnit::new(0)) {
Ok(enums::AttemptStatus::PartialCharged)
} else {
Ok(self.status)
}
}
enums::AttemptStatus::Charged => {
let captured_amount = types::Capturable::get_captured_amount(
&self.request,
amount_captured,
payment_data,
);
let total_capturable_amount = payment_data.payment_attempt.get_total_amount();
if Some(total_capturable_amount) == captured_amount.map(MinorUnit::new)
|| (captured_amount.is_some_and(|captured_amount| {
MinorUnit::new(captured_amount) > total_capturable_amount
}))
{
Ok(enums::AttemptStatus::Charged)
} else if captured_amount.is_some_and(|captured_amount| {
MinorUnit::new(captured_amount) < total_capturable_amount
}) {
Ok(enums::AttemptStatus::PartialCharged)
} else {
Ok(self.status)
}
}
enums::AttemptStatus::Authorized => {
let capturable_amount = types::Capturable::get_amount_capturable(
&self.request,
payment_data,
amount_capturable,
payment_data.payment_attempt.status,
);
let total_capturable_amount = payment_data.payment_attempt.get_total_amount();
let is_overcapture_enabled = *payment_data
.payment_attempt
.is_overcapture_enabled
.unwrap_or_default()
.deref();
if Some(total_capturable_amount) == capturable_amount.map(MinorUnit::new)
|| (capturable_amount.is_some_and(|capturable_amount| {
MinorUnit::new(capturable_amount) > total_capturable_amount
}) && is_overcapture_enabled)
{
Ok(enums::AttemptStatus::Authorized)
} else if capturable_amount.is_some_and(|capturable_amount| {
MinorUnit::new(capturable_amount) < total_capturable_amount
}) && payment_data
.payment_intent
.enable_partial_authorization
.is_some_and(|val| val.is_true())
{
Ok(enums::AttemptStatus::PartiallyAuthorized)
} else if capturable_amount.is_some_and(|capturable_amount| {
MinorUnit::new(capturable_amount) < total_capturable_amount
}) && !payment_data
.payment_intent
.enable_partial_authorization
.is_some_and(|val| val.is_true())
{
Err(ApiErrorResponse::IntegrityCheckFailed {
reason: "capturable_amount is less than the total attempt amount"
.to_string(),
field_names: "amount_capturable".to_string(),
connector_transaction_id: payment_data
.payment_attempt
.connector_transaction_id
.clone(),
})?
} else if capturable_amount.is_some_and(|capturable_amount| {
MinorUnit::new(capturable_amount) > total_capturable_amount
}) && !is_overcapture_enabled
{
Err(ApiErrorResponse::IntegrityCheckFailed {
reason: "capturable_amount is greater than the total attempt amount"
.to_string(),
field_names: "amount_capturable".to_string(),
connector_transaction_id: payment_data
.payment_attempt
.connector_transaction_id
.clone(),
})?
} else {
Ok(self.status)
}
}
_ => Ok(self.status),
}
}
}
#[cfg(feature = "v2")]
impl<Flow, Request, Response> PaymentResponseRouterData
for types::RouterData<Flow, Request, Response>
where
Request: types::Capturable,
{
fn get_attempt_status_for_db_update<F>(
&self,
payment_data: &PaymentData<F>,
amount_captured: Option<i64>,
amount_capturable: Option<i64>,
) -> CustomResult<enums::AttemptStatus, ApiErrorResponse>
where
F: Clone,
{
match self.status {
enums::AttemptStatus::Voided => {
if payment_data.payment_intent.amount_captured > Some(MinorUnit::new(0)) {
Ok(enums::AttemptStatus::PartialCharged)
} else {
Ok(self.status)
}
}
enums::AttemptStatus::Charged => {
let captured_amount = types::Capturable::get_captured_amount(
&self.request,
amount_captured,
payment_data,
);
let total_capturable_amount = payment_data.payment_attempt.get_total_amount();
if Some(total_capturable_amount) == captured_amount.map(MinorUnit::new) {
Ok(enums::AttemptStatus::Charged)
} else if captured_amount.is_some() {
Ok(enums::AttemptStatus::PartialCharged)
} else {
Ok(self.status)
}
}
enums::AttemptStatus::Authorized => {
let capturable_amount = types::Capturable::get_amount_capturable(
&self.request,
payment_data,
amount_capturable,
payment_data.payment_attempt.status,
);
if Some(payment_data.payment_attempt.get_total_amount())
== capturable_amount.map(MinorUnit::new)
{
Ok(enums::AttemptStatus::Authorized)
} else if capturable_amount.is_some() {
Ok(enums::AttemptStatus::PartiallyAuthorized)
} else {
Ok(self.status)
}
}
_ => Ok(self.status),
}
}
}
pub const SELECTED_PAYMENT_METHOD: &str = "Selected payment method";
pub fn get_unimplemented_payment_method_error_message(connector: &str) -> String {
format!("{SELECTED_PAYMENT_METHOD} through {connector}")
}
impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> {
fn get_billing(&self) -> Result<&hyperswitch_domain_models::address::Address, Error> {
self.address
.get_payment_method_billing()
.ok_or_else(missing_field_err("billing"))
}
fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error> {
self.address
.get_payment_method_billing()
.and_then(|a| a.address.as_ref())
.and_then(|ad| ad.country)
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.country",
))
}
fn get_billing_phone(
&self,
) -> Result<&hyperswitch_domain_models::address::PhoneDetails, Error> {
self.address
.get_payment_method_billing()
.and_then(|a| a.phone.as_ref())
.ok_or_else(missing_field_err("billing.phone"))
}
fn get_optional_billing(&self) -> Option<&hyperswitch_domain_models::address::Address> {
self.address.get_payment_method_billing()
}
fn get_optional_shipping(&self) -> Option<&hyperswitch_domain_models::address::Address> {
self.address.get_shipping()
}
fn get_optional_shipping_first_name(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.first_name)
})
}
fn get_optional_shipping_last_name(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.last_name)
})
}
fn get_optional_shipping_line1(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.line1)
})
}
fn get_optional_shipping_line2(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.line2)
})
}
fn get_optional_shipping_line3(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.line3)
})
}
fn get_optional_shipping_city(&self) -> Option<String> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.city)
})
}
fn get_optional_shipping_state(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.state)
})
}
fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.country)
})
}
fn get_optional_shipping_zip(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.zip)
})
}
fn get_optional_shipping_email(&self) -> Option<Email> {
self.address
.get_shipping()
.and_then(|shipping_address| shipping_address.clone().email)
}
fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>> {
self.address
.get_shipping()
.and_then(|shipping_address| shipping_address.clone().phone)
.and_then(|phone_details| phone_details.get_number_with_country_code().ok())
}
fn get_description(&self) -> Result<String, Error> {
self.description
.clone()
.ok_or_else(missing_field_err("description"))
}
fn get_billing_address(
&self,
) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error> {
self.address
.get_payment_method_billing()
.as_ref()
.and_then(|a| a.address.as_ref())
.ok_or_else(missing_field_err("billing.address"))
}
fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error> {
self.connector_meta_data
.clone()
.ok_or_else(missing_field_err("connector_meta_data"))
}
fn get_session_token(&self) -> Result<String, Error> {
self.session_token
.clone()
.ok_or_else(missing_field_err("session_token"))
}
fn get_billing_first_name(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.first_name.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.first_name",
))
}
fn get_billing_full_name(&self) -> Result<Secret<String>, Error> {
self.get_optional_billing()
.and_then(|billing_details| billing_details.address.as_ref())
.and_then(|billing_address| billing_address.get_optional_full_name())
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.first_name",
))
}
fn get_billing_last_name(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.last_name.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.last_name",
))
}
fn get_billing_line1(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line1.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.line1",
))
}
fn get_billing_city(&self) -> Result<String, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.city)
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.city",
))
}
fn get_billing_email(&self) -> Result<Email, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.email.clone())
.ok_or_else(missing_field_err("payment_method_data.billing.email"))
}
fn get_billing_phone_number(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.clone().phone)
.map(|phone_details| phone_details.get_number_with_country_code())
.transpose()?
.ok_or_else(missing_field_err("payment_method_data.billing.phone"))
}
fn get_optional_billing_line1(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line1)
})
}
fn get_optional_billing_line2(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line2)
})
}
fn get_optional_billing_city(&self) -> Option<String> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.city)
})
}
fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.country)
})
}
fn get_optional_billing_zip(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.zip)
})
}
fn get_optional_billing_state(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.state)
})
}
fn get_optional_billing_first_name(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.first_name)
})
}
fn get_optional_billing_last_name(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.last_name)
})
}
fn get_optional_billing_phone_number(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.phone
.and_then(|phone_data| phone_data.number)
})
}
fn get_optional_billing_email(&self) -> Option<Email> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.clone().email)
}
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
self.get_connector_meta()?
.parse_value(std::any::type_name::<T>())
.change_context(errors::ConnectorError::NoConnectorMetaData)
}
fn is_three_ds(&self) -> bool {
matches!(self.auth_type, enums::AuthenticationType::ThreeDs)
}
fn get_shipping_address(
&self,
) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error> {
self.address
.get_shipping()
.and_then(|a| a.address.as_ref())
.ok_or_else(missing_field_err("shipping.address"))
}
fn get_shipping_address_with_phone_number(
&self,
) -> Result<&hyperswitch_domain_models::address::Address, Error> {
self.address
.get_shipping()
.ok_or_else(missing_field_err("shipping"))
}
fn get_payment_method_token(&self) -> Result<types::PaymentMethodToken, Error> {
self.payment_method_token
.clone()
.ok_or_else(missing_field_err("payment_method_token"))
}
fn get_customer_id(&self) -> Result<id_type::CustomerId, Error> {
self.customer_id
.to_owned()
.ok_or_else(missing_field_err("customer_id"))
}
fn get_connector_customer_id(&self) -> Result<String, Error> {
self.connector_customer
.to_owned()
.ok_or_else(missing_field_err("connector_customer_id"))
}
fn get_preprocessing_id(&self) -> Result<String, Error> {
self.preprocessing_id
.to_owned()
.ok_or_else(missing_field_err("preprocessing_id"))
}
fn get_recurring_mandate_payment_data(
&self,
) -> Result<types::RecurringMandatePaymentData, Error> {
self.recurring_mandate_payment_data
.to_owned()
.ok_or_else(missing_field_err("recurring_mandate_payment_data"))
}
fn get_optional_billing_full_name(&self) -> Option<Secret<String>> {
self.get_optional_billing()
.and_then(|billing_details| billing_details.address.as_ref())
.and_then(|billing_address| billing_address.get_optional_full_name())
}
#[cfg(feature = "payouts")]
fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error> {
self.payout_method_data
.to_owned()
.ok_or_else(missing_field_err("payout_method_data"))
}
#[cfg(feature = "payouts")]
fn get_quote_id(&self) -> Result<String, Error> {
self.quote_id
.to_owned()
.ok_or_else(missing_field_err("quote_id"))
}
}
pub trait AddressData {
fn get_email(&self) -> Result<Email, Error>;
fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error>;
fn get_optional_country(&self) -> Option<enums::CountryAlpha2>;
fn get_optional_full_name(&self) -> Option<Secret<String>>;
}
impl AddressData for hyperswitch_domain_models::address::Address {
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error> {
self.phone
.clone()
.map(|phone_details| phone_details.get_number_with_country_code())
.transpose()?
.ok_or_else(missing_field_err("phone"))
}
fn get_optional_country(&self) -> Option<enums::CountryAlpha2> {
self.address
.as_ref()
.and_then(|billing_details| billing_details.country)
}
fn get_optional_full_name(&self) -> Option<Secret<String>> {
self.address
.as_ref()
.and_then(|billing_address| billing_address.get_optional_full_name())
}
}
pub trait PaymentsPreProcessingData {
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
fn get_currency(&self) -> Result<enums::Currency, Error>;
fn get_amount(&self) -> Result<i64, Error>;
fn get_minor_amount(&self) -> Result<MinorUnit, Error>;
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_router_return_url(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn connector_mandate_id(&self) -> Option<String>;
}
impl PaymentsPreProcessingData for types::PaymentsPreProcessingData {
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> {
self.payment_method_type
.to_owned()
.ok_or_else(missing_field_err("payment_method_type"))
}
fn get_currency(&self) -> Result<enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
fn get_amount(&self) -> Result<i64, Error> {
self.amount.ok_or_else(missing_field_err("amount"))
}
// New minor amount function for amount framework
fn get_minor_amount(&self) -> Result<MinorUnit, Error> {
self.minor_amount.ok_or_else(missing_field_err("amount"))
}
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| None
| Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> {
self.order_details
.clone()
.ok_or_else(missing_field_err("order_details"))
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_router_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_complete_authorize_url(&self) -> Result<String, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
}
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> {
self.redirect_response
.as_ref()
.and_then(|res| res.payload.to_owned())
.ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
}
.into(),
)
}
fn connector_mandate_id(&self) -> Option<String> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_id()
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/api_keys.rs | crates/router/src/routes/api_keys.rs | use actix_web::{web, HttpRequest, Responder};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_keys, api_locking},
services::{api, authentication as auth, authorization::permissions::Permission},
types::api as api_types,
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyCreate))]
pub async fn api_key_create(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<api_types::CreateApiKeyRequest>,
) -> impl Responder {
let flow = Flow::ApiKeyCreate;
let payload = json_payload.into_inner();
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth_data, payload, _| {
let key_store = auth_data.platform.get_processor().get_key_store().clone();
async move { api_keys::create_api_key(state, payload, key_store).await }
},
auth::auth_type(
&auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
merchant_id_from_route: merchant_id.clone(),
is_admin_auth_allowed: true,
},
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyCreate))]
pub async fn api_key_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_types::CreateApiKeyRequest>,
) -> impl Responder {
let flow = Flow::ApiKeyCreate;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth::AuthenticationDataWithoutProfile { key_store, .. }, payload, _| async {
api_keys::create_api_key(state, payload, key_store).await
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyRetrieve))]
pub async fn api_key_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::ApiKeyId>,
) -> impl Responder {
let flow = Flow::ApiKeyRetrieve;
let key_id = path.into_inner();
api::server_wrap(
flow,
state,
&req,
&key_id,
|state,
auth::AuthenticationDataWithoutProfile {
merchant_account, ..
},
key_id,
_| {
api_keys::retrieve_api_key(
state,
merchant_account.get_id().to_owned(),
key_id.to_owned(),
)
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyRetrieve))]
pub async fn api_key_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ApiKeyId,
)>,
) -> impl Responder {
let flow = Flow::ApiKeyRetrieve;
let (merchant_id, key_id) = path.into_inner();
api::server_wrap(
flow,
state,
&req,
(merchant_id.clone(), key_id.clone()),
|state, _, (merchant_id, key_id), _| api_keys::retrieve_api_key(state, merchant_id, key_id),
auth::auth_type(
&auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
merchant_id_from_route: merchant_id.clone(),
is_admin_auth_allowed: true,
},
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyUpdate))]
pub async fn api_key_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ApiKeyId,
)>,
json_payload: web::Json<api_types::UpdateApiKeyRequest>,
) -> impl Responder {
let flow = Flow::ApiKeyUpdate;
let (merchant_id, key_id) = path.into_inner();
let mut payload = json_payload.into_inner();
payload.key_id = key_id;
payload.merchant_id.clone_from(&merchant_id);
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| api_keys::update_api_key(state, payload),
auth::auth_type(
&auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
merchant_id_from_route: merchant_id.clone(),
is_admin_auth_allowed: true,
},
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
pub async fn api_key_update(
state: web::Data<AppState>,
req: HttpRequest,
key_id: web::Path<common_utils::id_type::ApiKeyId>,
json_payload: web::Json<api_types::UpdateApiKeyRequest>,
) -> impl Responder {
let flow = Flow::ApiKeyUpdate;
let api_key_id = key_id.into_inner();
let mut payload = json_payload.into_inner();
payload.key_id = api_key_id;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state,
auth::AuthenticationDataWithoutProfile {
merchant_account, ..
},
mut payload,
_| {
payload.merchant_id = merchant_account.get_id().to_owned();
api_keys::update_api_key(state, payload)
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyRevoke))]
pub async fn api_key_revoke(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ApiKeyId,
)>,
) -> impl Responder {
let flow = Flow::ApiKeyRevoke;
let (merchant_id, key_id) = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
(&merchant_id, &key_id),
|state, _, (merchant_id, key_id), _| {
api_keys::revoke_api_key(state, merchant_id.clone(), key_id)
},
auth::auth_type(
&auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
merchant_id_from_route: merchant_id.clone(),
is_admin_auth_allowed: true,
},
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyRevoke))]
pub async fn api_key_revoke(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::ApiKeyId>,
) -> impl Responder {
let flow = Flow::ApiKeyRevoke;
let key_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
&key_id,
|state,
auth::AuthenticationDataWithoutProfile {
merchant_account, ..
},
key_id,
_| api_keys::revoke_api_key(state, merchant_account.get_id().to_owned(), key_id),
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyList))]
pub async fn api_key_list(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
query: web::Query<api_types::ListApiKeyConstraints>,
) -> impl Responder {
let flow = Flow::ApiKeyList;
let list_api_key_constraints = query.into_inner();
let limit = list_api_key_constraints.limit;
let offset = list_api_key_constraints.skip;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
(limit, offset, merchant_id.clone()),
|state, _, (limit, offset, merchant_id), _| async move {
api_keys::list_api_keys(state, merchant_id, limit, offset).await
},
auth::auth_type(
&auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
merchant_id_from_route: merchant_id.clone(),
is_admin_auth_allowed: true,
},
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyList))]
pub async fn api_key_list(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<api_types::ListApiKeyConstraints>,
) -> impl Responder {
let flow = Flow::ApiKeyList;
let payload = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state,
auth::AuthenticationDataWithoutProfile {
merchant_account, ..
},
payload,
_| async move {
let merchant_id = merchant_account.get_id().to_owned();
api_keys::list_api_keys(state, merchant_id, payload.limit, payload.skip).await
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/app.rs | crates/router/src/routes/app.rs | use std::{collections::HashMap, sync::Arc};
use actix_web::{web, Scope};
#[cfg(all(feature = "olap", feature = "v1"))]
use api_models::routing::RoutingRetrieveQuery;
use api_models::routing::RuleMigrationQuery;
#[cfg(feature = "olap")]
use common_enums::{ExecutionMode, TransactionType};
#[cfg(feature = "partial-auth")]
use common_utils::crypto::Blake3;
use common_utils::{
id_type,
types::{keymanager::KeyManagerState, TenantConfig},
};
#[cfg(feature = "email")]
use external_services::email::{
no_email::NoEmailClient, ses::AwsSes, smtp::SmtpServer, EmailClientConfigs, EmailService,
};
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use external_services::grpc_client::revenue_recovery::GrpcRecoveryHeaders;
use external_services::{
file_storage::FileStorageInterface,
grpc_client::{GrpcClients, GrpcHeaders, GrpcHeadersUcs, GrpcHeadersUcsBuilderInitial},
superposition::SuperpositionClient,
};
use hyperswitch_interfaces::{
crm::CrmInterface,
encryption_interface::EncryptionManagementInterface,
helpers as interfaces_helpers,
secrets_interface::secret_state::{RawSecret, SecuredSecret},
types as interfaces_types,
};
use router_env::RequestId;
use scheduler::SchedulerInterface;
use storage_impl::{redis::RedisStore, MockDb};
use tokio::sync::oneshot;
use self::settings::Tenant;
#[cfg(any(feature = "olap", feature = "oltp"))]
use super::currency;
#[cfg(feature = "dummy_connector")]
use super::dummy_connector::*;
#[cfg(all(any(feature = "v1", feature = "v2"), feature = "oltp"))]
use super::ephemeral_key::*;
#[cfg(any(feature = "olap", feature = "oltp"))]
use super::payment_methods;
#[cfg(feature = "payouts")]
use super::payout_link::*;
#[cfg(feature = "payouts")]
use super::payouts::*;
#[cfg(all(feature = "oltp", feature = "v1"))]
use super::pm_auth;
#[cfg(feature = "oltp")]
use super::poll;
#[cfg(feature = "v2")]
use super::proxy;
#[cfg(all(feature = "v2", feature = "revenue_recovery", feature = "oltp"))]
use super::recovery_webhooks::*;
#[cfg(all(feature = "oltp", feature = "v2"))]
use super::refunds;
#[cfg(feature = "olap")]
use super::routing;
#[cfg(all(feature = "oltp", feature = "v2"))]
use super::tokenization as tokenization_routes;
#[cfg(all(feature = "olap", any(feature = "v1", feature = "v2")))]
use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains};
#[cfg(feature = "oltp")]
use super::webhooks::*;
use super::{
admin, api_keys, cache::*, chat, connector_onboarding, disputes, files, gsm, health::*, oidc,
profiles, relay, user, user_role,
};
#[cfg(feature = "v1")]
use super::{
apple_pay_certificates_migration, blocklist, payment_link, subscription, webhook_events,
};
#[cfg(any(feature = "olap", feature = "oltp"))]
use super::{configs::*, customers, payments};
#[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))]
use super::{mandates::*, refunds::*};
#[cfg(feature = "olap")]
pub use crate::analytics::opensearch::OpenSearchClient;
#[cfg(feature = "olap")]
use crate::analytics::AnalyticsProvider;
#[cfg(feature = "partial-auth")]
use crate::errors::RouterResult;
#[cfg(feature = "oltp")]
use crate::routes::authentication;
#[cfg(feature = "v1")]
use crate::routes::cards_info::{
card_iin_info, create_cards_info, migrate_cards_info, update_cards_info,
};
#[cfg(all(feature = "olap", feature = "v1"))]
use crate::routes::feature_matrix;
#[cfg(all(feature = "frm", feature = "oltp"))]
use crate::routes::fraud_check as frm_routes;
#[cfg(all(feature = "olap", feature = "v1"))]
use crate::routes::profile_acquirer;
#[cfg(all(feature = "recon", feature = "olap"))]
use crate::routes::recon as recon_routes;
pub use crate::{
configs::settings,
db::{
AccountsStorageInterface, CommonStorageInterface, GlobalStorageInterface, StorageImpl,
StorageInterface,
},
events::EventsHandler,
services::{get_cache_store, get_store},
types::transformers::ForeignFrom,
};
use crate::{
configs::{secrets_transformers, Settings},
db::kafka_store::{KafkaStore, TenantID},
routes::{hypersense as hypersense_routes, three_ds_decision_rule},
};
#[derive(Clone)]
pub struct ReqState {
pub event_context: events::EventContext<crate::events::EventType, EventsHandler>,
}
#[derive(Clone)]
pub struct SessionState {
pub store: Box<dyn StorageInterface>,
/// Global store is used for global schema operations in tables like Users and Tenants
pub global_store: Box<dyn GlobalStorageInterface>,
pub accounts_store: Box<dyn AccountsStorageInterface>,
pub conf: Arc<settings::Settings<RawSecret>>,
pub api_client: Box<dyn crate::services::ApiClient>,
pub event_handler: EventsHandler,
#[cfg(feature = "email")]
pub email_client: Arc<Box<dyn EmailService>>,
#[cfg(feature = "olap")]
pub pool: AnalyticsProvider,
pub file_storage_client: Arc<dyn FileStorageInterface>,
pub request_id: Option<RequestId>,
pub base_url: String,
pub tenant: Tenant,
#[cfg(feature = "olap")]
pub opensearch_client: Option<Arc<OpenSearchClient>>,
pub grpc_client: Arc<GrpcClients>,
pub theme_storage_client: Arc<dyn FileStorageInterface>,
pub locale: String,
pub crm_client: Arc<dyn CrmInterface>,
pub infra_components: Option<serde_json::Value>,
pub enhancement: Option<HashMap<String, String>>,
pub superposition_service: Option<Arc<SuperpositionClient>>,
}
impl scheduler::SchedulerSessionState for SessionState {
fn get_db(&self) -> Box<dyn SchedulerInterface> {
self.store.get_scheduler_db()
}
fn get_application_source(&self) -> common_enums::ApplicationSource {
self.conf.application_source
}
}
impl SessionState {
pub fn set_store(&mut self, store: Box<dyn StorageInterface>) {
self.store = store;
}
pub fn get_req_state(&self) -> ReqState {
ReqState {
event_context: events::EventContext::new(self.event_handler.clone()),
}
}
pub fn get_grpc_headers(&self) -> GrpcHeaders {
GrpcHeaders {
tenant_id: self.tenant.tenant_id.get_string_repr().to_string(),
request_id: self.request_id.as_ref().map(|req_id| req_id.to_string()),
}
}
pub fn get_grpc_headers_ucs(
&self,
unified_connector_service_execution_mode: ExecutionMode,
) -> GrpcHeadersUcsBuilderInitial {
let tenant_id = self.tenant.tenant_id.get_string_repr().to_string();
let request_id = self.request_id.clone();
let shadow_mode = match unified_connector_service_execution_mode {
ExecutionMode::Primary => Some(false),
ExecutionMode::Shadow => Some(true),
ExecutionMode::NotApplicable => None,
};
GrpcHeadersUcs::builder()
.tenant_id(tenant_id)
.request_id(request_id)
.shadow_mode(shadow_mode)
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
pub fn get_recovery_grpc_headers(&self) -> GrpcRecoveryHeaders {
GrpcRecoveryHeaders {
request_id: self.request_id.as_ref().map(|req_id| req_id.to_string()),
}
}
}
pub trait SessionStateInfo {
fn conf(&self) -> settings::Settings<RawSecret>;
fn store(&self) -> Box<dyn StorageInterface>;
fn event_handler(&self) -> EventsHandler;
fn get_request_id(&self) -> Option<String>;
fn add_request_id(&mut self, request_id: RequestId);
#[cfg(feature = "partial-auth")]
fn get_detached_auth(&self) -> RouterResult<(Blake3, &[u8])>;
fn session_state(&self) -> SessionState;
fn global_store(&self) -> Box<dyn GlobalStorageInterface>;
}
impl SessionStateInfo for SessionState {
fn store(&self) -> Box<dyn StorageInterface> {
self.store.to_owned()
}
fn conf(&self) -> settings::Settings<RawSecret> {
self.conf.as_ref().to_owned()
}
fn event_handler(&self) -> EventsHandler {
self.event_handler.clone()
}
fn get_request_id(&self) -> Option<String> {
self.api_client.get_request_id_str()
}
fn add_request_id(&mut self, request_id: RequestId) {
self.api_client.add_request_id(request_id.clone());
self.store.add_request_id(request_id.to_string());
self.request_id.replace(request_id);
}
#[cfg(feature = "partial-auth")]
fn get_detached_auth(&self) -> RouterResult<(Blake3, &[u8])> {
use error_stack::ResultExt;
use hyperswitch_domain_models::errors::api_error_response as errors;
use masking::prelude::PeekInterface as _;
use router_env::logger;
let output = CHECKSUM_KEY.get_or_try_init(|| {
let conf = self.conf();
let context = conf
.api_keys
.get_inner()
.checksum_auth_context
.peek()
.clone();
let key = conf.api_keys.get_inner().checksum_auth_key.peek();
hex::decode(key).map(|key| {
(
masking::StrongSecret::new(context),
masking::StrongSecret::new(key),
)
})
});
match output {
Ok((context, key)) => Ok((Blake3::new(context.peek().clone()), key.peek())),
Err(err) => {
logger::error!("Failed to get checksum key");
Err(err).change_context(errors::ApiErrorResponse::InternalServerError)
}
}
}
fn session_state(&self) -> SessionState {
self.clone()
}
fn global_store(&self) -> Box<dyn GlobalStorageInterface> {
self.global_store.to_owned()
}
}
impl interfaces_helpers::GetComparisonServiceConfig for SessionState {
fn get_comparison_service_config(&self) -> Option<interfaces_types::ComparisonServiceConfig> {
self.conf.comparison_service.clone()
}
}
impl hyperswitch_interfaces::api_client::ApiClientWrapper for SessionState {
fn get_api_client(&self) -> &dyn crate::services::ApiClient {
self.api_client.as_ref()
}
fn get_proxy(&self) -> hyperswitch_interfaces::types::Proxy {
self.conf.proxy.clone()
}
fn get_request_id(&self) -> Option<RequestId> {
self.request_id.clone()
}
fn get_request_id_str(&self) -> Option<String> {
self.request_id.as_ref().map(|req_id| req_id.to_string())
}
fn get_tenant(&self) -> Tenant {
self.tenant.clone()
}
fn get_connectors(&self) -> hyperswitch_domain_models::connector_endpoints::Connectors {
self.conf.connectors.clone()
}
fn event_handler(&self) -> &dyn hyperswitch_interfaces::events::EventHandlerInterface {
&self.event_handler
}
}
#[derive(Clone)]
pub struct AppState {
pub flow_name: String,
pub global_store: Box<dyn GlobalStorageInterface>,
// TODO: use a separate schema for accounts_store
pub accounts_store: HashMap<id_type::TenantId, Box<dyn AccountsStorageInterface>>,
pub stores: HashMap<id_type::TenantId, Box<dyn StorageInterface>>,
pub conf: Arc<settings::Settings<RawSecret>>,
pub event_handler: EventsHandler,
#[cfg(feature = "email")]
pub email_client: Arc<Box<dyn EmailService>>,
pub api_client: Box<dyn crate::services::ApiClient>,
#[cfg(feature = "olap")]
pub pools: HashMap<id_type::TenantId, AnalyticsProvider>,
#[cfg(feature = "olap")]
pub opensearch_client: Option<Arc<OpenSearchClient>>,
pub request_id: Option<RequestId>,
pub file_storage_client: Arc<dyn FileStorageInterface>,
pub encryption_client: Arc<dyn EncryptionManagementInterface>,
pub grpc_client: Arc<GrpcClients>,
pub theme_storage_client: Arc<dyn FileStorageInterface>,
pub crm_client: Arc<dyn CrmInterface>,
pub infra_components: Option<serde_json::Value>,
pub enhancement: Option<HashMap<String, String>>,
pub superposition_service: Option<Arc<SuperpositionClient>>,
}
impl scheduler::SchedulerAppState for AppState {
fn get_tenants(&self) -> Vec<id_type::TenantId> {
self.conf.multitenancy.get_tenant_ids()
}
}
pub trait AppStateInfo {
fn conf(&self) -> settings::Settings<RawSecret>;
fn event_handler(&self) -> EventsHandler;
#[cfg(feature = "email")]
fn email_client(&self) -> Arc<Box<dyn EmailService>>;
fn add_request_id(&mut self, request_id: RequestId);
fn add_flow_name(&mut self, flow_name: String);
fn get_request_id(&self) -> Option<String>;
}
#[cfg(feature = "partial-auth")]
static CHECKSUM_KEY: once_cell::sync::OnceCell<(
masking::StrongSecret<String>,
masking::StrongSecret<Vec<u8>>,
)> = once_cell::sync::OnceCell::new();
impl AppStateInfo for AppState {
fn conf(&self) -> settings::Settings<RawSecret> {
self.conf.as_ref().to_owned()
}
#[cfg(feature = "email")]
fn email_client(&self) -> Arc<Box<dyn EmailService>> {
self.email_client.to_owned()
}
fn event_handler(&self) -> EventsHandler {
self.event_handler.clone()
}
fn add_request_id(&mut self, request_id: RequestId) {
self.api_client.add_request_id(request_id.clone());
self.request_id.replace(request_id);
}
fn add_flow_name(&mut self, flow_name: String) {
self.api_client.add_flow_name(flow_name);
}
fn get_request_id(&self) -> Option<String> {
self.api_client.get_request_id_str()
}
}
impl AsRef<Self> for AppState {
fn as_ref(&self) -> &Self {
self
}
}
#[cfg(feature = "email")]
pub async fn create_email_client(
settings: &settings::Settings<RawSecret>,
) -> Box<dyn EmailService> {
match &settings.email.client_config {
EmailClientConfigs::Ses { aws_ses } => Box::new(
AwsSes::create(
&settings.email,
aws_ses,
settings.proxy.https_url.to_owned(),
)
.await,
),
EmailClientConfigs::Smtp { smtp } => {
Box::new(SmtpServer::create(&settings.email, smtp.clone()).await)
}
EmailClientConfigs::NoEmailClient => Box::new(NoEmailClient::create().await),
}
}
impl AppState {
/// # Panics
///
/// Panics if Store can't be created or JWE decryption fails
pub async fn with_storage(
conf: settings::Settings<SecuredSecret>,
storage_impl: StorageImpl,
shut_down_signal: oneshot::Sender<()>,
api_client: Box<dyn crate::services::ApiClient>,
) -> Self {
#[allow(clippy::expect_used)]
let secret_management_client = conf
.secrets_management
.get_secret_management_client()
.await
.expect("Failed to create secret management client");
let conf = Box::pin(secrets_transformers::fetch_raw_secrets(
conf,
&*secret_management_client,
))
.await;
#[allow(clippy::expect_used)]
let encryption_client = conf
.encryption_management
.get_encryption_management_client()
.await
.expect("Failed to create encryption client");
Box::pin(async move {
let testable = storage_impl == StorageImpl::PostgresqlTest;
#[allow(clippy::expect_used)]
let event_handler = conf
.events
.get_event_handler()
.await
.expect("Failed to create event handler");
#[allow(clippy::expect_used)]
#[cfg(feature = "olap")]
let opensearch_client = conf
.opensearch
.get_opensearch_client()
.await
.expect("Failed to initialize OpenSearch client.")
.map(Arc::new);
#[allow(clippy::expect_used)]
let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable)
.await
.expect("Failed to create store");
let global_store: Box<dyn GlobalStorageInterface> = Box::pin(Self::get_store_interface(
&storage_impl,
&event_handler,
&conf,
&conf.multitenancy.global_tenant,
Arc::clone(&cache_store),
testable,
))
.await
.get_global_storage_interface();
#[cfg(feature = "olap")]
let pools = conf
.multitenancy
.tenants
.get_pools_map(conf.analytics.get_inner())
.await;
let stores = conf
.multitenancy
.tenants
.get_store_interface_map(&storage_impl, &conf, Arc::clone(&cache_store), testable)
.await;
let accounts_store = conf
.multitenancy
.tenants
.get_accounts_store_interface_map(
&storage_impl,
&conf,
Arc::clone(&cache_store),
testable,
)
.await;
#[cfg(feature = "email")]
let email_client = Arc::new(create_email_client(&conf).await);
let file_storage_client = conf.file_storage.get_file_storage_client().await;
let theme_storage_client = conf.theme.storage.get_file_storage_client().await;
let crm_client = conf.crm.get_crm_client().await;
let grpc_client = conf.grpc_client.get_grpc_client_interface().await;
let infra_component_values = Self::process_env_mappings(conf.infra_values.clone());
let enhancement = conf.enhancement.clone();
let superposition_service = if conf.superposition.get_inner().enabled {
match SuperpositionClient::new(conf.superposition.get_inner().clone()).await {
Ok(client) => {
router_env::logger::info!("Superposition client initialized successfully");
Some(Arc::new(client))
}
Err(err) => {
router_env::logger::warn!(
"Failed to initialize superposition client: {:?}. Continuing without superposition support.",
err
);
None
}
}
} else {
None
};
Self {
flow_name: String::from("default"),
stores,
global_store,
accounts_store,
conf: Arc::new(conf),
#[cfg(feature = "email")]
email_client,
api_client,
event_handler,
#[cfg(feature = "olap")]
pools,
#[cfg(feature = "olap")]
opensearch_client,
request_id: None,
file_storage_client,
encryption_client,
grpc_client,
theme_storage_client,
crm_client,
infra_components: infra_component_values,
enhancement,
superposition_service,
}
})
.await
}
/// # Panics
///
/// Panics if Failed to create store
pub async fn get_store_interface(
storage_impl: &StorageImpl,
event_handler: &EventsHandler,
conf: &Settings,
tenant: &dyn TenantConfig,
cache_store: Arc<RedisStore>,
testable: bool,
) -> Box<dyn CommonStorageInterface> {
let km_conf = conf.key_manager.get_inner();
let key_manager_state = KeyManagerState {
global_tenant_id: conf.multitenancy.global_tenant.tenant_id.clone(),
tenant_id: tenant.get_tenant_id().clone(),
enabled: km_conf.enabled,
url: km_conf.url.clone(),
client_idle_timeout: conf.proxy.idle_pool_connection_timeout,
#[cfg(feature = "km_forward_x_request_id")]
request_id: None,
#[cfg(feature = "keymanager_mtls")]
cert: km_conf.cert.clone(),
#[cfg(feature = "keymanager_mtls")]
ca: km_conf.ca.clone(),
infra_values: Self::process_env_mappings(conf.infra_values.clone()),
};
match storage_impl {
StorageImpl::Postgresql | StorageImpl::PostgresqlTest => match event_handler {
EventsHandler::Kafka(kafka_client) => Box::new(
KafkaStore::new(
#[allow(clippy::expect_used)]
get_store(
&conf.clone(),
tenant,
Arc::clone(&cache_store),
testable,
key_manager_state,
)
.await
.expect("Failed to create store"),
kafka_client.clone(),
TenantID(tenant.get_tenant_id().get_string_repr().to_owned()),
tenant,
)
.await,
),
EventsHandler::Logs(_) => Box::new(
#[allow(clippy::expect_used)]
get_store(
conf,
tenant,
Arc::clone(&cache_store),
testable,
key_manager_state,
)
.await
.expect("Failed to create store"),
),
},
#[allow(clippy::expect_used)]
StorageImpl::Mock => Box::new(
MockDb::new(&conf.redis, key_manager_state)
.await
.expect("Failed to create mock store"),
),
}
}
pub async fn new(
conf: settings::Settings<SecuredSecret>,
shut_down_signal: oneshot::Sender<()>,
api_client: Box<dyn crate::services::ApiClient>,
) -> Self {
Box::pin(Self::with_storage(
conf,
StorageImpl::Postgresql,
shut_down_signal,
api_client,
))
.await
}
pub fn get_session_state<E, F>(
self: Arc<Self>,
tenant: &id_type::TenantId,
locale: Option<String>,
err: F,
) -> Result<SessionState, E>
where
F: FnOnce() -> E + Copy,
{
let tenant_conf = self.conf.multitenancy.get_tenant(tenant).ok_or_else(err)?;
let mut event_handler = self.event_handler.clone();
event_handler.add_tenant(tenant_conf);
let mut store = self.stores.get(tenant).ok_or_else(err)?.clone();
let key_manager_state = KeyManagerState::foreign_from((self.as_ref(), tenant_conf.clone()));
store.set_key_manager_state(key_manager_state);
Ok(SessionState {
store,
global_store: self.global_store.clone(),
accounts_store: self.accounts_store.get(tenant).ok_or_else(err)?.clone(),
conf: Arc::clone(&self.conf),
api_client: self.api_client.clone(),
event_handler,
#[cfg(feature = "olap")]
pool: self.pools.get(tenant).ok_or_else(err)?.clone(),
file_storage_client: self.file_storage_client.clone(),
request_id: self.request_id.clone(),
base_url: tenant_conf.base_url.clone(),
tenant: tenant_conf.clone(),
#[cfg(feature = "email")]
email_client: Arc::clone(&self.email_client),
#[cfg(feature = "olap")]
opensearch_client: self.opensearch_client.clone(),
grpc_client: Arc::clone(&self.grpc_client),
theme_storage_client: self.theme_storage_client.clone(),
locale: locale.unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string()),
crm_client: self.crm_client.clone(),
infra_components: self.infra_components.clone(),
enhancement: self.enhancement.clone(),
superposition_service: self.superposition_service.clone(),
})
}
pub fn process_env_mappings(
mappings: Option<HashMap<String, String>>,
) -> Option<serde_json::Value> {
let result: HashMap<String, String> = mappings?
.into_iter()
.filter_map(|(key, env_var)| std::env::var(&env_var).ok().map(|value| (key, value)))
.collect();
if result.is_empty() {
None
} else {
Some(serde_json::Value::Object(
result
.into_iter()
.map(|(k, v)| (k, serde_json::Value::String(v)))
.collect(),
))
}
}
}
pub struct Health;
#[cfg(feature = "v1")]
impl Health {
pub fn server(state: AppState) -> Scope {
web::scope("health")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::get().to(health)))
.service(web::resource("/ready").route(web::get().to(deep_health_check)))
}
}
#[cfg(feature = "v2")]
impl Health {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/health")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::get().to(health)))
.service(web::resource("/ready").route(web::get().to(deep_health_check)))
}
}
#[cfg(feature = "dummy_connector")]
pub struct DummyConnector;
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
impl DummyConnector {
pub fn server(state: AppState) -> Scope {
let mut routes_with_restricted_access = web::scope("");
#[cfg(not(feature = "external_access_dc"))]
{
routes_with_restricted_access =
routes_with_restricted_access.guard(actix_web::guard::Host("localhost"));
}
routes_with_restricted_access = routes_with_restricted_access
.service(web::resource("/payment").route(web::post().to(dummy_connector_payment)))
.service(
web::resource("/payments/{payment_id}")
.route(web::get().to(dummy_connector_payment_data)),
)
.service(
web::resource("/{payment_id}/refund").route(web::post().to(dummy_connector_refund)),
)
.service(
web::resource("/refunds/{refund_id}")
.route(web::get().to(dummy_connector_refund_data)),
);
web::scope("/dummy-connector")
.app_data(web::Data::new(state))
.service(
web::resource("/authorize/{attempt_id}")
.route(web::get().to(dummy_connector_authorize_payment)),
)
.service(
web::resource("/complete/{attempt_id}")
.route(web::get().to(dummy_connector_complete_payment)),
)
.service(routes_with_restricted_access)
}
}
#[cfg(all(feature = "dummy_connector", feature = "v2"))]
impl DummyConnector {
pub fn server(state: AppState) -> Scope {
let mut routes_with_restricted_access = web::scope("");
#[cfg(not(feature = "external_access_dc"))]
{
routes_with_restricted_access =
routes_with_restricted_access.guard(actix_web::guard::Host("localhost"));
}
routes_with_restricted_access = routes_with_restricted_access
.service(web::resource("/payment").route(web::post().to(dummy_connector_payment)));
web::scope("/dummy-connector")
.app_data(web::Data::new(state))
.service(routes_with_restricted_access)
}
}
pub struct Payments;
#[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v2"))]
impl Payments {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/v2/payments").app_data(web::Data::new(state));
route = route
.service(
web::resource("/create-intent")
.route(web::post().to(payments::payments_create_intent)),
)
.service(web::resource("/filter").route(web::get().to(payments::get_payment_filters)))
.service(
web::resource("/profile/filter")
.route(web::get().to(payments::get_payment_filters_profile)),
)
.service(
web::resource("")
.route(web::post().to(payments::payments_create_and_confirm_intent)),
)
.service(web::resource("/list").route(web::get().to(payments::payments_list)))
.service(
web::resource("/recovery-list")
.route(web::get().to(payments::revenue_recovery_invoices_list)),
)
.service(
web::resource("/aggregate").route(web::get().to(payments::get_payments_aggregates)),
)
.service(
web::resource("/recovery")
.route(web::post().to(payments::recovery_payments_create)),
)
.service(
web::resource("/profile/aggregate")
.route(web::get().to(payments::get_payments_aggregates_profile)),
);
route =
route
.service(web::resource("/ref/{merchant_reference_id}").route(
web::get().to(payments::payment_get_intent_using_merchant_reference_id),
));
route = route.service(
web::scope("/{payment_id}")
.service(
web::resource("/confirm-intent")
.route(web::post().to(payments::payment_confirm_intent)),
)
// TODO: Deprecated. Remove this in favour of /list-attempts
.service(
web::resource("/list_attempts")
.route(web::get().to(payments::list_payment_attempts)),
)
.service(
web::resource("/list-attempts")
.route(web::get().to(payments::list_payment_attempts)),
)
.service(
web::resource("/proxy-confirm-intent")
.route(web::post().to(payments::proxy_confirm_intent)),
)
.service(
web::resource("/confirm-intent/external-vault-proxy")
.route(web::post().to(payments::confirm_intent_with_external_vault_proxy)),
)
.service(
web::resource("/get-intent")
.route(web::get().to(payments::payments_get_intent)),
)
.service(
web::resource("/get-revenue-recovery-intent")
.route(web::get().to(payments::revenue_recovery_get_intent)),
)
.service(
web::resource("/update-intent")
.route(web::put().to(payments::payments_update_intent)),
)
.service(
web::resource("/create-external-sdk-tokens")
.route(web::post().to(payments::payments_connector_session)),
)
.service(
web::resource("")
.route(web::get().to(payments::payment_status))
.route(web::post().to(payments::payments_status_with_gateway_creds)),
)
.service(
web::resource("/start-redirection")
.route(web::get().to(payments::payments_start_redirection)),
)
.service(web::scope("/payment-methods").service(
web::resource("").route(web::get().to(payments::list_payment_methods)),
))
.service(
web::resource("/eligibility/check-balance-and-apply-pm-data")
.route(web::post().to(payments::payments_apply_pm_data)),
)
.service(
web::resource("/finish-redirection/{publishable_key}/{profile_id}")
.route(web::get().to(payments::payments_finish_redirection)),
)
.service(
web::resource("/capture").route(web::post().to(payments::payments_capture)),
)
.service(web::resource("/cancel").route(web::post().to(payments::payments_cancel))),
);
route
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/mandates.rs | crates/router/src/routes/mandates.rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, mandate},
services::{api, authentication as auth, authorization::permissions::Permission},
types::api::mandates,
};
/// Mandates - Retrieve Mandate
///
/// Retrieves a mandate created using the Payments/Create API
#[instrument(skip_all, fields(flow = ?Flow::MandatesRetrieve))]
// #[get("/{id}")]
pub async fn get_mandate(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::MandatesRetrieve;
let mandate_id = mandates::MandateId {
mandate_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
mandate_id,
|state, auth: auth::AuthenticationData, req, _| {
mandate::get_mandate(state, auth.platform, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::MandatesRevoke))]
pub async fn revoke_mandate(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::MandatesRevoke;
let mandate_id = mandates::MandateId {
mandate_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
mandate_id,
|state, auth: auth::AuthenticationData, req, _| {
mandate::revoke_mandate(state, auth.platform, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Mandates - List Mandates
#[instrument(skip_all, fields(flow = ?Flow::MandatesList))]
pub async fn retrieve_mandates_list(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Query<api_models::mandates::MandateListConstraints>,
) -> HttpResponse {
let flow = Flow::MandatesList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
mandate::retrieve_mandates_list(state, auth.platform, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantMandateRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/user.rs | crates/router/src/routes/user.rs | pub mod theme;
use actix_web::{web, HttpRequest, HttpResponse};
#[cfg(feature = "dummy_connector")]
use api_models::user::sample_data::SampleDataRequest;
use api_models::{
errors::types::ApiErrorResponse,
user::{self as user_api},
};
use common_enums::TokenPurpose;
use common_utils::errors::ReportSwitchExt;
use router_env::Flow;
use super::AppState;
use crate::{
core::{api_locking, user as user_core},
services::{
api,
authentication::{self as auth},
authorization::permissions::Permission,
},
utils::user::dashboard_metadata::{parse_string_to_enums, set_ip_address_if_required},
};
pub async fn get_user_details(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::GetUserDetails;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, user, _, _| user_core::get_user_details(state, user),
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "email")]
pub async fn user_signup_with_merchant_id(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SignUpWithMerchantIdRequest>,
query: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::UserSignUpWithMerchantId;
let req_payload = json_payload.into_inner();
let query_params = query.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
|state, _, req_body, _| {
user_core::signup_with_merchant_id(
state,
req_body,
query_params.auth_id.clone(),
query_params.theme_id.clone(),
)
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn user_signup(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SignUpRequest>,
) -> HttpResponse {
let flow = Flow::UserSignUp;
let req_payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
|state, _: (), req_body, _| async move {
user_core::signup_token_only_flow(state, req_body).await
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn user_signin(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SignInRequest>,
) -> HttpResponse {
let flow = Flow::UserSignIn;
let req_payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
|state, _: (), req_body, _| async move {
user_core::signin_token_only_flow(state, req_body).await
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "email")]
pub async fn user_connect_account(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::ConnectAccountRequest>,
query: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::UserConnectAccount;
let req_payload = json_payload.into_inner();
let query_params = query.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
|state, _: (), req_body, _| {
user_core::connect_account(
state,
req_body,
query_params.auth_id.clone(),
query_params.theme_id.clone(),
)
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn signout(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse {
let flow = Flow::Signout;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
(),
|state, user, _, _| user_core::signout(state, user),
&auth::AnyPurposeOrLoginTokenAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn change_password(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::ChangePasswordRequest>,
) -> HttpResponse {
let flow = Flow::ChangePassword;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, user, req, _| user_core::change_password(state, req, user),
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn set_dashboard_metadata(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::dashboard_metadata::SetMetaDataRequest>,
) -> HttpResponse {
let flow = Flow::SetDashboardMetadata;
let mut payload = json_payload.into_inner();
if let Err(e) = ReportSwitchExt::<(), ApiErrorResponse>::switch(set_ip_address_if_required(
&mut payload,
req.headers(),
)) {
return api::log_and_return_error_response(e);
}
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
user_core::dashboard_metadata::set_metadata,
&auth::JWTAuth {
permission: Permission::ProfileAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_multiple_dashboard_metadata(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<user_api::dashboard_metadata::GetMultipleMetaDataRequest>,
) -> HttpResponse {
let flow = Flow::GetMultipleDashboardMetadata;
let payload = match ReportSwitchExt::<_, ApiErrorResponse>::switch(parse_string_to_enums(
query.into_inner().keys,
)) {
Ok(payload) => payload,
Err(e) => {
return api::log_and_return_error_response(e);
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
user_core::dashboard_metadata::get_multiple_metadata,
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn internal_user_signup(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::CreateInternalUserRequest>,
) -> HttpResponse {
let flow = Flow::InternalUserSignup;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, _, req, _| user_core::create_internal_user(state, req),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn create_tenant_user(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::CreateTenantUserRequest>,
) -> HttpResponse {
let flow = Flow::TenantUserCreate;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, _, req, _| user_core::create_tenant_user(state, req),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn create_platform(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::PlatformAccountCreateRequest>,
) -> HttpResponse {
let flow = Flow::CreatePlatformAccount;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, user: auth::UserFromToken, json_payload, _| {
user_core::create_platform_account(state, user, json_payload)
},
&auth::JWTAuth {
permission: Permission::OrganizationAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn user_org_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::UserOrgMerchantCreateRequest>,
) -> HttpResponse {
let flow = Flow::UserOrgMerchantCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _auth: auth::UserFromToken, json_payload, _| {
user_core::create_org_merchant_for_user(state, json_payload)
},
&auth::JWTAuth {
permission: Permission::TenantAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn user_merchant_account_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::UserMerchantCreate>,
) -> HttpResponse {
let flow = Flow::UserMerchantAccountCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::UserFromToken, json_payload, _| {
user_core::create_merchant_account(state, auth, json_payload)
},
&auth::JWTAuth {
permission: Permission::OrganizationAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
pub async fn generate_sample_data(
state: web::Data<AppState>,
http_req: HttpRequest,
payload: web::Json<SampleDataRequest>,
) -> impl actix_web::Responder {
use crate::core::user::sample_data;
let flow = Flow::GenerateSampleData;
Box::pin(api::server_wrap(
flow,
state,
&http_req,
payload.into_inner(),
sample_data::generate_sample_data_for_user,
&auth::JWTAuth {
permission: Permission::MerchantPaymentWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
pub async fn delete_sample_data(
state: web::Data<AppState>,
http_req: HttpRequest,
payload: web::Json<SampleDataRequest>,
) -> impl actix_web::Responder {
use crate::core::user::sample_data;
let flow = Flow::DeleteSampleData;
Box::pin(api::server_wrap(
flow,
state,
&http_req,
payload.into_inner(),
sample_data::delete_sample_data_for_user,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn list_user_roles_details(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::GetUserRoleDetailsRequest>,
) -> HttpResponse {
let flow = Flow::GetUserRoleDetails;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload.into_inner(),
user_core::list_user_roles_details,
&auth::JWTAuth {
permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn rotate_password(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::RotatePasswordRequest>,
) -> HttpResponse {
let flow = Flow::RotatePassword;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload.into_inner(),
user_core::rotate_password,
&auth::SinglePurposeJWTAuth(TokenPurpose::ForceSetPassword),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "email")]
pub async fn forgot_password(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::ForgotPasswordRequest>,
query: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::ForgotPassword;
let query_params = query.into_inner();
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload.into_inner(),
|state, _: (), payload, _| {
user_core::forgot_password(
state,
payload,
query_params.auth_id.clone(),
query_params.theme_id.clone(),
)
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "email")]
pub async fn reset_password(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::ResetPasswordRequest>,
) -> HttpResponse {
let flow = Flow::ResetPassword;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload.into_inner(),
|state, user, payload, _| user_core::reset_password_token_only_flow(state, user, payload),
&auth::SinglePurposeJWTAuth(TokenPurpose::ResetPassword),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn invite_multiple_user(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<Vec<user_api::InviteUserRequest>>,
auth_id_query_param: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::InviteMultipleUser;
let auth_id = auth_id_query_param.into_inner().auth_id;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload.into_inner(),
|state, user, payload, req_state| {
user_core::invite_multiple_user(state, user, payload, req_state, auth_id.clone())
},
&auth::JWTAuth {
permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "email")]
pub async fn resend_invite(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::ReInviteUserRequest>,
query: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::ReInviteUser;
let auth_id = query.into_inner().auth_id;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload.into_inner(),
|state, user, req_payload, _| {
user_core::resend_invite(state, user, req_payload, auth_id.clone())
},
&auth::JWTAuth {
permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "email")]
pub async fn accept_invite_from_email(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::AcceptInviteFromEmailRequest>,
query: web::Query<user_api::ValidateOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::AcceptInviteFromEmail;
let status_check = query.into_inner().status_check;
Box::pin(api::server_wrap(
flow.clone(),
state,
&req,
payload.into_inner(),
|state, user, req_payload, _| {
user_core::accept_invite_from_email_token_only_flow(
state,
user,
req_payload,
status_check,
)
},
&auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvitationFromEmail),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "email")]
pub async fn terminate_accept_invite(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::AcceptInviteFromEmailRequest>,
) -> HttpResponse {
let flow = Flow::AcceptInviteFromEmail;
Box::pin(api::server_wrap(
flow.clone(),
state,
&req,
payload.into_inner(),
|state, user, req_payload, _| {
user_core::terminate_accept_invite_only_flow(state, user, req_payload)
},
&auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvitationFromEmail),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "email")]
pub async fn verify_email(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::VerifyEmailRequest>,
) -> HttpResponse {
let flow = Flow::VerifyEmail;
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
json_payload.into_inner(),
|state, user, req_payload, _| {
user_core::verify_email_token_only_flow(state, user, req_payload)
},
&auth::SinglePurposeJWTAuth(TokenPurpose::VerifyEmail),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "email")]
pub async fn verify_email_request(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SendVerifyEmailRequest>,
query: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::VerifyEmailRequest;
let query_params = query.into_inner();
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, _: (), req_body, _| {
user_core::send_verification_mail(
state,
req_body,
query_params.auth_id.clone(),
query_params.theme_id.clone(),
)
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn update_user_account_details(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::UpdateUserAccountDetailsRequest>,
) -> HttpResponse {
let flow = Flow::UpdateUserAccountDetails;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
user_core::update_user_details,
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "email")]
pub async fn user_from_email(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::UserFromEmailRequest>,
) -> HttpResponse {
let flow = Flow::UserFromEmail;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, _: (), req_body, _| user_core::user_from_email(state, req_body),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn totp_begin(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::TotpBegin;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user, _, _| user_core::begin_totp(state, user),
&auth::SinglePurposeJWTAuth(TokenPurpose::TOTP),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn totp_reset(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::TotpReset;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user, _, _| user_core::reset_totp(state, user),
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn totp_verify(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::VerifyTotpRequest>,
) -> HttpResponse {
let flow = Flow::TotpVerify;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, user, req_body, _| user_core::verify_totp(state, user, req_body),
&auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn verify_recovery_code(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::VerifyRecoveryCodeRequest>,
) -> HttpResponse {
let flow = Flow::RecoveryCodeVerify;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, user, req_body, _| user_core::verify_recovery_code(state, user, req_body),
&auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn totp_update(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::VerifyTotpRequest>,
) -> HttpResponse {
let flow = Flow::TotpUpdate;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, user, req_body, _| user_core::update_totp(state, user, req_body),
&auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn generate_recovery_codes(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::RecoveryCodesGenerate;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user, _, _| user_core::generate_recovery_codes(state, user),
&auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn terminate_two_factor_auth(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<user_api::SkipTwoFactorAuthQueryParam>,
) -> HttpResponse {
let flow = Flow::TerminateTwoFactorAuth;
let skip_two_factor_auth = query.into_inner().skip_two_factor_auth.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user, _, _| user_core::terminate_two_factor_auth(state, user, skip_two_factor_auth),
&auth::SinglePurposeJWTAuth(TokenPurpose::TOTP),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn check_two_factor_auth_status(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::TwoFactorAuthStatus;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user, _, _| user_core::check_two_factor_auth_status(state, user),
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn check_two_factor_auth_status_with_attempts(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::TwoFactorAuthStatus;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user, _, _| user_core::check_two_factor_auth_status_with_attempts(state, user),
&auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn get_sso_auth_url(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<user_api::GetSsoAuthUrlRequest>,
) -> HttpResponse {
let flow = Flow::GetSsoAuthUrl;
let payload = query.into_inner();
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, _: (), req, _| user_core::get_sso_auth_url(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn sso_sign(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::SsoSignInRequest>,
) -> HttpResponse {
let flow = Flow::SignInWithSso;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, user: Option<auth::UserFromSinglePurposeToken>, payload, _| {
user_core::sso_sign(state, payload, user)
},
auth::auth_type(
&auth::NoAuth,
&auth::SinglePurposeJWTAuth(TokenPurpose::SSO),
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn create_user_authentication_method(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::CreateUserAuthenticationMethodRequest>,
) -> HttpResponse {
let flow = Flow::CreateUserAuthenticationMethod;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, _, req_body, _| user_core::create_user_authentication_method(state, req_body),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn update_user_authentication_method(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::UpdateUserAuthenticationMethodRequest>,
) -> HttpResponse {
let flow = Flow::UpdateUserAuthenticationMethod;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, _, req_body, _| user_core::update_user_authentication_method(state, req_body),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn list_user_authentication_methods(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<user_api::GetUserAuthenticationMethodsRequest>,
) -> HttpResponse {
let flow = Flow::ListUserAuthenticationMethods;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
query.into_inner(),
|state, _: (), req, _| user_core::list_user_authentication_methods(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn terminate_auth_select(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::AuthSelectRequest>,
) -> HttpResponse {
let flow = Flow::AuthSelect;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, user, req, _| user_core::terminate_auth_select(state, user, req),
&auth::SinglePurposeJWTAuth(TokenPurpose::AuthSelect),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn transfer_user_key(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::UserKeyTransferRequest>,
) -> HttpResponse {
let flow = Flow::UserTransferKey;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload.into_inner(),
|state, _, req, _| user_core::transfer_user_key_store_keymanager(state, req),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn list_orgs_for_user(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::ListOrgForUser;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user_from_token, _, _| user_core::list_orgs_for_user(state, user_from_token),
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn list_merchants_for_user_in_org(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::ListMerchantsForUserInOrg;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user_from_token, _, _| {
user_core::list_merchants_for_user_in_org(state, user_from_token)
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn list_profiles_for_user_in_org_and_merchant(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::ListProfileForUserInOrgAndMerchant;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user_from_token, _, _| {
user_core::list_profiles_for_user_in_org_and_merchant_account(state, user_from_token)
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn switch_org_for_user(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SwitchOrganizationRequest>,
) -> HttpResponse {
let flow = Flow::SwitchOrg;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, user, req, _| user_core::switch_org_for_user(state, req, user),
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn switch_merchant_for_user_in_org(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SwitchMerchantRequest>,
) -> HttpResponse {
let flow = Flow::SwitchMerchantV2;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, user, req, _| user_core::switch_merchant_for_user_in_org(state, req, user),
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn switch_profile_for_user_in_org_and_merchant(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SwitchProfileRequest>,
) -> HttpResponse {
let flow = Flow::SwitchProfile;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, user, req, _| {
user_core::switch_profile_for_user_in_org_and_merchant(state, req, user)
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn clone_connector(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::CloneConnectorRequest>,
) -> HttpResponse {
let flow = Flow::CloneConnector;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, _: auth::UserFromToken, req, _| user_core::clone_connector(state, req),
&auth::JWTAuth {
permission: Permission::MerchantInternalConnectorWrite,
},
api_locking::LockAction::NotApplicable,
))
.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/routes/blocklist.rs | crates/router/src/routes/blocklist.rs | use actix_web::{web, HttpRequest, HttpResponse};
use api_models::blocklist as api_blocklist;
use error_stack::report;
use router_env::Flow;
use crate::{
core::{api_locking, blocklist},
routes::AppState,
services::{api, authentication as auth, authorization::permissions::Permission},
};
#[utoipa::path(
post,
path = "/blocklist",
request_body = BlocklistRequest,
responses(
(status = 200, description = "Fingerprint Blocked", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Block a Fingerprint",
security(("api_key" = []))
)]
pub async fn add_entry_to_blocklist(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_blocklist::AddToBlocklistRequest>,
) -> HttpResponse {
let flow = Flow::AddToBlocklist;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, body, _| {
blocklist::add_entry_to_blocklist(state, auth.platform, body)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[utoipa::path(
delete,
path = "/blocklist",
request_body = BlocklistRequest,
responses(
(status = 200, description = "Fingerprint Unblocked", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Unblock a Fingerprint",
security(("api_key" = []))
)]
pub async fn remove_entry_from_blocklist(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_blocklist::DeleteFromBlocklistRequest>,
) -> HttpResponse {
let flow = Flow::DeleteFromBlocklist;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, body, _| {
blocklist::remove_entry_from_blocklist(state, auth.platform, body)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[utoipa::path(
get,
path = "/blocklist",
params (
("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"),
),
responses(
(status = 200, description = "Blocked Fingerprints", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "List Blocked fingerprints of a particular kind",
security(("api_key" = []))
)]
pub async fn list_blocked_payment_methods(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<api_blocklist::ListBlocklistQuery>,
) -> HttpResponse {
let flow = Flow::ListBlocklist;
let payload = query_payload.into_inner();
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, _) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, query, _| {
blocklist::list_blocklist_entries(state, auth.platform, query)
},
auth::auth_type(
&*auth_type,
&auth::JWTAuth {
permission: Permission::MerchantAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[utoipa::path(
post,
path = "/blocklist/toggle",
params (
("status" = bool, Query, description = "Boolean value to enable/disable blocklist"),
),
responses(
(status = 200, description = "Blocklist guard enabled/disabled", body = ToggleBlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Toggle blocklist guard for a particular merchant",
security(("api_key" = []))
)]
pub async fn toggle_blocklist_guard(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<api_blocklist::ToggleBlocklistQuery>,
) -> HttpResponse {
let flow = Flow::ListBlocklist;
Box::pin(api::server_wrap(
flow,
state,
&req,
query_payload.into_inner(),
|state, auth: auth::AuthenticationData, query, _| {
blocklist::toggle_blocklist_guard(state, auth.platform, query)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/profiles.rs | crates/router/src/routes/profiles.rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{admin::*, api_locking, errors},
services::{api, authentication as auth, authorization::permissions},
types::api::admin,
};
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::ProfileCreate))]
pub async fn profile_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<admin::ProfileCreate>,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::ProfileCreate;
let payload = json_payload.into_inner();
let merchant_id = path.into_inner();
if let Err(api_error) = payload
.payment_link_config
.as_ref()
.map(|config| {
config
.validate()
.map_err(|err| errors::ApiErrorResponse::InvalidRequestData { message: err })
})
.transpose()
{
return api::log_and_return_error_response(api_error.into());
}
if let Err(api_error) = payload
.webhook_details
.as_ref()
.map(|details| {
details
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
})
.transpose()
{
return api::log_and_return_error_response(api_error.into());
}
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth_data, req, _| {
create_profile(state, req, auth_data.platform.get_processor().clone())
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: permissions::Permission::MerchantAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all, fields(flow = ?Flow::ProfileCreate))]
pub async fn profile_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<admin::ProfileCreate>,
) -> HttpResponse {
let flow = Flow::ProfileCreate;
let payload = json_payload.into_inner();
if let Err(api_error) = payload
.webhook_details
.as_ref()
.map(|details| {
details
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
})
.transpose()
{
return api::log_and_return_error_response(api_error.into());
}
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state,
auth::AuthenticationDataWithoutProfile {
merchant_account,
key_store,
},
req,
_| {
let platform = hyperswitch_domain_models::platform::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account,
key_store,
None,
);
create_profile(state, req, platform.get_processor().clone())
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: permissions::Permission::MerchantAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ProfileRetrieve))]
pub async fn profile_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ProfileId,
)>,
) -> HttpResponse {
let flow = Flow::ProfileRetrieve;
let (merchant_id, profile_id) = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
profile_id,
|state, auth_data, profile_id, _| {
retrieve_profile(
state,
profile_id,
auth_data
.platform
.get_processor()
.get_account()
.get_id()
.clone(),
auth_data.platform.get_processor().get_key_store().clone(),
)
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: permissions::Permission::ProfileAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ProfileRetrieve))]
pub async fn profile_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::ProfileId>,
) -> HttpResponse {
let flow = Flow::ProfileRetrieve;
let profile_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
profile_id,
|state,
auth::AuthenticationDataWithoutProfile {
merchant_account,
key_store,
},
profile_id,
_| {
retrieve_profile(
state,
profile_id,
merchant_account.get_id().clone(),
key_store,
)
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: permissions::Permission::MerchantAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::ProfileUpdate))]
pub async fn profile_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ProfileId,
)>,
json_payload: web::Json<api_models::admin::ProfileUpdate>,
) -> HttpResponse {
let flow = Flow::ProfileUpdate;
let (merchant_id, profile_id) = path.into_inner();
let payload = json_payload.into_inner();
if let Err(api_error) = payload
.payment_link_config
.as_ref()
.map(|config| {
config
.validate()
.map_err(|err| errors::ApiErrorResponse::InvalidRequestData { message: err })
})
.transpose()
{
return api::log_and_return_error_response(api_error.into());
}
if let Err(api_error) = payload
.webhook_details
.as_ref()
.map(|details| {
details
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
})
.transpose()
{
return api::log_and_return_error_response(api_error.into());
}
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth_data, req, _| {
update_profile(
state,
&profile_id,
auth_data
.platform
.get_processor()
.get_account()
.get_id()
.clone(),
auth_data.platform.get_processor().get_key_store().clone(),
req,
)
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantAndProfileFromRoute {
merchant_id: merchant_id.clone(),
profile_id: profile_id.clone(),
required_permission: permissions::Permission::ProfileAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ProfileUpdate))]
pub async fn profile_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::ProfileId>,
json_payload: web::Json<api_models::admin::ProfileUpdate>,
) -> HttpResponse {
let flow = Flow::ProfileUpdate;
let profile_id = path.into_inner();
let payload = json_payload.into_inner();
if let Err(api_error) = payload
.webhook_details
.as_ref()
.map(|details| {
details
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
})
.transpose()
{
return api::log_and_return_error_response(api_error.into());
}
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state,
auth::AuthenticationDataWithoutProfile {
merchant_account,
key_store,
},
req,
_| {
update_profile(
state,
&profile_id,
merchant_account.get_id().clone(),
key_store,
req,
)
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: permissions::Permission::MerchantAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::ProfileDelete))]
pub async fn profile_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ProfileId,
)>,
) -> HttpResponse {
let flow = Flow::ProfileDelete;
let (merchant_id, profile_id) = path.into_inner();
api::server_wrap(
flow,
state,
&req,
profile_id,
|state, _, profile_id, _| delete_profile(state, profile_id, &merchant_id),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ProfileList))]
pub async fn profiles_list(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::ProfileList;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
merchant_id.clone(),
|state, auth, _, _| {
list_profile(
state,
auth.platform.get_processor().get_account().get_id().clone(),
None,
)
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: permissions::Permission::MerchantAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ProfileList))]
pub async fn profiles_list(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::ProfileList;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
merchant_id.clone(),
|state, auth::AuthenticationDataWithoutProfile { .. }, merchant_id, _| {
list_profile(state, merchant_id, None)
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: permissions::Permission::MerchantAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::ProfileList))]
pub async fn profiles_list_at_profile_level(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::ProfileList;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
merchant_id.clone(),
|state, auth, _, _| {
list_profile(
state,
auth.platform.get_processor().get_account().get_id().clone(),
auth.profile.map(|profile| vec![profile.get_id().clone()]),
)
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: permissions::Permission::ProfileAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::ToggleConnectorAgnosticMit))]
pub async fn toggle_connector_agnostic_mit(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ProfileId,
)>,
json_payload: web::Json<api_models::admin::ConnectorAgnosticMitChoice>,
) -> HttpResponse {
let flow = Flow::ToggleConnectorAgnosticMit;
let (merchant_id, profile_id) = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _: auth::AuthenticationData, req, _| {
connector_agnostic_mit_toggle(state, &merchant_id, &profile_id, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: permissions::Permission::MerchantRoutingWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::ToggleExtendedCardInfo))]
pub async fn toggle_extended_card_info(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ProfileId,
)>,
json_payload: web::Json<api_models::admin::ExtendedCardInfoChoice>,
) -> HttpResponse {
let flow = Flow::ToggleExtendedCardInfo;
let (merchant_id, profile_id) = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| extended_card_info_toggle(state, &merchant_id, &profile_id, req),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsList))]
pub async fn payment_connector_list_profile(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsList;
let merchant_id = path.into_inner();
api::server_wrap(
flow,
state,
&req,
merchant_id.to_owned(),
|state, auth, _, _| {
list_payment_connectors(
state,
auth.platform.get_processor().clone(),
auth.profile.map(|profile| vec![profile.get_id().clone()]),
)
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: permissions::Permission::ProfileConnectorRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
)
.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/routes/connector_onboarding.rs | crates/router/src/routes/connector_onboarding.rs | use actix_web::{web, HttpRequest, HttpResponse};
use api_models::connector_onboarding as api_types;
use router_env::Flow;
use super::AppState;
use crate::{
core::{api_locking, connector_onboarding as core},
services::{api, authentication as auth, authorization::permissions::Permission},
};
pub async fn get_action_url(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<api_types::ActionUrlRequest>,
) -> HttpResponse {
let flow = Flow::GetActionUrl;
let req_payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
core::get_action_url,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn sync_onboarding_status(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<api_types::OnboardingSyncRequest>,
) -> HttpResponse {
let flow = Flow::SyncOnboardingStatus;
let req_payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
core::sync_onboarding_status,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn reset_tracking_id(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<api_types::ResetTrackingIdRequest>,
) -> HttpResponse {
let flow = Flow::ResetTrackingId;
let req_payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
core::reset_tracking_id,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
.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/routes/hypersense.rs | crates/router/src/routes/hypersense.rs | use actix_web::{web, HttpRequest, HttpResponse};
use api_models::external_service_auth as external_service_auth_api;
use router_env::Flow;
use super::AppState;
use crate::{
core::{api_locking, external_service_auth},
services::{
api,
authentication::{self, ExternalServiceType},
},
};
pub async fn get_hypersense_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::HypersenseTokenRequest;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, user, _, _| {
external_service_auth::generate_external_token(
state,
user,
ExternalServiceType::Hypersense,
)
},
&authentication::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn signout_hypersense_token(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<external_service_auth_api::ExternalSignoutTokenRequest>,
) -> HttpResponse {
let flow = Flow::HypersenseSignoutToken;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, _: (), json_payload, _| {
external_service_auth::signout_external_token(state, json_payload)
},
&authentication::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn verify_hypersense_token(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<external_service_auth_api::ExternalVerifyTokenRequest>,
) -> HttpResponse {
let flow = Flow::HypersenseVerifyToken;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, _: (), json_payload, _| {
external_service_auth::verify_external_token(
state,
json_payload,
ExternalServiceType::Hypersense,
)
},
&authentication::NoAuth,
api_locking::LockAction::NotApplicable,
))
.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/routes/fraud_check.rs | crates/router/src/routes/fraud_check.rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::Flow;
use crate::{
core::{api_locking, fraud_check as frm_core},
services::{self, api},
AppState,
};
#[cfg(feature = "v1")]
pub async fn frm_fulfillment(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<frm_core::types::FrmFulfillmentRequest>,
) -> HttpResponse {
let flow = Flow::FrmFulfillment;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, auth: services::authentication::AuthenticationData, req, _| {
frm_core::frm_fulfillment_core(state, auth.platform, req)
},
&services::authentication::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.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/routes/revenue_recovery_data_backfill.rs | crates/router/src/routes/revenue_recovery_data_backfill.rs | use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::revenue_recovery_data_backfill::{
BackfillQuery, GetRedisDataQuery, RevenueRecoveryDataBackfillForm, UnlockStatusRequest,
UnlockStatusResponse, UpdateTokenStatusRequest,
};
use router_env::{instrument, tracing, Flow};
use crate::{
core::{api_locking, revenue_recovery_data_backfill},
routes::AppState,
services::{api, authentication as auth},
types::{domain, storage},
};
#[instrument(skip_all, fields(flow = ?Flow::RecoveryDataBackfill))]
pub async fn revenue_recovery_data_backfill(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<BackfillQuery>,
MultipartForm(form): MultipartForm<RevenueRecoveryDataBackfillForm>,
) -> HttpResponse {
let flow = Flow::RecoveryDataBackfill;
// Parse cutoff_time from query parameter
let cutoff_datetime = match query
.cutoff_time
.as_ref()
.map(|time_str| {
time::PrimitiveDateTime::parse(
time_str,
&time::format_description::well_known::Iso8601::DEFAULT,
)
})
.transpose()
{
Ok(datetime) => datetime,
Err(err) => {
return HttpResponse::BadRequest().json(serde_json::json!({
"error": format!("Invalid datetime format: {}. Use ISO8601: 2024-01-15T10:30:00", err)
}));
}
};
let records = match form.validate_and_get_records_with_errors() {
Ok(records) => records,
Err(e) => {
return HttpResponse::BadRequest().json(serde_json::json!({
"error": e.to_string()
}));
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
records,
|state, _, records, _req| {
revenue_recovery_data_backfill::revenue_recovery_data_backfill(
state,
records.records,
cutoff_datetime,
)
},
&auth::V2AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::RecoveryDataBackfill))]
pub async fn update_revenue_recovery_additional_redis_data(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<UpdateTokenStatusRequest>,
) -> HttpResponse {
let flow = Flow::RecoveryDataBackfill;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _: (), request, _| {
revenue_recovery_data_backfill::redis_update_additional_details_for_revenue_recovery(
state, request,
)
},
&auth::V2AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::RecoveryDataBackfill))]
pub async fn revenue_recovery_data_backfill_status(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(String, common_utils::id_type::GlobalPaymentId)>,
) -> HttpResponse {
let flow = Flow::RecoveryDataBackfill;
let (connector_customer_id, payment_intent_id) = path.into_inner();
let payload = UnlockStatusRequest {
connector_customer_id,
payment_intent_id,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| {
revenue_recovery_data_backfill::unlock_connector_customer_status_handler(
state,
req.connector_customer_id,
req.payment_intent_id,
)
},
&auth::V2AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.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/routes/refunds.rs | crates/router/src/routes/refunds.rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
#[cfg(feature = "v1")]
use crate::core::refunds::*;
#[cfg(feature = "v2")]
use crate::core::refunds_v2::*;
use crate::{
core::api_locking,
services::{api, authentication as auth, authorization::permissions::Permission},
types::api::refunds,
};
#[cfg(feature = "v2")]
/// A private module to hold internal types to be used in route handlers.
/// This is because we will need to implement certain traits on these types which will have the resource id
/// But the api payload will not contain the resource id
/// So these types can hold the resource id along with actual api payload, on which api event and locking action traits can be implemented
mod internal_payload_types {
use super::*;
// Serialize is implemented because of api events
#[derive(Debug, serde::Serialize)]
pub struct RefundsGenericRequestWithResourceId<T: serde::Serialize> {
pub global_refund_id: common_utils::id_type::GlobalRefundId,
pub payment_id: Option<common_utils::id_type::GlobalPaymentId>,
#[serde(flatten)]
pub payload: T,
}
impl<T: serde::Serialize> common_utils::events::ApiEventMetric
for RefundsGenericRequestWithResourceId<T>
{
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
let refund_id = self.global_refund_id.clone();
let payment_id = self.payment_id.clone();
Some(common_utils::events::ApiEventsType::Refund {
payment_id,
refund_id,
})
}
}
}
/// Refunds - Create
///
/// To create a refund against an already processed payment
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::RefundsCreate))]
// #[post("")]
pub async fn refunds_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundRequest>,
) -> HttpResponse {
let flow = Flow::RefundsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
refund_create_core(state, auth.platform, profile_id, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRefundWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::RefundsCreate))]
// #[post("")]
pub async fn refunds_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundsCreateRequest>,
) -> HttpResponse {
let flow = Flow::RefundsCreate;
let global_refund_id =
common_utils::id_type::GlobalRefundId::generate(&state.conf.cell_information.id);
let payload = json_payload.into_inner();
let internal_refund_create_payload =
internal_payload_types::RefundsGenericRequestWithResourceId {
global_refund_id: global_refund_id.clone(),
payment_id: Some(payload.payment_id.clone()),
payload,
};
let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled {
&auth::MerchantIdAuth
} else {
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileRefundWrite,
},
req.headers(),
)
};
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_refund_create_payload,
|state, auth: auth::AuthenticationData, req, _| {
refund_create_core(state, auth.platform, req.payload, global_refund_id.clone())
},
auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Refunds - Retrieve (GET)
///
/// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[instrument(skip_all, fields(flow))]
// #[get("/{id}")]
pub async fn refunds_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
query_params: web::Query<api_models::refunds::RefundsRetrieveBody>,
) -> HttpResponse {
let refund_request = refunds::RefundsRetrieveRequest {
refund_id: path.into_inner(),
force_sync: query_params.force_sync,
merchant_connector_details: None,
all_keys_required: query_params.all_keys_required,
};
let flow = match query_params.force_sync {
Some(true) => Flow::RefundsRetrieveForceSync,
_ => Flow::RefundsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_request,
|state, auth: auth::AuthenticationData, refund_request, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
refund_response_wrapper(
state,
auth.platform,
profile_id,
refund_request,
refund_retrieve_core_with_refund_id,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow))]
pub async fn refunds_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::GlobalRefundId>,
query_params: web::Query<api_models::refunds::RefundsRetrieveBody>,
) -> HttpResponse {
let refund_request = refunds::RefundsRetrieveRequest {
refund_id: path.into_inner(),
force_sync: query_params.force_sync,
merchant_connector_details: None,
return_raw_connector_response: query_params.return_raw_connector_response,
};
let flow = match query_params.force_sync {
Some(true) => Flow::RefundsRetrieveForceSync,
_ => Flow::RefundsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_request,
|state, auth: auth::AuthenticationData, refund_request, _| {
refund_retrieve_core_with_refund_id(state, auth.platform, auth.profile, refund_request)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow))]
pub async fn refunds_retrieve_with_gateway_creds(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::GlobalRefundId>,
payload: web::Json<api_models::refunds::RefundsRetrievePayload>,
) -> HttpResponse {
let flow = match payload.force_sync {
Some(true) => Flow::RefundsRetrieveForceSync,
_ => Flow::RefundsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
let refund_request = refunds::RefundsRetrieveRequest {
refund_id: path.into_inner(),
force_sync: payload.force_sync,
merchant_connector_details: payload.merchant_connector_details.clone(),
return_raw_connector_response: payload.return_raw_connector_response,
};
let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled {
&auth::MerchantIdAuth
} else {
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
)
};
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_request,
|state, auth: auth::AuthenticationData, refund_request, _| {
refund_retrieve_core_with_refund_id(state, auth.platform, auth.profile, refund_request)
},
auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Refunds - Retrieve (POST)
///
/// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[instrument(skip_all, fields(flow))]
// #[post("/sync")]
pub async fn refunds_retrieve_with_body(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundsRetrieveRequest>,
) -> HttpResponse {
let flow = match json_payload.force_sync {
Some(true) => Flow::RefundsRetrieveForceSync,
_ => Flow::RefundsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
refund_response_wrapper(
state,
auth.platform,
profile_id,
req,
refund_retrieve_core_with_refund_id,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Refunds - Update
///
/// To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields
#[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))]
// #[post("/{id}")]
pub async fn refunds_update(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundUpdateRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::RefundsUpdate;
let mut refund_update_req = json_payload.into_inner();
refund_update_req.refund_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_update_req,
|state, auth: auth::AuthenticationData, req, _| {
refund_update_core(state, auth.platform, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))]
pub async fn refunds_metadata_update(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundMetadataUpdateRequest>,
path: web::Path<common_utils::id_type::GlobalRefundId>,
) -> HttpResponse {
let flow = Flow::RefundsUpdate;
let global_refund_id = path.into_inner();
let internal_payload = internal_payload_types::RefundsGenericRequestWithResourceId {
global_refund_id: global_refund_id.clone(),
payment_id: None,
payload: json_payload.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, _| {
refund_metadata_update_core(
state,
auth.platform.get_processor().get_account().clone(),
req.payload,
global_refund_id.clone(),
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
/// Refunds - List
///
/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided
#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
pub async fn refunds_list(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<api_models::refunds::RefundListRequest>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
refund_list(state, auth.platform, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
pub async fn refunds_list(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<api_models::refunds::RefundListRequest>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
refund_list(
state,
auth.platform.get_processor().get_account().clone(),
auth.profile,
req,
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
/// Refunds - List at profile level
///
/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided
#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
pub async fn refunds_list_profile(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<api_models::refunds::RefundListRequest>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
refund_list(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
/// Refunds - Filter
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
pub async fn refunds_filter_list(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
refund_filter_list(state, auth.platform, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
/// Refunds - Filter V2
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))]
pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::RefundsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
get_filters_for_refunds(state, auth.platform, None)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
/// Refunds - Filter V2 at profile level
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))]
pub async fn get_refunds_filters_profile(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::RefundsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
get_filters_for_refunds(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))]
pub async fn get_refunds_aggregates(
state: web::Data<AppState>,
req: HttpRequest,
query_params: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsAggregate;
let query_params = query_params.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
query_params,
|state, auth: auth::AuthenticationData, req, _| {
get_aggregates_for_refunds(state, auth.platform, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::RefundsManualUpdate))]
pub async fn refunds_manual_update(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<api_models::refunds::RefundManualUpdateRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::RefundsManualUpdate;
let mut refund_manual_update_req = payload.into_inner();
refund_manual_update_req.refund_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_manual_update_req,
|state, _auth, req, _| refund_manual_update(state, req),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))]
pub async fn get_refunds_aggregate_profile(
state: web::Data<AppState>,
req: HttpRequest,
query_params: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsAggregate;
let query_params = query_params.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
query_params,
|state, auth: auth::AuthenticationData, req, _| {
get_aggregates_for_refunds(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/routing.rs | crates/router/src/routes/routing.rs | //! Analysis for usage of Routing in Payment flows
//!
//! Functions that are used to perform the api level configuration, retrieval, updation
//! of Routing configs.
use actix_web::{web, HttpRequest, Responder};
use api_models::{
enums,
routing::{
self as routing_types, RoutingEvaluateRequest, RoutingEvaluateResponse,
RoutingRetrieveQuery,
},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::platform::MerchantKeyStore;
use payment_methods::core::errors::ApiErrorResponse;
use router_env::{
tracing::{self, instrument},
Flow,
};
use crate::{
core::{
api_locking, conditional_config,
payments::routing::utils::{DecisionEngineApiHandler, EuclidApiClient},
routing, surcharge_decision_config,
},
db::errors::StorageErrorExt,
routes::AppState,
services,
services::{api as oss_api, authentication as auth, authorization::permissions::Permission},
types::domain,
};
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all)]
pub async fn routing_create_config(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<routing_types::RoutingConfigRequest>,
transaction_type: Option<enums::TransactionType>,
) -> impl Responder {
let flow = Flow::RoutingCreateConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, payload, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
routing::create_routing_algorithm_under_profile(
state,
auth.platform,
profile_id,
payload.clone(),
transaction_type
.or(payload.transaction_type)
.unwrap_or(enums::TransactionType::Payment),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all)]
pub async fn routing_create_config(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<routing_types::RoutingConfigRequest>,
transaction_type: enums::TransactionType,
) -> impl Responder {
let flow = Flow::RoutingCreateConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, payload, _| {
routing::create_routing_algorithm_under_profile(
state,
auth.platform,
Some(auth.profile.get_id().clone()),
payload,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all)]
pub async fn routing_link_config(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::RoutingId>,
json_payload: web::Json<routing_types::RoutingActivatePayload>,
transaction_type: Option<enums::TransactionType>,
) -> impl Responder {
let flow = Flow::RoutingLinkConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
path.into_inner(),
|state, auth: auth::AuthenticationData, algorithm, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
routing::link_routing_config(
state,
auth.platform,
profile_id,
algorithm,
transaction_type
.or(json_payload.transaction_type)
.unwrap_or(enums::TransactionType::Payment),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all)]
pub async fn routing_link_config(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::ProfileId>,
json_payload: web::Json<routing_types::RoutingAlgorithmId>,
transaction_type: &enums::TransactionType,
) -> impl Responder {
let flow = Flow::RoutingLinkConfig;
let wrapper = routing_types::RoutingLinkWrapper {
profile_id: path.into_inner(),
algorithm_id: json_payload.into_inner(),
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
wrapper.clone(),
|state, auth: auth::AuthenticationData, wrapper, _| {
routing::link_routing_config_under_profile(
state,
auth.platform,
wrapper.profile_id,
wrapper.algorithm_id.routing_algorithm_id,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
required_permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
required_permission: Permission::MerchantRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all)]
pub async fn routing_retrieve_config(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::RoutingId>,
) -> impl Responder {
let algorithm_id = path.into_inner();
let flow = Flow::RoutingRetrieveConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
algorithm_id,
|state, auth: auth::AuthenticationData, algorithm_id, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
routing::retrieve_routing_algorithm_from_algorithm_id(
state,
auth.platform,
profile_id,
algorithm_id,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all)]
pub async fn routing_retrieve_config(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::RoutingId>,
) -> impl Responder {
let algorithm_id = path.into_inner();
let flow = Flow::RoutingRetrieveConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
algorithm_id,
|state, auth: auth::AuthenticationData, algorithm_id, _| {
routing::retrieve_routing_algorithm_from_algorithm_id(
state,
auth.platform,
Some(auth.profile.get_id().clone()),
algorithm_id,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
pub async fn list_routing_configs(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<RoutingRetrieveQuery>,
transaction_type: Option<enums::TransactionType>,
) -> impl Responder {
let flow = Flow::RoutingRetrieveDictionary;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
query.into_inner(),
|state, auth: auth::AuthenticationData, query_params, _| {
routing::retrieve_merchant_routing_dictionary(
state,
auth.platform,
None,
query_params.clone(),
transaction_type
.or(query_params.transaction_type)
.unwrap_or(enums::TransactionType::Payment),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantRoutingRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all)]
pub async fn list_routing_configs_for_profile(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<RoutingRetrieveQuery>,
transaction_type: Option<enums::TransactionType>,
) -> impl Responder {
let flow = Flow::RoutingRetrieveDictionary;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
query.into_inner(),
|state, auth: auth::AuthenticationData, query_params, _| {
routing::retrieve_merchant_routing_dictionary(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
query_params.clone(),
transaction_type
.or(query_params.transaction_type)
.unwrap_or(enums::TransactionType::Payment),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all)]
pub async fn routing_unlink_config(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::ProfileId>,
transaction_type: &enums::TransactionType,
) -> impl Responder {
let flow = Flow::RoutingUnlinkConfig;
let path = path.into_inner();
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
path.clone(),
|state, auth: auth::AuthenticationData, path, _| {
routing::unlink_routing_config_under_profile(
state,
auth.platform,
path,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuthProfileFromRoute {
profile_id: path,
required_permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: path,
required_permission: Permission::MerchantRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all)]
pub async fn routing_unlink_config(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<routing_types::RoutingConfigRequest>,
transaction_type: Option<enums::TransactionType>,
) -> impl Responder {
let flow = Flow::RoutingUnlinkConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, payload_req, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
routing::unlink_routing_config(
state,
auth.platform,
payload_req.clone(),
profile_id,
transaction_type
.or(payload_req.transaction_type)
.unwrap_or(enums::TransactionType::Payment),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all)]
pub async fn routing_update_default_config(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::ProfileId>,
json_payload: web::Json<Vec<routing_types::RoutableConnectorChoice>>,
) -> impl Responder {
let wrapper = routing_types::ProfileDefaultRoutingConfig {
profile_id: path.into_inner(),
connectors: json_payload.into_inner(),
};
Box::pin(oss_api::server_wrap(
Flow::RoutingUpdateDefaultConfig,
state,
&req,
wrapper,
|state, auth: auth::AuthenticationData, wrapper, _| {
routing::update_default_fallback_routing(
state,
auth.platform,
wrapper.profile_id,
wrapper.connectors,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::MerchantRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all)]
pub async fn routing_update_default_config(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<Vec<routing_types::RoutableConnectorChoice>>,
transaction_type: &enums::TransactionType,
) -> impl Responder {
Box::pin(oss_api::server_wrap(
Flow::RoutingUpdateDefaultConfig,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, updated_config, _| {
routing::update_default_routing_config(
state,
auth.platform,
updated_config,
transaction_type,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all)]
pub async fn routing_retrieve_default_config(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::ProfileId>,
) -> impl Responder {
let path = path.into_inner();
Box::pin(oss_api::server_wrap(
Flow::RoutingRetrieveDefaultConfig,
state,
&req,
path.clone(),
|state, auth: auth::AuthenticationData, profile_id, _| {
routing::retrieve_default_fallback_algorithm_for_profile(
state,
auth.platform,
profile_id,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuthProfileFromRoute {
profile_id: path,
required_permission: Permission::MerchantRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: path,
required_permission: Permission::MerchantRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all)]
pub async fn routing_retrieve_default_config(
state: web::Data<AppState>,
req: HttpRequest,
transaction_type: &enums::TransactionType,
) -> impl Responder {
Box::pin(oss_api::server_wrap(
Flow::RoutingRetrieveDefaultConfig,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
routing::retrieve_default_routing_config(
state,
profile_id,
auth.platform,
transaction_type,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
pub async fn upsert_surcharge_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_models::surcharge_decision_configs::SurchargeDecisionConfigReq>,
) -> impl Responder {
let flow = Flow::DecisionManagerUpsertConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, update_decision, _| {
surcharge_decision_config::upsert_surcharge_decision_config(
state,
auth.platform,
update_decision,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantSurchargeDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::MerchantSurchargeDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
pub async fn delete_surcharge_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
) -> impl Responder {
let flow = Flow::DecisionManagerDeleteConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, (), _| {
surcharge_decision_config::delete_surcharge_decision_config(state, auth.platform)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantSurchargeDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::MerchantSurchargeDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
pub async fn retrieve_surcharge_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
) -> impl Responder {
let flow = Flow::DecisionManagerRetrieveConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
surcharge_decision_config::retrieve_surcharge_decision_config(state, auth.platform)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantSurchargeDecisionManagerRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::MerchantSurchargeDecisionManagerRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all)]
pub async fn upsert_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_models::conditional_configs::DecisionManager>,
) -> impl Responder {
let flow = Flow::DecisionManagerUpsertConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, update_decision, _| {
conditional_config::upsert_conditional_config(state, auth.platform, update_decision)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantThreeDsDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::MerchantThreeDsDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all)]
pub async fn upsert_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_models::conditional_configs::DecisionManagerRequest>,
) -> impl Responder {
let flow = Flow::DecisionManagerUpsertConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, update_decision, _| {
conditional_config::upsert_conditional_config(
state,
auth.platform.get_processor().get_key_store().clone(),
update_decision,
auth.profile,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileThreeDsDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileThreeDsDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
pub async fn delete_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
) -> impl Responder {
let flow = Flow::DecisionManagerDeleteConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, (), _| {
conditional_config::delete_conditional_config(state, auth.platform)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantThreeDsDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::MerchantThreeDsDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[cfg(feature = "olap")]
#[instrument(skip_all)]
pub async fn retrieve_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
) -> impl Responder {
let flow = Flow::DecisionManagerRetrieveConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
conditional_config::retrieve_conditional_config(
state,
auth.platform.get_processor().get_key_store().clone(),
auth.profile,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileThreeDsDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileThreeDsDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[cfg(feature = "olap")]
#[instrument(skip_all)]
pub async fn retrieve_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
) -> impl Responder {
let flow = Flow::DecisionManagerRetrieveConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
conditional_config::retrieve_conditional_config(state, auth.platform)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantThreeDsDecisionManagerRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::MerchantThreeDsDecisionManagerRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all)]
pub async fn routing_retrieve_linked_config(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<routing_types::RoutingRetrieveLinkQuery>,
transaction_type: Option<enums::TransactionType>,
) -> impl Responder {
use crate::services::authentication::AuthenticationData;
let flow = Flow::RoutingRetrieveActiveConfig;
let query = query.into_inner();
if let Some(profile_id) = query.profile_id.clone() {
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
query.clone(),
|state, auth: AuthenticationData, query_params, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
routing::retrieve_linked_routing_config(
state,
auth.platform,
profile_id,
query_params,
transaction_type
.or(query.transaction_type)
.unwrap_or(enums::TransactionType::Payment),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuthProfileFromRoute {
profile_id,
required_permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
} else {
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
query.clone(),
|state, auth: AuthenticationData, query_params, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
routing::retrieve_linked_routing_config(
state,
auth.platform,
profile_id,
query_params,
transaction_type
.or(query.transaction_type)
.unwrap_or(enums::TransactionType::Payment),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all)]
pub async fn routing_retrieve_linked_config(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<RoutingRetrieveQuery>,
path: web::Path<common_utils::id_type::ProfileId>,
transaction_type: &enums::TransactionType,
) -> impl Responder {
use crate::services::authentication::AuthenticationData;
let flow = Flow::RoutingRetrieveActiveConfig;
let wrapper = routing_types::RoutingRetrieveLinkQueryWrapper {
routing_query: query.into_inner(),
profile_id: path.into_inner(),
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
wrapper.clone(),
|state, auth: AuthenticationData, wrapper, _| {
routing::retrieve_routing_config_under_profile(
state,
auth.platform,
wrapper.routing_query,
wrapper.profile_id,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
required_permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/webhook_events.rs | crates/router/src/routes/webhook_events.rs | use actix_web::{web, HttpRequest, Responder};
use router_env::{instrument, tracing, Flow};
use crate::{
core::{api_locking, webhooks::webhook_events},
routes::AppState,
services::{
api,
authentication::{self as auth, UserFromToken},
authorization::permissions::Permission,
},
types::api::webhook_events::{
EventListConstraints, EventListRequestInternal, WebhookDeliveryAttemptListRequestInternal,
WebhookDeliveryRetryRequestInternal,
},
};
#[instrument(skip_all, fields(flow = ?Flow::WebhookEventInitialDeliveryAttemptList))]
pub async fn list_initial_webhook_delivery_attempts(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<EventListConstraints>,
) -> impl Responder {
let flow = Flow::WebhookEventInitialDeliveryAttemptList;
let merchant_id = path.into_inner();
let constraints = json_payload.into_inner();
let request_internal = EventListRequestInternal {
merchant_id: merchant_id.clone(),
constraints,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request_internal,
|state, _, request_internal, _| {
webhook_events::list_initial_delivery_attempts(
state,
request_internal.merchant_id,
request_internal.constraints,
)
},
auth::auth_type(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantWebhookEventRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::WebhookEventInitialDeliveryAttemptList))]
pub async fn list_initial_webhook_delivery_attempts_with_jwtauth(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<EventListConstraints>,
) -> impl Responder {
let flow = Flow::WebhookEventInitialDeliveryAttemptList;
let constraints = json_payload.into_inner();
let request_internal = EventListRequestInternal {
merchant_id: common_utils::id_type::MerchantId::default(),
constraints,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request_internal,
|state, auth: UserFromToken, mut request_internal, _| {
let merchant_id = auth.merchant_id;
let profile_id = auth.profile_id;
request_internal.merchant_id = merchant_id;
request_internal.constraints.profile_id = Some(profile_id);
webhook_events::list_initial_delivery_attempts(
state,
request_internal.merchant_id,
request_internal.constraints,
)
},
&auth::JWTAuth {
permission: Permission::ProfileWebhookEventRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::WebhookEventDeliveryAttemptList))]
pub async fn list_webhook_delivery_attempts(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::WebhookEventDeliveryAttemptList;
let (merchant_id, initial_attempt_id) = path.into_inner();
let request_internal = WebhookDeliveryAttemptListRequestInternal {
merchant_id: merchant_id.clone(),
initial_attempt_id,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request_internal,
|state, _, request_internal, _| {
webhook_events::list_delivery_attempts(
state,
request_internal.merchant_id,
request_internal.initial_attempt_id,
)
},
auth::auth_type(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantWebhookEventRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::WebhookEventDeliveryRetry))]
#[cfg(feature = "v1")]
pub async fn retry_webhook_delivery_attempt(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::WebhookEventDeliveryRetry;
let (merchant_id, event_id) = path.into_inner();
let request_internal = WebhookDeliveryRetryRequestInternal {
merchant_id: merchant_id.clone(),
event_id,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request_internal,
|state, _, request_internal, _| {
webhook_events::retry_delivery_attempt(
state,
request_internal.merchant_id,
request_internal.event_id,
)
},
auth::auth_type(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantWebhookEventWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/customers.rs | crates/router/src/routes/customers.rs | use actix_web::{web, HttpRequest, HttpResponse, Responder};
use common_utils::id_type;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, customers::*},
services::{api, authentication as auth, authorization::permissions::Permission},
types::api::customers,
};
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))]
pub async fn customers_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<customers::CustomerRequest>,
) -> HttpResponse {
let flow = Flow::CustomersCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
create_customer(state, auth.platform.get_provider().clone(), req, None)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))]
pub async fn customers_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<customers::CustomerRequest>,
) -> HttpResponse {
let flow = Flow::CustomersCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
create_customer(state, auth.platform.get_provider().clone(), req, None)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))]
pub async fn customers_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
) -> HttpResponse {
let flow = Flow::CustomersRetrieve;
let customer_id = path.into_inner();
let auth = if auth::is_jwt_auth(req.headers()) {
Box::new(auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
})
} else {
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
};
match auth::is_ephemeral_auth(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
customer_id,
|state, auth: auth::AuthenticationData, customer_id, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
retrieve_customer(
state,
auth.platform.get_provider().clone(),
profile_id,
customer_id,
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))]
pub async fn customers_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalCustomerId>,
) -> HttpResponse {
use crate::services::authentication::api_or_client_auth;
let flow = Flow::CustomersRetrieve;
let id = path.into_inner();
let v2_client_auth = auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::Customer(id.clone()),
);
let auth = if auth::is_jwt_auth(req.headers()) {
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
}
} else {
api_or_client_auth(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&v2_client_auth,
req.headers(),
)
};
Box::pin(api::server_wrap(
flow,
state,
&req,
id,
|state, auth: auth::AuthenticationData, id, _| {
retrieve_customer(state, auth.platform.get_provider().clone(), id)
},
auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersList))]
pub async fn customers_list(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<customers::CustomerListRequest>,
) -> HttpResponse {
let flow = Flow::CustomersList;
let payload = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| {
list_customers(state, auth.platform.get_provider().clone(), None, request)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersList))]
pub async fn customers_list(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<customers::CustomerListRequest>,
) -> HttpResponse {
let flow = Flow::CustomersList;
let payload = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| {
list_customers(state, auth.platform.get_provider().clone(), None, request)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersListWithConstraints))]
pub async fn customers_list_with_count(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<customers::CustomerListRequestWithConstraints>,
) -> HttpResponse {
let flow = Flow::CustomersListWithConstraints;
let payload = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| {
list_customers_with_count(state, auth.platform.get_provider().clone(), request)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersListWithConstraints))]
pub async fn customers_list_with_count(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<customers::CustomerListRequestWithConstraints>,
) -> HttpResponse {
let flow = Flow::CustomersListWithConstraints;
let payload = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| {
list_customers_with_count(state, auth.platform.get_provider().clone(), request)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))]
pub async fn customers_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
json_payload: web::Json<customers::CustomerUpdateRequest>,
) -> HttpResponse {
let flow = Flow::CustomersUpdate;
let customer_id = path.into_inner();
let request = json_payload.into_inner();
let request_internal = customers::CustomerUpdateRequestInternal {
customer_id,
request,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request_internal,
|state, auth: auth::AuthenticationData, request_internal, _| {
update_customer(
state,
auth.platform.get_provider().clone(),
request_internal,
)
},
auth::auth_type(
&auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))]
pub async fn customers_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalCustomerId>,
json_payload: web::Json<customers::CustomerUpdateRequest>,
) -> HttpResponse {
let flow = Flow::CustomersUpdate;
let id = path.into_inner();
let request = json_payload.into_inner();
let request_internal = customers::CustomerUpdateRequestInternal { id, request };
Box::pin(api::server_wrap(
flow,
state,
&req,
request_internal,
|state, auth: auth::AuthenticationData, request_internal, _| {
update_customer(
state,
auth.platform.get_provider().clone(),
request_internal,
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))]
pub async fn customers_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalCustomerId>,
) -> impl Responder {
let flow = Flow::CustomersDelete;
let id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
id,
|state, auth: auth::AuthenticationData, id, _| {
delete_customer(state, auth.platform.get_provider().clone(), id)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))]
pub async fn customers_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
) -> impl Responder {
let flow = Flow::CustomersDelete;
let customer_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
customer_id,
|state, auth: auth::AuthenticationData, customer_id, _| {
delete_customer(state, auth.platform.get_provider().clone(), customer_id)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersGetMandates))]
pub async fn get_customer_mandates(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
) -> impl Responder {
let flow = Flow::CustomersGetMandates;
let customer_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
customer_id,
|state, auth: auth::AuthenticationData, customer_id, _| {
crate::core::mandate::get_customer_mandates(state, auth.platform, customer_id)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantMandateRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/payout_link.rs | crates/router/src/routes/payout_link.rs | use actix_web::{web, Responder};
use api_models::payouts::PayoutLinkInitiateRequest;
use router_env::Flow;
use crate::{
core::{api_locking, payout_link::*},
services::{
api,
authentication::{self as auth},
},
AppState,
};
#[cfg(feature = "v1")]
pub async fn render_payout_link(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::PayoutId,
)>,
) -> impl Responder {
let flow = Flow::PayoutLinkInitiate;
let (merchant_id, payout_id) = path.into_inner();
let payload = PayoutLinkInitiateRequest {
merchant_id: merchant_id.clone(),
payout_id,
};
let headers = req.headers();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.clone(),
|state, auth, req, _| initiate_payout_link(state, auth.platform, req, headers),
&auth::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.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/routes/poll.rs | crates/router/src/routes/poll.rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, poll},
services::{api, authentication as auth},
types::api::PollId,
};
#[cfg(feature = "v1")]
/// Poll - Retrieve Poll Status
#[utoipa::path(
get,
path = "/poll/status/{poll_id}",
params(
("poll_id" = String, Path, description = "The identifier for poll")
),
responses(
(status = 200, description = "The poll status was retrieved successfully", body = PollResponse),
(status = 404, description = "Poll not found")
),
tag = "Poll",
operation_id = "Retrieve Poll Status",
security(("publishable_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::RetrievePollStatus))]
pub async fn retrieve_poll_status(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::RetrievePollStatus;
let poll_id = PollId {
poll_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
poll_id,
|state, auth, req, _| poll::retrieve_poll_status(state, req, auth.platform),
&auth::HeaderAuth(auth::PublishableKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.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/routes/disputes.rs | crates/router/src/routes/disputes.rs | use actix_multipart::Multipart;
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::disputes as dispute_models;
use router_env::{instrument, tracing, Flow};
use crate::{core::api_locking, services::authorization::permissions::Permission};
pub mod utils;
use super::app::AppState;
use crate::{
core::disputes,
services::{api, authentication as auth},
types::api::disputes as dispute_types,
};
#[cfg(feature = "v1")]
/// Disputes - Retrieve Dispute
#[utoipa::path(
get,
path = "/disputes/{dispute_id}",
params(
("dispute_id" = String, Path, description = "The identifier for dispute")
),
responses(
(status = 200, description = "The dispute was retrieved successfully", body = DisputeResponse),
(status = 404, description = "Dispute does not exist in our records")
),
tag = "Disputes",
operation_id = "Retrieve a Dispute",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesRetrieve))]
pub async fn retrieve_dispute(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Query<dispute_models::DisputeRetrieveBody>,
) -> HttpResponse {
let flow = Flow::DisputesRetrieve;
let payload = dispute_models::DisputeRetrieveRequest {
dispute_id: path.into_inner(),
force_sync: json_payload.force_sync,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
disputes::retrieve_dispute(state, auth.platform, profile_id, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::DisputesRetrieve))]
pub async fn fetch_disputes(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Query<dispute_types::DisputeFetchQueryData>,
) -> HttpResponse {
let flow = Flow::DisputesList;
let connector_id = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
disputes::connector_sync_disputes(state, auth.platform, connector_id.clone(), req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Disputes - List Disputes
#[utoipa::path(
get,
path = "/disputes/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
("reason" = Option<String>, Query, description = "The reason for dispute"),
("connector" = Option<String>, Query, description = "The connector linked to dispute"),
("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"),
("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"),
("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"),
("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"),
("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"),
),
responses(
(status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Disputes",
operation_id = "List Disputes",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesList))]
pub async fn retrieve_disputes_list(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<dispute_models::DisputeListGetConstraints>,
) -> HttpResponse {
let flow = Flow::DisputesList;
let payload = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
disputes::retrieve_disputes_list(state, auth.platform, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - List Disputes for The Given Business Profiles
#[utoipa::path(
get,
path = "/disputes/profile/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
("reason" = Option<String>, Query, description = "The reason for dispute"),
("connector" = Option<String>, Query, description = "The connector linked to dispute"),
("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"),
("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"),
("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"),
("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"),
("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"),
),
responses(
(status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Disputes",
operation_id = "List Disputes for The given Business Profiles",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesList))]
pub async fn retrieve_disputes_list_profile(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Query<dispute_models::DisputeListGetConstraints>,
) -> HttpResponse {
let flow = Flow::DisputesList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
disputes::retrieve_disputes_list(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - Disputes Filters
#[utoipa::path(
get,
path = "/disputes/filter",
responses(
(status = 200, description = "List of filters", body = DisputeListFilters),
),
tag = "Disputes",
operation_id = "List all filters for disputes",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesFilters))]
pub async fn get_disputes_filters(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::DisputesFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
disputes::get_filters_for_disputes(state, auth.platform, None)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - Disputes Filters Profile
#[utoipa::path(
get,
path = "/disputes/profile/filter",
responses(
(status = 200, description = "List of filters", body = DisputeListFilters),
),
tag = "Disputes",
operation_id = "List all filters for disputes",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesFilters))]
pub async fn get_disputes_filters_profile(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::DisputesFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
disputes::get_filters_for_disputes(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - Accept Dispute
#[utoipa::path(
get,
path = "/disputes/accept/{dispute_id}",
params(
("dispute_id" = String, Path, description = "The identifier for dispute")
),
responses(
(status = 200, description = "The dispute was accepted successfully", body = DisputeResponse),
(status = 404, description = "Dispute does not exist in our records")
),
tag = "Disputes",
operation_id = "Accept a Dispute",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesRetrieve))]
pub async fn accept_dispute(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::DisputesRetrieve;
let dispute_id = dispute_types::DisputeId {
dispute_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
dispute_id,
|state, auth: auth::AuthenticationData, req, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
disputes::accept_dispute(state, auth.platform, profile_id, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - Submit Dispute Evidence
#[utoipa::path(
post,
path = "/disputes/evidence",
request_body=AcceptDisputeRequestData,
responses(
(status = 200, description = "The dispute evidence submitted successfully", body = AcceptDisputeResponse),
(status = 404, description = "Dispute does not exist in our records")
),
tag = "Disputes",
operation_id = "Submit Dispute Evidence",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesEvidenceSubmit))]
pub async fn submit_dispute_evidence(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<dispute_models::SubmitEvidenceRequest>,
) -> HttpResponse {
let flow = Flow::DisputesEvidenceSubmit;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
disputes::submit_evidence(state, auth.platform, profile_id, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - Attach Evidence to Dispute
///
/// To attach an evidence file to dispute
#[utoipa::path(
put,
path = "/disputes/evidence",
request_body=MultipartRequestWithFile,
responses(
(status = 200, description = "Evidence attached to dispute", body = CreateFileResponse),
(status = 400, description = "Bad Request")
),
tag = "Disputes",
operation_id = "Attach Evidence to Dispute",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::AttachDisputeEvidence))]
pub async fn attach_dispute_evidence(
state: web::Data<AppState>,
req: HttpRequest,
payload: Multipart,
) -> HttpResponse {
let flow = Flow::AttachDisputeEvidence;
//Get attach_evidence_request from the multipart request
let attach_evidence_request_result = utils::get_attach_evidence_request(payload).await;
let attach_evidence_request = match attach_evidence_request_result {
Ok(valid_request) => valid_request,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
attach_evidence_request,
|state, auth: auth::AuthenticationData, req, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
disputes::attach_evidence(state, auth.platform, profile_id, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - Retrieve Dispute
#[utoipa::path(
get,
path = "/disputes/evidence/{dispute_id}",
params(
("dispute_id" = String, Path, description = "The identifier for dispute")
),
responses(
(status = 200, description = "The dispute evidence was retrieved successfully", body = DisputeResponse),
(status = 404, description = "Dispute does not exist in our records")
),
tag = "Disputes",
operation_id = "Retrieve a Dispute Evidence",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::RetrieveDisputeEvidence))]
pub async fn retrieve_dispute_evidence(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::RetrieveDisputeEvidence;
let dispute_id = dispute_types::DisputeId {
dispute_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
dispute_id,
|state, auth: auth::AuthenticationData, req, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
disputes::retrieve_dispute_evidence(state, auth.platform, profile_id, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Disputes - Delete Evidence attached to a Dispute
///
/// To delete an evidence file attached to a dispute
#[utoipa::path(
put,
path = "/disputes/evidence",
request_body=DeleteEvidenceRequest,
responses(
(status = 200, description = "Evidence deleted from a dispute"),
(status = 400, description = "Bad Request")
),
tag = "Disputes",
operation_id = "Delete Evidence attached to a Dispute",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DeleteDisputeEvidence))]
pub async fn delete_dispute_evidence(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<dispute_models::DeleteEvidenceRequest>,
) -> HttpResponse {
let flow = Flow::DeleteDisputeEvidence;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
disputes::delete_evidence(state, auth.platform, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::DisputesAggregate))]
pub async fn get_disputes_aggregate(
state: web::Data<AppState>,
req: HttpRequest,
query_param: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::DisputesAggregate;
let query_param = query_param.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
query_param,
|state, auth: auth::AuthenticationData, req, _| {
disputes::get_aggregates_for_disputes(state, auth.platform, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::DisputesAggregate))]
pub async fn get_disputes_aggregate_profile(
state: web::Data<AppState>,
req: HttpRequest,
query_param: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::DisputesAggregate;
let query_param = query_param.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
query_param,
|state, auth: auth::AuthenticationData, req, _| {
disputes::get_aggregates_for_disputes(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/lock_utils.rs | crates/router/src/routes/lock_utils.rs | use router_env::Flow;
#[derive(Clone, Debug, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum ApiIdentifier {
Payments,
Refunds,
Webhooks,
Organization,
MerchantAccount,
MerchantConnector,
Configs,
Customers,
Ephemeral,
Health,
Mandates,
PaymentMethods,
PaymentMethodAuth,
Payouts,
Disputes,
CardsInfo,
Files,
Cache,
Profile,
Verification,
ApiKeys,
PaymentLink,
Routing,
Subscription,
Blocklist,
Forex,
RustLockerMigration,
Gsm,
Role,
User,
UserRole,
ConnectorOnboarding,
Recon,
AiWorkflow,
Poll,
ApplePayCertificatesMigration,
Relay,
Documentation,
CardNetworkTokenization,
Hypersense,
PaymentMethodSession,
ProcessTracker,
Authentication,
Proxy,
ProfileAcquirer,
ThreeDsDecisionRule,
GenericTokenization,
RecoveryRecovery,
}
impl From<Flow> for ApiIdentifier {
fn from(flow: Flow) -> Self {
match flow {
Flow::MerchantsAccountCreate
| Flow::MerchantsAccountRetrieve
| Flow::MerchantsAccountUpdate
| Flow::MerchantsAccountDelete
| Flow::MerchantTransferKey
| Flow::MerchantAccountList
| Flow::EnablePlatformAccount => Self::MerchantAccount,
Flow::OrganizationCreate | Flow::OrganizationRetrieve | Flow::OrganizationUpdate => {
Self::Organization
}
Flow::RoutingCreateConfig
| Flow::RoutingLinkConfig
| Flow::RoutingUnlinkConfig
| Flow::RoutingRetrieveConfig
| Flow::RoutingRetrieveActiveConfig
| Flow::RoutingRetrieveDefaultConfig
| Flow::RoutingRetrieveDictionary
| Flow::RoutingUpdateConfig
| Flow::RoutingUpdateDefaultConfig
| Flow::RoutingDeleteConfig
| Flow::DecisionManagerDeleteConfig
| Flow::DecisionManagerRetrieveConfig
| Flow::ToggleDynamicRouting
| Flow::CreateDynamicRoutingConfig
| Flow::UpdateDynamicRoutingConfigs
| Flow::DecisionManagerUpsertConfig
| Flow::RoutingEvaluateRule
| Flow::DecisionEngineRuleMigration
| Flow::VolumeSplitOnRoutingType
| Flow::DecisionEngineDecideGatewayCall
| Flow::DecisionEngineGatewayFeedbackCall => Self::Routing,
Flow::CreateSubscription
| Flow::ConfirmSubscription
| Flow::CreateAndConfirmSubscription
| Flow::GetSubscription
| Flow::UpdateSubscription
| Flow::GetSubscriptionEstimate
| Flow::GetSubscriptionItemsForSubscription
| Flow::PauseSubscription
| Flow::ResumeSubscription
| Flow::CancelSubscription => Self::Subscription,
Flow::RetrieveForexFlow => Self::Forex,
Flow::AddToBlocklist => Self::Blocklist,
Flow::DeleteFromBlocklist => Self::Blocklist,
Flow::ListBlocklist => Self::Blocklist,
Flow::ToggleBlocklistGuard => Self::Blocklist,
Flow::MerchantConnectorsCreate
| Flow::MerchantConnectorsRetrieve
| Flow::MerchantConnectorsUpdate
| Flow::MerchantConnectorsDelete
| Flow::MerchantConnectorsList => Self::MerchantConnector,
Flow::ConfigKeyCreate
| Flow::ConfigKeyFetch
| Flow::ConfigKeyUpdate
| Flow::ConfigKeyDelete
| Flow::CreateConfigKey => Self::Configs,
Flow::CustomersCreate
| Flow::CustomersRetrieve
| Flow::CustomersUpdate
| Flow::CustomersDelete
| Flow::CustomersGetMandates
| Flow::CustomersList
| Flow::CustomersListWithConstraints => Self::Customers,
Flow::EphemeralKeyCreate | Flow::EphemeralKeyDelete => Self::Ephemeral,
Flow::DeepHealthCheck | Flow::HealthCheck => Self::Health,
Flow::MandatesRetrieve | Flow::MandatesRevoke | Flow::MandatesList => Self::Mandates,
Flow::PaymentMethodsCreate
| Flow::PaymentMethodsMigrate
| Flow::PaymentMethodsBatchUpdate
| Flow::PaymentMethodsBatchRetrieve
| Flow::PaymentMethodsList
| Flow::CustomerPaymentMethodsList
| Flow::GetPaymentMethodTokenData
| Flow::PaymentMethodsRetrieve
| Flow::PaymentMethodsUpdate
| Flow::PaymentMethodsDelete
| Flow::NetworkTokenStatusCheck
| Flow::PaymentMethodCollectLink
| Flow::ValidatePaymentMethod
| Flow::ListCountriesCurrencies
| Flow::DefaultPaymentMethodsSet
| Flow::PaymentMethodSave
| Flow::TotalPaymentMethodCount => Self::PaymentMethods,
Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth,
Flow::PaymentsCreate
| Flow::PaymentsRetrieve
| Flow::PaymentsRetrieveForceSync
| Flow::PaymentsUpdate
| Flow::PaymentsConfirm
| Flow::PaymentsCapture
| Flow::PaymentsCancel
| Flow::PaymentsCancelPostCapture
| Flow::PaymentsApprove
| Flow::PaymentsReject
| Flow::PaymentsSessionToken
| Flow::PaymentsStart
| Flow::PaymentsList
| Flow::PaymentsFilters
| Flow::PaymentsAggregate
| Flow::PaymentsRedirect
| Flow::PaymentsIncrementalAuthorization
| Flow::PaymentsExtendAuthorization
| Flow::PaymentsExternalAuthentication
| Flow::PaymentsAuthorize
| Flow::GetExtendedCardInfo
| Flow::PaymentsCompleteAuthorize
| Flow::PaymentsManualUpdate
| Flow::SessionUpdateTaxCalculation
| Flow::PaymentsConfirmIntent
| Flow::PaymentsCreateIntent
| Flow::PaymentsGetIntent
| Flow::PaymentMethodBalanceCheck
| Flow::ApplyPaymentMethodData
| Flow::PaymentsPostSessionTokens
| Flow::PaymentsUpdateMetadata
| Flow::PaymentsUpdateIntent
| Flow::PaymentsCreateAndConfirmIntent
| Flow::PaymentStartRedirection
| Flow::ProxyConfirmIntent
| Flow::PaymentsRetrieveUsingMerchantReferenceId
| Flow::PaymentAttemptsList
| Flow::RecoveryPaymentsCreate
| Flow::PaymentsSubmitEligibility => Self::Payments,
Flow::PayoutsCreate
| Flow::PayoutsRetrieve
| Flow::PayoutsUpdate
| Flow::PayoutsCancel
| Flow::PayoutsFulfill
| Flow::PayoutsList
| Flow::PayoutsFilter
| Flow::PayoutsAccounts
| Flow::PayoutsConfirm
| Flow::PayoutsManualUpdate
| Flow::PayoutLinkInitiate
| Flow::PayoutsAggregate => Self::Payouts,
Flow::RefundsCreate
| Flow::RefundsRetrieve
| Flow::RefundsRetrieveForceSync
| Flow::RefundsUpdate
| Flow::RefundsList
| Flow::RefundsFilters
| Flow::RefundsAggregate
| Flow::RefundsManualUpdate => Self::Refunds,
Flow::Relay | Flow::RelayRetrieve => Self::Relay,
Flow::FrmFulfillment
| Flow::IncomingWebhookReceive
| Flow::IncomingRelayWebhookReceive
| Flow::WebhookEventInitialDeliveryAttemptList
| Flow::WebhookEventDeliveryAttemptList
| Flow::WebhookEventDeliveryRetry
| Flow::RecoveryIncomingWebhookReceive
| Flow::IncomingNetworkTokenWebhookReceive => Self::Webhooks,
Flow::ApiKeyCreate
| Flow::ApiKeyRetrieve
| Flow::ApiKeyUpdate
| Flow::ApiKeyRevoke
| Flow::ApiKeyList => Self::ApiKeys,
Flow::DisputesRetrieve
| Flow::DisputesList
| Flow::DisputesFilters
| Flow::DisputesEvidenceSubmit
| Flow::AttachDisputeEvidence
| Flow::RetrieveDisputeEvidence
| Flow::DisputesAggregate
| Flow::DeleteDisputeEvidence => Self::Disputes,
Flow::CardsInfo
| Flow::CardsInfoCreate
| Flow::CardsInfoUpdate
| Flow::CardsInfoMigrate => Self::CardsInfo,
Flow::CreateFile | Flow::DeleteFile | Flow::RetrieveFile => Self::Files,
Flow::CacheInvalidate => Self::Cache,
Flow::ProfileCreate
| Flow::ProfileUpdate
| Flow::ProfileRetrieve
| Flow::ProfileDelete
| Flow::ProfileList
| Flow::ToggleExtendedCardInfo
| Flow::ToggleConnectorAgnosticMit => Self::Profile,
Flow::PaymentLinkRetrieve
| Flow::PaymentLinkInitiate
| Flow::PaymentSecureLinkInitiate
| Flow::PaymentLinkList
| Flow::PaymentLinkStatus => Self::PaymentLink,
Flow::Verification => Self::Verification,
Flow::RustLockerMigration => Self::RustLockerMigration,
Flow::GsmRuleCreate
| Flow::GsmRuleRetrieve
| Flow::GsmRuleUpdate
| Flow::GsmRuleDelete => Self::Gsm,
Flow::ApplePayCertificatesMigration => Self::ApplePayCertificatesMigration,
Flow::UserConnectAccount
| Flow::UserSignUp
| Flow::UserSignIn
| Flow::Signout
| Flow::ChangePassword
| Flow::SetDashboardMetadata
| Flow::GetMultipleDashboardMetadata
| Flow::VerifyPaymentConnector
| Flow::InternalUserSignup
| Flow::TenantUserCreate
| Flow::SwitchOrg
| Flow::SwitchMerchantV2
| Flow::SwitchProfile
| Flow::CreatePlatformAccount
| Flow::UserOrgMerchantCreate
| Flow::UserMerchantAccountCreate
| Flow::GenerateSampleData
| Flow::DeleteSampleData
| Flow::GetUserDetails
| Flow::GetUserRoleDetails
| Flow::ForgotPassword
| Flow::ResetPassword
| Flow::RotatePassword
| Flow::InviteMultipleUser
| Flow::ReInviteUser
| Flow::UserSignUpWithMerchantId
| Flow::VerifyEmail
| Flow::AcceptInviteFromEmail
| Flow::VerifyEmailRequest
| Flow::UpdateUserAccountDetails
| Flow::TotpBegin
| Flow::TotpReset
| Flow::TotpVerify
| Flow::TotpUpdate
| Flow::RecoveryCodeVerify
| Flow::RecoveryCodesGenerate
| Flow::TerminateTwoFactorAuth
| Flow::TwoFactorAuthStatus
| Flow::CreateUserAuthenticationMethod
| Flow::UpdateUserAuthenticationMethod
| Flow::ListUserAuthenticationMethods
| Flow::UserTransferKey
| Flow::GetSsoAuthUrl
| Flow::SignInWithSso
| Flow::OidcDiscovery
| Flow::OidcJwks
| Flow::OidcAuthorize
| Flow::OidcToken
| Flow::ListOrgForUser
| Flow::ListMerchantsForUserInOrg
| Flow::ListProfileForUserInOrgAndMerchant
| Flow::ListInvitationsForUser
| Flow::AuthSelect
| Flow::GetThemeUsingLineage
| Flow::GetThemeUsingThemeId
| Flow::UploadFileToThemeStorage
| Flow::CreateTheme
| Flow::UpdateTheme
| Flow::DeleteTheme
| Flow::CreateUserTheme
| Flow::UpdateUserTheme
| Flow::DeleteUserTheme
| Flow::GetUserThemeUsingThemeId
| Flow::UploadFileToUserThemeStorage
| Flow::GetUserThemeUsingLineage
| Flow::ListAllThemesInLineage
| Flow::CloneConnector => Self::User,
Flow::GetDataFromHyperswitchAiFlow | Flow::ListAllChatInteractions => Self::AiWorkflow,
Flow::ListRolesV2
| Flow::ListInvitableRolesAtEntityLevel
| Flow::ListUpdatableRolesAtEntityLevel
| Flow::GetRole
| Flow::GetRoleV2
| Flow::GetRoleFromToken
| Flow::GetRoleFromTokenV2
| Flow::GetParentGroupsInfoForRoleFromToken
| Flow::UpdateUserRole
| Flow::GetAuthorizationInfo
| Flow::GetRolesInfo
| Flow::GetParentGroupInfo
| Flow::AcceptInvitationsV2
| Flow::AcceptInvitationsPreAuth
| Flow::DeleteUserRole
| Flow::CreateRole
| Flow::CreateRoleV2
| Flow::UpdateRole
| Flow::UserFromEmail
| Flow::ListUsersInLineage => Self::UserRole,
Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => {
Self::ConnectorOnboarding
}
Flow::ReconMerchantUpdate
| Flow::ReconTokenRequest
| Flow::ReconServiceRequest
| Flow::ReconVerifyToken => Self::Recon,
Flow::RetrievePollStatus => Self::Poll,
Flow::FeatureMatrix => Self::Documentation,
Flow::TokenizeCard
| Flow::TokenizeCardUsingPaymentMethodId
| Flow::TokenizeCardBatch => Self::CardNetworkTokenization,
Flow::HypersenseTokenRequest
| Flow::HypersenseVerifyToken
| Flow::HypersenseSignoutToken => Self::Hypersense,
Flow::PaymentMethodSessionCreate
| Flow::PaymentMethodSessionRetrieve
| Flow::PaymentMethodSessionConfirm
| Flow::PaymentMethodSessionUpdateSavedPaymentMethod
| Flow::PaymentMethodSessionDeleteSavedPaymentMethod
| Flow::PaymentMethodSessionUpdate => Self::PaymentMethodSession,
Flow::RevenueRecoveryRetrieve | Flow::RevenueRecoveryResume => Self::ProcessTracker,
Flow::AuthenticationCreate
| Flow::AuthenticationEligibility
| Flow::AuthenticationSync
| Flow::AuthenticationSyncPostUpdate
| Flow::AuthenticationAuthenticate
| Flow::AuthenticationSessionToken
| Flow::AuthenticationEligibilityCheck
| Flow::AuthenticationRetrieveEligibilityCheck => Self::Authentication,
Flow::Proxy => Self::Proxy,
Flow::ProfileAcquirerCreate | Flow::ProfileAcquirerUpdate => Self::ProfileAcquirer,
Flow::ThreeDsDecisionRuleExecute => Self::ThreeDsDecisionRule,
Flow::TokenizationCreate | Flow::TokenizationRetrieve | Flow::TokenizationDelete => {
Self::GenericTokenization
}
Flow::RecoveryDataBackfill | Flow::RevenueRecoveryRedis => Self::RecoveryRecovery,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/feature_matrix.rs | crates/router/src/routes/feature_matrix.rs | use actix_web::{web, HttpRequest, Responder};
use api_models::{connector_enums::Connector, feature_matrix};
use common_enums::enums;
use hyperswitch_domain_models::{
api::ApplicationResponse, router_response_types::PaymentMethodTypeMetadata,
};
use hyperswitch_interfaces::api::{ConnectorCommon, ConnectorSpecifications};
use router_env::{instrument, tracing, Flow};
use strum::IntoEnumIterator;
use crate::{
self as app,
core::{api_locking::LockAction, errors::RouterResponse},
services::{api, authentication as auth, connector_integration_interface::ConnectorEnum},
settings,
types::api::{self as api_types, payments as payment_types},
};
#[instrument(skip_all)]
pub async fn fetch_feature_matrix(
state: web::Data<app::AppState>,
req: HttpRequest,
json_payload: Option<web::Json<payment_types::FeatureMatrixRequest>>,
) -> impl Responder {
let flow: Flow = Flow::FeatureMatrix;
let payload = json_payload
.map(|json_request| json_request.into_inner())
.unwrap_or_else(|| payment_types::FeatureMatrixRequest { connectors: None });
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, (), req, _| generate_feature_matrix(state, req),
&auth::NoAuth,
LockAction::NotApplicable,
))
.await
}
pub async fn generate_feature_matrix(
state: app::SessionState,
req: payment_types::FeatureMatrixRequest,
) -> RouterResponse<feature_matrix::FeatureMatrixListResponse> {
let connector_list = req
.connectors
.unwrap_or_else(|| Connector::iter().collect());
let feature_matrix_response: Vec<payment_types::ConnectorFeatureMatrixResponse> =
connector_list
.into_iter()
.filter_map(|connector_name| {
api_types::feature_matrix::FeatureMatrixConnectorData::convert_connector(
&connector_name.to_string(),
)
.inspect_err(|_| {
router_env::logger::warn!("Failed to fetch {:?} details", connector_name)
})
.ok()
.and_then(|connector| {
build_connector_feature_details(&state, connector, connector_name.to_string())
})
})
.collect();
Ok(ApplicationResponse::Json(
payment_types::FeatureMatrixListResponse {
connector_count: feature_matrix_response.len(),
connectors: feature_matrix_response,
},
))
}
fn build_connector_feature_details(
state: &app::SessionState,
connector: ConnectorEnum,
connector_name: String,
) -> Option<feature_matrix::ConnectorFeatureMatrixResponse> {
let connector_integration_features = connector.get_supported_payment_methods();
let supported_payment_methods =
connector_integration_features.map(|connector_integration_feature_data| {
connector_integration_feature_data
.iter()
.flat_map(|(payment_method, supported_payment_method_types)| {
build_payment_method_wise_feature_details(
state,
&connector_name,
*payment_method,
supported_payment_method_types,
)
})
.collect::<Vec<feature_matrix::SupportedPaymentMethod>>()
});
let supported_webhook_flows = connector
.get_supported_webhook_flows()
.map(|webhook_flows| webhook_flows.to_vec());
let connector_about = connector.get_connector_about();
connector_about.map(
|connector_about| feature_matrix::ConnectorFeatureMatrixResponse {
name: connector_name.to_uppercase(),
display_name: connector_about.display_name.to_string(),
description: connector_about.description.to_string(),
base_url: Some(connector.base_url(&state.conf.connectors).to_string()),
integration_status: connector_about.integration_status,
category: connector_about.connector_type,
supported_webhook_flows,
supported_payment_methods,
},
)
}
fn build_payment_method_wise_feature_details(
state: &app::SessionState,
connector_name: &str,
payment_method: enums::PaymentMethod,
supported_payment_method_types: &PaymentMethodTypeMetadata,
) -> Vec<feature_matrix::SupportedPaymentMethod> {
supported_payment_method_types
.iter()
.map(|(payment_method_type, feature_metadata)| {
let payment_method_type_config =
state
.conf
.pm_filters
.0
.get(connector_name)
.and_then(|selected_connector| {
selected_connector.0.get(
&settings::PaymentMethodFilterKey::PaymentMethodType(
*payment_method_type,
),
)
});
let supported_countries = payment_method_type_config.and_then(|config| {
config.country.clone().map(|set| {
set.into_iter()
.map(common_enums::CountryAlpha2::from_alpha2_to_alpha3)
.collect::<std::collections::HashSet<_>>()
})
});
let supported_currencies =
payment_method_type_config.and_then(|config| config.currency.clone());
feature_matrix::SupportedPaymentMethod {
payment_method,
payment_method_type: *payment_method_type,
payment_method_type_display_name: payment_method_type.to_display_name(),
mandates: feature_metadata.mandates,
refunds: feature_metadata.refunds,
supported_capture_methods: feature_metadata.supported_capture_methods.clone(),
payment_method_specific_features: feature_metadata.specific_features.clone(),
supported_countries,
supported_currencies,
}
})
.collect()
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/profile_acquirer.rs | crates/router/src/routes/profile_acquirer.rs | use actix_web::{web, HttpRequest, HttpResponse};
use api_models::profile_acquirer::{ProfileAcquirerCreate, ProfileAcquirerUpdate};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::api_locking,
services::{api, authentication as auth, authorization::permissions::Permission},
};
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::ProfileAcquirerCreate))]
pub async fn create_profile_acquirer(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<ProfileAcquirerCreate>,
) -> HttpResponse {
let flow = Flow::ProfileAcquirerCreate;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state: super::SessionState, auth_data, req, _| {
crate::core::profile_acquirer::create_profile_acquirer(state, req, auth_data.platform)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::ProfileAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::ProfileAcquirerUpdate))]
pub async fn profile_acquirer_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::ProfileId,
common_utils::id_type::ProfileAcquirerId,
)>,
json_payload: web::Json<ProfileAcquirerUpdate>,
) -> HttpResponse {
let flow = Flow::ProfileAcquirerUpdate;
let (profile_id, profile_acquirer_id) = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state: super::SessionState, auth_data, req, _| {
crate::core::profile_acquirer::update_profile_acquirer_config(
state,
profile_id.clone(),
profile_acquirer_id.clone(),
req,
auth_data.platform,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::ProfileAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/payment_link.rs | crates/router/src/routes/payment_link.rs | use actix_web::{web, Responder};
use router_env::{instrument, tracing, Flow};
use crate::{
core::{api_locking, payment_link::*},
services::{api, authentication as auth},
AppState,
};
/// Payments Link - Retrieve
///
/// To retrieve the properties of a Payment Link. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[instrument(skip(state, req), fields(flow = ?Flow::PaymentLinkRetrieve))]
pub async fn payment_link_retrieve(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
path: web::Path<String>,
json_payload: web::Query<api_models::payments::RetrievePaymentLinkRequest>,
) -> impl Responder {
let flow = Flow::PaymentLinkRetrieve;
let payload = json_payload.into_inner();
let api_auth = auth::ApiKeyAuth::default();
let (auth_type, _) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(error_stack::report!(err)),
};
api::server_wrap(
flow,
state,
&req,
payload.clone(),
|state, _auth, _, _| retrieve_payment_link(state, path.clone()),
&*auth_type,
api_locking::LockAction::NotApplicable,
)
.await
}
pub async fn initiate_payment_link(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::PaymentId,
)>,
) -> impl Responder {
let flow = Flow::PaymentLinkInitiate;
let (merchant_id, payment_id) = path.into_inner();
let payload = api_models::payments::PaymentLinkInitiateRequest {
payment_id,
merchant_id: merchant_id.clone(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.clone(),
|state, auth: auth::AuthenticationData, _, _| {
initiate_payment_link_flow(
state,
auth.platform,
payload.merchant_id.clone(),
payload.payment_id.clone(),
)
},
&crate::services::authentication::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn initiate_secure_payment_link(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::PaymentId,
)>,
) -> impl Responder {
let flow = Flow::PaymentSecureLinkInitiate;
let (merchant_id, payment_id) = path.into_inner();
let payload = api_models::payments::PaymentLinkInitiateRequest {
payment_id,
merchant_id: merchant_id.clone(),
};
let headers = req.headers();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.clone(),
|state, auth: auth::AuthenticationData, _, _| {
initiate_secure_payment_link_flow(
state,
auth.platform,
payload.merchant_id.clone(),
payload.payment_id.clone(),
headers,
)
},
&crate::services::authentication::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payment Link - List
///
/// To list the payment links
#[instrument(skip_all, fields(flow = ?Flow::PaymentLinkList))]
pub async fn payments_link_list(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
payload: web::Query<api_models::payments::PaymentLinkListConstraints>,
) -> impl Responder {
let flow = Flow::PaymentLinkList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, payload, _| {
list_payment_link(
state,
auth.platform.get_processor().get_account().clone(),
payload,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn payment_link_status(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::PaymentId,
)>,
) -> impl Responder {
let flow = Flow::PaymentLinkStatus;
let (merchant_id, payment_id) = path.into_inner();
let payload = api_models::payments::PaymentLinkInitiateRequest {
payment_id,
merchant_id: merchant_id.clone(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.clone(),
|state, auth: auth::AuthenticationData, _, _| {
get_payment_link_status(
state,
auth.platform,
payload.merchant_id.clone(),
payload.payment_id.clone(),
)
},
&crate::services::authentication::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.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/routes/three_ds_decision_rule.rs | crates/router/src/routes/three_ds_decision_rule.rs | use actix_web::{web, Responder};
use router_env::{instrument, tracing, Flow};
use crate::{
self as app,
core::{api_locking, three_ds_decision_rule as three_ds_decision_rule_core},
services::{api, authentication as auth},
};
#[instrument(skip_all, fields(flow = ?Flow::ThreeDsDecisionRuleExecute))]
#[cfg(feature = "oltp")]
pub async fn execute_decision_rule(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest>,
) -> impl Responder {
let flow = Flow::ThreeDsDecisionRuleExecute;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
three_ds_decision_rule_core::execute_three_ds_decision_rule(state, auth.platform, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.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/routes/process_tracker.rs | crates/router/src/routes/process_tracker.rs | #[cfg(feature = "v2")]
pub mod revenue_recovery;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/verification.rs | crates/router/src/routes/verification.rs | use actix_web::{web, HttpRequest, Responder};
use api_models::verifications;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, verification},
services::{api, authentication as auth, authorization::permissions::Permission},
};
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::Verification))]
pub async fn apple_pay_merchant_registration(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<verifications::ApplepayMerchantVerificationRequest>,
path: web::Path<common_utils::id_type::MerchantId>,
) -> impl Responder {
let flow = Flow::Verification;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, body, _| {
verification::verify_merchant_creds_for_applepay(
state.clone(),
body,
merchant_id.clone(),
auth.profile.map(|profile| profile.get_id().clone()),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all, fields(flow = ?Flow::Verification))]
pub async fn apple_pay_merchant_registration(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<verifications::ApplepayMerchantVerificationRequest>,
path: web::Path<common_utils::id_type::MerchantId>,
) -> impl Responder {
let flow = Flow::Verification;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, body, _| {
verification::verify_merchant_creds_for_applepay(
state.clone(),
body,
merchant_id.clone(),
Some(auth.profile.get_id().clone()),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::Verification))]
pub async fn retrieve_apple_pay_verified_domains(
state: web::Data<AppState>,
req: HttpRequest,
params: web::Query<verifications::ApplepayGetVerifiedDomainsParam>,
) -> impl Responder {
let flow = Flow::Verification;
let merchant_id = ¶ms.merchant_id;
let mca_id = ¶ms.merchant_connector_account_id;
Box::pin(api::server_wrap(
flow,
state,
&req,
merchant_id.clone(),
|state, _: auth::AuthenticationData, _, _| {
verification::get_verified_apple_domains_with_mid_mca_id(
state,
merchant_id.to_owned(),
mca_id.clone(),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/recovery_webhooks.rs | crates/router/src/routes/recovery_webhooks.rs | use actix_web::{web, HttpRequest, Responder};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{
api_locking,
webhooks::{self, types},
},
services::{api, authentication as auth},
types::domain,
};
#[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))]
pub async fn recovery_receive_incoming_webhook<W: types::OutgoingWebhookType>(
state: web::Data<AppState>,
req: HttpRequest,
body: web::Bytes,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ProfileId,
common_utils::id_type::MerchantConnectorAccountId,
)>,
) -> impl Responder {
let flow = Flow::RecoveryIncomingWebhookReceive;
let (merchant_id, profile_id, connector_id) = path.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&req,
(),
|state, auth, _, req_state| {
webhooks::incoming_webhooks_wrapper::<W>(
&flow,
state.to_owned(),
req_state,
&req,
auth.platform,
auth.profile,
&connector_id,
body.clone(),
false,
)
},
&auth::MerchantIdAndProfileIdAuth {
merchant_id,
profile_id,
},
api_locking::LockAction::NotApplicable,
))
.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/routes/ephemeral_key.rs | crates/router/src/routes/ephemeral_key.rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};
use super::AppState;
#[cfg(feature = "v2")]
use crate::types::domain;
use crate::{
core::{api_locking, payments::helpers},
services::{api, authentication as auth},
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyCreate))]
pub async fn ephemeral_key_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_models::ephemeral_key::EphemeralKeyCreateRequest>,
) -> HttpResponse {
let flow = Flow::EphemeralKeyCreate;
let payload = json_payload.into_inner();
api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, payload, _| {
helpers::make_ephemeral_key(
state,
payload.customer_id,
auth.platform
.get_processor()
.get_account()
.get_id()
.to_owned(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyDelete))]
pub async fn ephemeral_key_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::EphemeralKeyDelete;
let payload = path.into_inner();
api::server_wrap(
flow,
state,
&req,
payload,
|state, _: auth::AuthenticationData, req, _| helpers::delete_ephemeral_key(state, req),
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyCreate))]
pub async fn client_secret_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_models::ephemeral_key::ClientSecretCreateRequest>,
) -> HttpResponse {
let flow = Flow::EphemeralKeyCreate;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, payload, _| {
helpers::make_client_secret(
state,
payload.resource_id.to_owned(),
auth.platform,
req.headers(),
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyDelete))]
pub async fn client_secret_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::EphemeralKeyDelete;
let payload = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _: auth::AuthenticationData, req, _| helpers::delete_client_secret(state, req),
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.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/routes/pm_auth.rs | crates/router/src/routes/pm_auth.rs | use actix_web::{web, HttpRequest, Responder};
use api_models as api_types;
use router_env::{instrument, tracing, types::Flow};
use crate::{
core::api_locking,
routes::AppState,
services::{api, authentication as auth},
types::transformers::ForeignTryFrom,
};
#[instrument(skip_all, fields(flow = ?Flow::PmAuthLinkTokenCreate))]
pub async fn link_token_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_types::pm_auth::LinkTokenCreateRequest>,
) -> impl Responder {
let payload = json_payload.into_inner();
let flow = Flow::PmAuthLinkTokenCreate;
let api_auth = auth::ApiKeyAuth::default();
let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth(
req.headers(),
&payload,
api_auth,
) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
let header_payload =
match hyperswitch_domain_models::payments::HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, payload, _| {
crate::core::pm_auth::create_link_token(
state,
auth.platform,
payload,
Some(header_payload.clone()),
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PmAuthExchangeToken))]
pub async fn exchange_token(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_types::pm_auth::ExchangeTokenCreateRequest>,
) -> impl Responder {
let payload = json_payload.into_inner();
let flow = Flow::PmAuthExchangeToken;
let api_auth = auth::ApiKeyAuth::default();
let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth(
req.headers(),
&payload,
api_auth,
) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, payload, _| {
crate::core::pm_auth::exchange_token_core(state, auth.platform, payload)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.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/routes/cards_info.rs | crates/router/src/routes/cards_info.rs | use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse, Responder};
use api_models::cards_info as cards_info_api_types;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, cards_info},
services::{api, authentication as auth},
};
#[cfg(feature = "v1")]
/// Cards Info - Retrieve
///
/// Retrieve the card information given the card bin
#[utoipa::path(
get,
path = "/cards/{bin}",
params(("bin" = String, Path, description = "The first 6 or 9 digits of card")),
responses(
(status = 200, description = "Card iin data found", body = CardInfoResponse),
(status = 404, description = "Card iin data not found")
),
operation_id = "Retrieve card information",
security(("api_key" = []), ("publishable_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::CardsInfo))]
pub async fn card_iin_info(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
payload: web::Query<api_models::cards_info::CardsInfoRequestParams>,
) -> impl Responder {
let card_iin = path.into_inner();
let request_params = payload.into_inner();
let payload = api_models::cards_info::CardsInfoRequest {
client_secret: request_params.client_secret,
card_iin,
};
let api_auth = auth::ApiKeyAuth::default();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
{
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
Flow::CardsInfo,
state,
&req,
payload,
|state, auth, req, _| cards_info::retrieve_card_info(state, auth.platform, req),
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::CardsInfoCreate))]
pub async fn create_cards_info(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<cards_info_api_types::CardInfoCreateRequest>,
) -> impl Responder {
let payload = json_payload.into_inner();
let flow = Flow::CardsInfoCreate;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, _, payload, _| cards_info::create_card_info(state, payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::CardsInfoUpdate))]
pub async fn update_cards_info(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<cards_info_api_types::CardInfoUpdateRequest>,
) -> impl Responder {
let payload = json_payload.into_inner();
let flow = Flow::CardsInfoUpdate;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, _, payload, _| cards_info::update_card_info(state, payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
#[instrument(skip_all, fields(flow = ?Flow::CardsInfoMigrate))]
pub async fn migrate_cards_info(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<cards_info::CardsInfoUpdateForm>,
) -> HttpResponse {
let flow = Flow::CardsInfoMigrate;
let records = match cards_info::get_cards_bin_records(form) {
Ok(records) => records,
Err(e) => return api::log_and_return_error_response(e.into()),
};
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
records,
|state, _, payload, _| cards_info::migrate_cards_info(state, payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.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/routes/apple_pay_certificates_migration.rs | crates/router/src/routes/apple_pay_certificates_migration.rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::Flow;
use super::AppState;
use crate::{
core::{api_locking, apple_pay_certificates_migration},
services::{api, authentication as auth},
};
pub async fn apple_pay_certificates_migration(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<
api_models::apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest,
>,
) -> HttpResponse {
let flow = Flow::ApplePayCertificatesMigration;
Box::pin(api::server_wrap(
flow,
state,
&req,
&json_payload.into_inner(),
|state, _, req, _| {
apple_pay_certificates_migration::apple_pay_certificates_migration(state, req)
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.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/routes/subscription.rs | crates/router/src/routes/subscription.rs | //! Analysis for usage of Subscription in Payment flows
//!
//! Functions that are used to perform the api level configuration and retrieval
//! of various types under Subscriptions.
use std::str::FromStr;
use actix_web::{web, HttpRequest, HttpResponse, Responder};
use api_models::subscription as subscription_types;
use error_stack::report;
use hyperswitch_domain_models::errors;
use router_env::{
tracing::{self, instrument},
Flow,
};
use crate::{
core::api_locking,
headers::X_PROFILE_ID,
routes::AppState,
services::{api as oss_api, authentication as auth, authorization::permissions::Permission},
};
fn extract_profile_id(req: &HttpRequest) -> Result<common_utils::id_type::ProfileId, HttpResponse> {
let header_value = req.headers().get(X_PROFILE_ID).ok_or_else(|| {
HttpResponse::BadRequest().json(
errors::api_error_response::ApiErrorResponse::MissingRequiredField {
field_name: X_PROFILE_ID,
},
)
})?;
let profile_str = header_value.to_str().unwrap_or_default();
if profile_str.is_empty() {
return Err(HttpResponse::BadRequest().json(
errors::api_error_response::ApiErrorResponse::MissingRequiredField {
field_name: X_PROFILE_ID,
},
));
}
common_utils::id_type::ProfileId::from_str(profile_str).map_err(|_| {
HttpResponse::BadRequest().json(
errors::api_error_response::ApiErrorResponse::InvalidDataValue {
field_name: X_PROFILE_ID,
},
)
})
}
#[instrument(skip_all)]
pub async fn create_subscription(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<subscription_types::CreateSubscriptionRequest>,
) -> impl Responder {
let flow = Flow::CreateSubscription;
let profile_id = match extract_profile_id(&req) {
Ok(id) => id,
Err(response) => return response,
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
move |state, auth: auth::AuthenticationData, payload, _| {
subscriptions::create_subscription(
state.into(),
auth.platform,
profile_id.clone(),
payload.clone(),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileSubscriptionWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all)]
pub async fn pause_subscription(
state: web::Data<AppState>,
req: HttpRequest,
subscription_id: web::Path<common_utils::id_type::SubscriptionId>,
json_payload: web::Json<subscription_types::PauseSubscriptionRequest>,
) -> impl Responder {
let flow = Flow::PauseSubscription;
let subscription_id = subscription_id.into_inner();
let profile_id = match extract_profile_id(&req) {
Ok(id) => id,
Err(response) => return response,
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, payload, _| {
subscriptions::pause_subscription(
state.into(),
auth.platform,
profile_id.clone(),
subscription_id.clone(),
payload.clone(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all)]
pub async fn resume_subscription(
state: web::Data<AppState>,
req: HttpRequest,
subscription_id: web::Path<common_utils::id_type::SubscriptionId>,
json_payload: web::Json<subscription_types::ResumeSubscriptionRequest>,
) -> impl Responder {
let flow = Flow::ResumeSubscription;
let subscription_id = subscription_id.into_inner();
let profile_id = match extract_profile_id(&req) {
Ok(id) => id,
Err(response) => return response,
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, payload, _| {
subscriptions::resume_subscription(
state.into(),
auth.platform,
profile_id.clone(),
subscription_id.clone(),
payload.clone(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all)]
pub async fn cancel_subscription(
state: web::Data<AppState>,
req: HttpRequest,
subscription_id: web::Path<common_utils::id_type::SubscriptionId>,
json_payload: web::Json<subscription_types::CancelSubscriptionRequest>,
) -> impl Responder {
let flow = Flow::CancelSubscription;
let subscription_id = subscription_id.into_inner();
let profile_id = match extract_profile_id(&req) {
Ok(id) => id,
Err(response) => return response,
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, payload, _| {
subscriptions::cancel_subscription(
state.into(),
auth.platform,
profile_id.clone(),
subscription_id.clone(),
payload.clone(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all)]
pub async fn confirm_subscription(
state: web::Data<AppState>,
req: HttpRequest,
subscription_id: web::Path<common_utils::id_type::SubscriptionId>,
json_payload: web::Json<subscription_types::ConfirmSubscriptionRequest>,
) -> impl Responder {
let flow = Flow::ConfirmSubscription;
let subscription_id = subscription_id.into_inner();
let payload = json_payload.into_inner();
let profile_id = match extract_profile_id(&req) {
Ok(id) => id,
Err(response) => return response,
};
let api_auth = auth::ApiKeyAuth::default();
let (auth_type, _) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return oss_api::log_and_return_error_response(error_stack::report!(err)),
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, payload, _| {
subscriptions::confirm_subscription(
state.into(),
auth.platform,
profile_id.clone(),
payload.clone(),
subscription_id.clone(),
)
},
auth::auth_type(
&*auth_type,
&auth::JWTAuth {
permission: Permission::ProfileSubscriptionWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all)]
pub async fn get_subscription_items(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<subscription_types::GetSubscriptionItemsQuery>,
) -> impl Responder {
let flow = Flow::GetSubscriptionItemsForSubscription;
let api_auth = auth::ApiKeyAuth::default();
let payload = query.into_inner();
let profile_id = match extract_profile_id(&req) {
Ok(profile_id) => profile_id,
Err(response) => return response,
};
let (auth_type, _) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return oss_api::log_and_return_error_response(error_stack::report!(err)),
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, query, _| {
subscriptions::get_subscription_items(
state.into(),
auth.platform,
profile_id.clone(),
query,
)
},
auth::auth_type(
&*auth_type,
&auth::JWTAuth {
permission: Permission::ProfileSubscriptionRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Add support for get subscription by id
#[instrument(skip_all)]
pub async fn get_subscription(
state: web::Data<AppState>,
req: HttpRequest,
subscription_id: web::Path<common_utils::id_type::SubscriptionId>,
) -> impl Responder {
let flow = Flow::GetSubscription;
let subscription_id = subscription_id.into_inner();
let profile_id = match extract_profile_id(&req) {
Ok(id) => id,
Err(response) => return response,
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
subscriptions::get_subscription(
state.into(),
auth.platform,
profile_id.clone(),
subscription_id.clone(),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileSubscriptionRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all)]
pub async fn create_and_confirm_subscription(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<subscription_types::CreateAndConfirmSubscriptionRequest>,
) -> impl Responder {
let flow = Flow::CreateAndConfirmSubscription;
let profile_id = match extract_profile_id(&req) {
Ok(id) => id,
Err(response) => return response,
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, payload, _| {
subscriptions::create_and_confirm_subscription(
state.into(),
auth.platform,
profile_id.clone(),
payload.clone(),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileSubscriptionWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// add support for get subscription estimate
#[instrument(skip_all)]
pub async fn get_estimate(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<subscription_types::EstimateSubscriptionQuery>,
) -> impl Responder {
let flow = Flow::GetSubscriptionEstimate;
let profile_id = match extract_profile_id(&req) {
Ok(id) => id,
Err(response) => return response,
};
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return oss_api::log_and_return_error_response(report!(err)),
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
query.into_inner(),
|state, auth: auth::AuthenticationData, query, _| {
subscriptions::get_estimate(state.into(), auth.platform, profile_id.clone(), query)
},
&*auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all)]
pub async fn update_subscription(
state: web::Data<AppState>,
req: HttpRequest,
subscription_id: web::Path<common_utils::id_type::SubscriptionId>,
json_payload: web::Json<subscription_types::UpdateSubscriptionRequest>,
) -> impl Responder {
let flow = Flow::UpdateSubscription;
let subscription_id = subscription_id.into_inner();
let profile_id = match extract_profile_id(&req) {
Ok(id) => id,
Err(response) => return response,
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, payload, _| {
subscriptions::update_subscription(
state.into(),
auth.platform,
profile_id.clone(),
subscription_id.clone(),
payload.clone(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all)]
pub async fn list_subscriptions(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<subscription_types::ListSubscriptionQuery>,
) -> impl Responder {
let flow = Flow::GetSubscription;
let query = query.into_inner();
let profile_id = match extract_profile_id(&req) {
Ok(id) => id,
Err(response) => return response,
};
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
subscriptions::list_subscriptions(
state.into(),
auth.platform,
profile_id.clone(),
query.clone(),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileSubscriptionRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/webhooks.rs | crates/router/src/routes/webhooks.rs | use actix_web::{web, HttpRequest, Responder};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{
api_locking,
webhooks::{self, types},
},
services::{api, authentication as auth},
};
#[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))]
#[cfg(feature = "v1")]
pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
state: web::Data<AppState>,
req: HttpRequest,
body: web::Bytes,
path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::IncomingWebhookReceive;
let (merchant_id, connector_id_or_name) = path.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&req,
(),
|state, auth, _, req_state| {
webhooks::incoming_webhooks_wrapper::<W>(
&flow,
state.to_owned(),
req_state,
&req,
auth.platform,
&connector_id_or_name,
body.clone(),
false,
)
},
&auth::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::IncomingRelayWebhookReceive))]
pub async fn receive_incoming_relay_webhook<W: types::OutgoingWebhookType>(
state: web::Data<AppState>,
req: HttpRequest,
body: web::Bytes,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::MerchantConnectorAccountId,
)>,
) -> impl Responder {
let flow = Flow::IncomingWebhookReceive;
let (merchant_id, connector_id) = path.into_inner();
let is_relay_webhook = true;
Box::pin(api::server_wrap(
flow.clone(),
state,
&req,
(),
|state, auth, _, req_state| {
webhooks::incoming_webhooks_wrapper::<W>(
&flow,
state.to_owned(),
req_state,
&req,
auth.platform,
connector_id.get_string_repr(),
body.clone(),
is_relay_webhook,
)
},
&auth::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::IncomingRelayWebhookReceive))]
pub async fn receive_incoming_relay_webhook<W: types::OutgoingWebhookType>(
state: web::Data<AppState>,
req: HttpRequest,
body: web::Bytes,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ProfileId,
common_utils::id_type::MerchantConnectorAccountId,
)>,
) -> impl Responder {
let flow = Flow::IncomingWebhookReceive;
let (merchant_id, profile_id, connector_id) = path.into_inner();
let is_relay_webhook = true;
Box::pin(api::server_wrap(
flow.clone(),
state,
&req,
(),
|state, auth, _, req_state| {
webhooks::incoming_webhooks_wrapper::<W>(
&flow,
state.to_owned(),
req_state,
&req,
auth.platform,
auth.profile,
&connector_id,
body.clone(),
is_relay_webhook,
)
},
&auth::MerchantIdAndProfileIdAuth {
merchant_id,
profile_id,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))]
#[cfg(feature = "v2")]
pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
state: web::Data<AppState>,
req: HttpRequest,
body: web::Bytes,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ProfileId,
common_utils::id_type::MerchantConnectorAccountId,
)>,
) -> impl Responder {
let flow = Flow::IncomingWebhookReceive;
let (merchant_id, profile_id, connector_id) = path.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&req,
(),
|state, auth, _, req_state| {
webhooks::incoming_webhooks_wrapper::<W>(
&flow,
state.to_owned(),
req_state,
&req,
auth.platform,
auth.profile,
&connector_id,
body.clone(),
false,
)
},
&auth::MerchantIdAndProfileIdAuth {
merchant_id,
profile_id,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::IncomingNetworkTokenWebhookReceive))]
pub async fn receive_network_token_requestor_incoming_webhook<W: types::OutgoingWebhookType>(
state: web::Data<AppState>,
req: HttpRequest,
body: web::Bytes,
_path: web::Path<String>,
) -> impl Responder {
let flow = Flow::IncomingNetworkTokenWebhookReceive;
Box::pin(api::server_wrap(
flow.clone(),
state,
&req,
(),
|state, _: (), _, _| {
webhooks::network_token_incoming_webhooks_wrapper::<W>(
&flow,
state.to_owned(),
&req,
body.clone(),
)
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.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/routes/user_role.rs | crates/router/src/routes/user_role.rs | use actix_web::{web, HttpRequest, HttpResponse};
use api_models::user_role::{self as user_role_api, role as role_api};
use common_enums::TokenPurpose;
use router_env::Flow;
use super::AppState;
use crate::{
core::{
api_locking,
user_role::{self as user_role_core, role as role_core},
},
services::{
api,
authentication::{self as auth},
authorization::permissions::Permission,
},
};
// TODO: To be deprecated
pub async fn get_authorization_info(
state: web::Data<AppState>,
http_req: HttpRequest,
) -> HttpResponse {
let flow = Flow::GetAuthorizationInfo;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
(),
|state, _: (), _, _| async move {
user_role_core::get_authorization_info_with_groups(state).await
},
&auth::JWTAuth {
permission: Permission::MerchantUserRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::GetRoleFromToken;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user, _, _| async move {
role_core::get_role_from_token_with_groups(state, user).await
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_groups_and_resources_for_role_from_token(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::GetRoleFromTokenV2;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user, _, _| async move {
role_core::get_groups_and_resources_for_role_from_token(state, user).await
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_parent_groups_info_for_role_from_token(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::GetParentGroupsInfoForRoleFromToken;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user, _, _| async move {
role_core::get_parent_groups_info_for_role_from_token(state, user).await
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
// TODO: To be deprecated
pub async fn create_role(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<role_api::CreateRoleRequest>,
) -> HttpResponse {
let flow = Flow::CreateRole;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
role_core::create_role,
&auth::JWTAuth {
permission: Permission::MerchantUserWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn create_role_v2(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<role_api::CreateRoleV2Request>,
) -> HttpResponse {
let flow = Flow::CreateRoleV2;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
role_core::create_role_v2,
&auth::JWTAuth {
permission: Permission::MerchantUserWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_role(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::GetRole;
let request_payload = user_role_api::role::GetRoleRequest {
role_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
request_payload,
|state, user, payload, _| async move {
role_core::get_role_with_groups(state, user, payload).await
},
&auth::JWTAuth {
permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_parent_info_for_role(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::GetRoleV2;
let request_payload = user_role_api::role::GetRoleRequest {
role_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
request_payload,
|state, user, payload, _| async move {
role_core::get_parent_info_for_role(state, user, payload).await
},
&auth::JWTAuth {
permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn update_role(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<role_api::UpdateRoleRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::UpdateRole;
let role_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, user, req, _| role_core::update_role(state, user, req, &role_id),
&auth::JWTAuth {
permission: Permission::MerchantUserWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn update_user_role(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_role_api::UpdateUserRoleRequest>,
) -> HttpResponse {
let flow = Flow::UpdateUserRole;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
user_role_core::update_user_role,
&auth::JWTAuth {
permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn accept_invitations_v2(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_role_api::AcceptInvitationsV2Request>,
) -> HttpResponse {
let flow = Flow::AcceptInvitationsV2;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, user, req_body, _| user_role_core::accept_invitations_v2(state, user, req_body),
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn accept_invitations_pre_auth(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_role_api::AcceptInvitationsPreAuthRequest>,
) -> HttpResponse {
let flow = Flow::AcceptInvitationsPreAuth;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, user, req_body, _| async move {
user_role_core::accept_invitations_pre_auth(state, user, req_body).await
},
&auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn delete_user_role(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_role_api::DeleteUserRoleRequest>,
) -> HttpResponse {
let flow = Flow::DeleteUserRole;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload.into_inner(),
user_role_core::delete_user_role,
&auth::JWTAuth {
permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_role_information(
state: web::Data<AppState>,
http_req: HttpRequest,
) -> HttpResponse {
let flow = Flow::GetRolesInfo;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
(),
|_, _: (), _, _| async move {
user_role_core::get_authorization_info_with_group_tag().await
},
&auth::JWTAuth {
permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_parent_group_info(
state: web::Data<AppState>,
http_req: HttpRequest,
query: web::Query<role_api::GetParentGroupsInfoQueryParams>,
) -> HttpResponse {
let flow = Flow::GetParentGroupInfo;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
query.into_inner(),
|state, user_from_token, request, _| async move {
user_role_core::get_parent_group_info(state, user_from_token, request).await
},
&auth::JWTAuth {
permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn list_users_in_lineage(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<user_role_api::ListUsersInEntityRequest>,
) -> HttpResponse {
let flow = Flow::ListUsersInLineage;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
query.into_inner(),
|state, user_from_token, request, _| {
user_role_core::list_users_in_lineage(state, user_from_token, request)
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn list_roles_with_info(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<role_api::ListRolesQueryParams>,
) -> HttpResponse {
let flow = Flow::ListRolesV2;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
query.into_inner(),
|state, user_from_token, request, _| {
role_core::list_roles_with_info(state, user_from_token, request)
},
&auth::JWTAuth {
permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn list_invitable_roles_at_entity_level(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<role_api::ListRolesAtEntityLevelRequest>,
) -> HttpResponse {
let flow = Flow::ListInvitableRolesAtEntityLevel;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
query.into_inner(),
|state, user_from_token, req, _| {
role_core::list_roles_at_entity_level(
state,
user_from_token,
req,
role_api::RoleCheckType::Invite,
)
},
&auth::JWTAuth {
permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn list_updatable_roles_at_entity_level(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<role_api::ListRolesAtEntityLevelRequest>,
) -> HttpResponse {
let flow = Flow::ListUpdatableRolesAtEntityLevel;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
query.into_inner(),
|state, user_from_token, req, _| {
role_core::list_roles_at_entity_level(
state,
user_from_token,
req,
role_api::RoleCheckType::Update,
)
},
&auth::JWTAuth {
permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn list_invitations_for_user(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::ListInvitationsForUser;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user_id_from_token, _, _| {
user_role_core::list_invitations_for_user(state, user_id_from_token)
},
&auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::AcceptInvite),
api_locking::LockAction::NotApplicable,
))
.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/routes/relay.rs | crates/router/src/routes/relay.rs | use actix_web::{web, Responder};
use router_env::{instrument, tracing, Flow};
use crate::{
self as app,
core::{api_locking, relay},
services::{api, authentication as auth},
};
#[instrument(skip_all, fields(flow = ?Flow::Relay))]
#[cfg(feature = "oltp")]
pub async fn relay(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<api_models::relay::RelayRequest>,
) -> impl Responder {
let flow = Flow::Relay;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
relay::relay_flow_decider(
state,
auth.platform,
#[cfg(feature = "v1")]
auth.profile.map(|profile| profile.get_id().clone()),
#[cfg(feature = "v2")]
Some(auth.profile.get_id().clone()),
req,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::RelayRetrieve))]
#[cfg(feature = "oltp")]
pub async fn relay_retrieve(
state: web::Data<app::AppState>,
path: web::Path<common_utils::id_type::RelayId>,
req: actix_web::HttpRequest,
query_params: web::Query<api_models::relay::RelayRetrieveBody>,
) -> impl Responder {
let flow = Flow::RelayRetrieve;
let relay_retrieve_request = api_models::relay::RelayRetrieveRequest {
force_sync: query_params.force_sync,
id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
relay_retrieve_request,
|state, auth: auth::AuthenticationData, req, _| {
relay::relay_retrieve(
state,
auth.platform,
#[cfg(feature = "v1")]
auth.profile.map(|profile| profile.get_id().clone()),
#[cfg(feature = "v2")]
Some(auth.profile.get_id().clone()),
req,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.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/routes/admin.rs | crates/router/src/routes/admin.rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{admin::*, api_locking, errors},
services::{api, authentication as auth, authorization::permissions::Permission},
types::api::admin,
};
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::OrganizationCreate))]
pub async fn organization_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<admin::OrganizationCreateRequest>,
) -> HttpResponse {
let flow = Flow::OrganizationCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| create_organization(state, req),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all, fields(flow = ?Flow::OrganizationCreate))]
pub async fn organization_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<admin::OrganizationCreateRequest>,
) -> HttpResponse {
let flow = Flow::OrganizationCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| create_organization(state, req),
&auth::V2AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::OrganizationUpdate))]
pub async fn organization_update(
state: web::Data<AppState>,
req: HttpRequest,
org_id: web::Path<common_utils::id_type::OrganizationId>,
json_payload: web::Json<admin::OrganizationUpdateRequest>,
) -> HttpResponse {
let flow = Flow::OrganizationUpdate;
let organization_id = org_id.into_inner();
let org_id = admin::OrganizationId {
organization_id: organization_id.clone(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| update_organization(state, org_id.clone(), req),
auth::auth_type(
&auth::PlatformOrgAdminAuth {
is_admin_auth_allowed: true,
organization_id: Some(organization_id.clone()),
},
&auth::JWTAuthOrganizationFromRoute {
organization_id,
required_permission: Permission::OrganizationAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all, fields(flow = ?Flow::OrganizationUpdate))]
pub async fn organization_update(
state: web::Data<AppState>,
req: HttpRequest,
org_id: web::Path<common_utils::id_type::OrganizationId>,
json_payload: web::Json<admin::OrganizationUpdateRequest>,
) -> HttpResponse {
let flow = Flow::OrganizationUpdate;
let organization_id = org_id.into_inner();
let org_id = admin::OrganizationId {
organization_id: organization_id.clone(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| update_organization(state, org_id.clone(), req),
auth::auth_type(
&auth::V2AdminApiAuth,
&auth::JWTAuthOrganizationFromRoute {
organization_id,
required_permission: Permission::OrganizationAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::OrganizationRetrieve))]
pub async fn organization_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
org_id: web::Path<common_utils::id_type::OrganizationId>,
) -> HttpResponse {
let flow = Flow::OrganizationRetrieve;
let organization_id = org_id.into_inner();
let payload = admin::OrganizationId {
organization_id: organization_id.clone(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, req, _| get_organization(state, req),
auth::auth_type(
&auth::PlatformOrgAdminAuth {
is_admin_auth_allowed: true,
organization_id: Some(organization_id.clone()),
},
&auth::JWTAuthOrganizationFromRoute {
organization_id,
required_permission: Permission::OrganizationAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all, fields(flow = ?Flow::OrganizationRetrieve))]
pub async fn organization_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
org_id: web::Path<common_utils::id_type::OrganizationId>,
) -> HttpResponse {
let flow = Flow::OrganizationRetrieve;
let organization_id = org_id.into_inner();
let payload = admin::OrganizationId {
organization_id: organization_id.clone(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, req, _| get_organization(state, req),
auth::auth_type(
&auth::V2AdminApiAuth,
&auth::JWTAuthOrganizationFromRoute {
organization_id,
required_permission: Permission::OrganizationAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountCreate))]
pub async fn merchant_account_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<admin::MerchantAccountCreate>,
) -> HttpResponse {
let flow = Flow::MerchantsAccountCreate;
let payload = json_payload.into_inner();
if let Err(api_error) = payload
.webhook_details
.as_ref()
.map(|details| {
details
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
})
.transpose()
{
return api::log_and_return_error_response(api_error.into());
}
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, req, _| create_merchant_account(state, req, auth),
&auth::PlatformOrgAdminAuth {
is_admin_auth_allowed: true,
organization_id: None,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountCreate))]
pub async fn merchant_account_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_models::admin::MerchantAccountCreateWithoutOrgId>,
) -> HttpResponse {
let flow = Flow::MerchantsAccountCreate;
let headers = req.headers();
let org_id = match auth::HeaderMapStruct::new(headers).get_organization_id_from_header() {
Ok(org_id) => org_id,
Err(e) => return api::log_and_return_error_response(e),
};
// Converting from MerchantAccountCreateWithoutOrgId to MerchantAccountCreate so we can use the existing
// `create_merchant_account` function for v2 as well
let json_payload = json_payload.into_inner();
let new_request_payload_with_org_id = api_models::admin::MerchantAccountCreate {
merchant_name: json_payload.merchant_name,
merchant_details: json_payload.merchant_details,
metadata: json_payload.metadata,
organization_id: org_id,
product_type: json_payload.product_type,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
new_request_payload_with_org_id,
|state, _, req, _| create_merchant_account(state, req, None),
&auth::V2AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountRetrieve))]
pub async fn retrieve_merchant_account(
state: web::Data<AppState>,
req: HttpRequest,
mid: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::MerchantsAccountRetrieve;
let merchant_id = mid.into_inner();
let payload = admin::MerchantId {
merchant_id: merchant_id.clone(),
};
api::server_wrap(
flow,
state,
&req,
payload,
|state, _, req, _| get_merchant_account(state, req, None),
auth::auth_type(
&auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
merchant_id_from_route: merchant_id.clone(),
is_admin_auth_allowed: true,
},
&auth::JWTAuthMerchantFromRoute {
merchant_id,
// This should ideally be MerchantAccountRead, but since FE is calling this API for
// profile level users currently keeping this as ProfileAccountRead. FE is removing
// this API call for profile level users.
// TODO: Convert this to MerchantAccountRead once FE changes are done.
required_permission: Permission::ProfileAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
)
.await
}
/// Merchant Account - Retrieve
///
/// Retrieve a merchant account details.
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountRetrieve))]
pub async fn retrieve_merchant_account(
state: web::Data<AppState>,
req: HttpRequest,
mid: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::MerchantsAccountRetrieve;
let merchant_id = mid.into_inner();
let payload = admin::MerchantId {
merchant_id: merchant_id.clone(),
};
api::server_wrap(
flow,
state,
&req,
payload,
|state, _, req, _| get_merchant_account(state, req, None),
auth::auth_type(
&auth::V2AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
// This should ideally be MerchantAccountRead, but since FE is calling this API for
// profile level users currently keeping this as ProfileAccountRead. FE is removing
// this API call for profile level users.
// TODO: Convert this to MerchantAccountRead once FE changes are done.
required_permission: Permission::ProfileAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all, fields(flow = ?Flow::MerchantAccountList))]
pub async fn merchant_account_list(
state: web::Data<AppState>,
req: HttpRequest,
organization_id: web::Path<common_utils::id_type::OrganizationId>,
) -> HttpResponse {
let flow = Flow::MerchantAccountList;
let organization_id = admin::OrganizationId {
organization_id: organization_id.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
organization_id,
|state, _, request, _| list_merchant_account(state, request),
auth::auth_type(
&auth::V2AdminApiAuth,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::MerchantAccountList))]
pub async fn merchant_account_list(
state: web::Data<AppState>,
req: HttpRequest,
query_params: web::Query<api_models::admin::MerchantAccountListRequest>,
) -> HttpResponse {
let flow = Flow::MerchantAccountList;
Box::pin(api::server_wrap(
flow,
state,
&req,
query_params.into_inner(),
|state, auth, request, _| list_merchant_account(state, request, auth),
auth::auth_type(
&auth::PlatformOrgAdminAuth {
is_admin_auth_allowed: true,
organization_id: None,
},
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Merchant Account - Update
///
/// To update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountUpdate))]
pub async fn update_merchant_account(
state: web::Data<AppState>,
req: HttpRequest,
mid: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<admin::MerchantAccountUpdate>,
) -> HttpResponse {
let flow = Flow::MerchantsAccountUpdate;
let merchant_id = mid.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| merchant_account_update(state, &merchant_id, None, req),
auth::auth_type(
&auth::V2AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountUpdate))]
pub async fn update_merchant_account(
state: web::Data<AppState>,
req: HttpRequest,
mid: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<admin::MerchantAccountUpdate>,
) -> HttpResponse {
let flow = Flow::MerchantsAccountUpdate;
let merchant_id = mid.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| merchant_account_update(state, &merchant_id, None, req),
auth::auth_type(
&auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
merchant_id_from_route: merchant_id.clone(),
is_admin_auth_allowed: true,
},
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Merchant Account - Delete
///
/// To delete a merchant account
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountDelete))]
pub async fn delete_merchant_account(
state: web::Data<AppState>,
req: HttpRequest,
mid: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::MerchantsAccountDelete;
let mid = mid.into_inner();
let payload = web::Json(admin::MerchantId { merchant_id: mid }).into_inner();
api::server_wrap(
flow,
state,
&req,
payload,
|state, _, req, _| merchant_account_delete(state, req.merchant_id),
&auth::V2AdminApiAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountDelete))]
pub async fn delete_merchant_account(
state: web::Data<AppState>,
req: HttpRequest,
mid: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::MerchantsAccountDelete;
let mid = mid.into_inner();
let payload = web::Json(admin::MerchantId { merchant_id: mid }).into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, req, _| merchant_account_delete(state, req.merchant_id),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
/// Merchant Connector - Create
///
/// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc."
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsCreate))]
pub async fn connector_create(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<admin::MerchantConnectorCreate>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsCreate;
let payload = json_payload.into_inner();
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth_data, req, _| {
create_connector(
state,
req,
auth_data.platform.get_processor().clone(),
auth_data.profile.map(|profile| profile.get_id().clone()),
)
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::ProfileConnectorWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Merchant Connector - Create
///
/// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc."
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsCreate))]
pub async fn connector_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<admin::MerchantConnectorCreate>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsCreate;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth_data: auth::AuthenticationData, req, _| {
create_connector(state, req, auth_data.platform.get_processor().clone(), None)
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Merchant Connector - Retrieve
///
/// Retrieve Merchant Connector Details
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsRetrieve))]
pub async fn connector_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::MerchantConnectorAccountId,
)>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsRetrieve;
let (merchant_id, merchant_connector_id) = path.into_inner();
let payload = web::Json(admin::MerchantConnectorId {
merchant_id: merchant_id.clone(),
merchant_connector_id,
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, req, _| {
retrieve_connector(
state,
auth.platform.get_processor().clone(),
auth.profile.map(|profile| profile.get_id().clone()),
req.merchant_connector_id,
)
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id,
// This should ideally be ProfileConnectorRead, but since this API responds with
// sensitive data, keeping this as ProfileConnectorWrite
// TODO: Convert this to ProfileConnectorRead once data is masked.
required_permission: Permission::ProfileConnectorWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Merchant Connector - Retrieve
///
/// Retrieve Merchant Connector Details
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsRetrieve))]
pub async fn connector_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantConnectorAccountId>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsRetrieve;
let id = path.into_inner();
let payload = web::Json(admin::MerchantConnectorId { id: id.clone() }).into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
retrieve_connector(state, auth.platform.get_processor().clone(), req.id.clone())
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantConnectorRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsList))]
pub async fn connector_list(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::ProfileId>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsList;
let profile_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
profile_id.to_owned(),
|state, auth: auth::AuthenticationData, _, _| {
list_connectors_for_a_profile(
state,
auth.platform.get_processor().clone(),
profile_id.clone(),
)
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantConnectorRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Merchant Connector - List
///
/// List Merchant Connector Details for the merchant
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsList))]
pub async fn connector_list(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsList;
let merchant_id = path.into_inner();
api::server_wrap(
flow,
state,
&req,
merchant_id.to_owned(),
|state, auth, _, _| {
list_payment_connectors(state, auth.platform.get_processor().clone(), None)
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantConnectorRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
/// Merchant Connector - List
///
/// List Merchant Connector Details for the merchant
#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsList))]
pub async fn connector_list_profile(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsList;
let merchant_id = path.into_inner();
api::server_wrap(
flow,
state,
&req,
merchant_id.to_owned(),
|state, auth, _, _| {
list_payment_connectors(
state,
auth.platform.get_processor().clone(),
auth.profile.map(|profile| vec![profile.get_id().clone()]),
)
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::ProfileConnectorRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
)
.await
}
/// Merchant Connector - Update
///
/// To update an existing Merchant Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc.
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsUpdate))]
pub async fn connector_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::MerchantConnectorAccountId,
)>,
json_payload: web::Json<api_models::admin::MerchantConnectorUpdate>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsUpdate;
let (merchant_id, merchant_connector_id) = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth, req, _| {
update_connector(
state,
auth.platform.get_processor().get_account().get_id().clone(),
auth.profile.map(|profile| profile.get_id().clone()),
&merchant_connector_id,
req,
)
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::ProfileConnectorWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Merchant Connector - Update
///
/// To update an existing Merchant Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc.
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsUpdate))]
pub async fn connector_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantConnectorAccountId>,
json_payload: web::Json<api_models::admin::MerchantConnectorUpdate>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsUpdate;
let id = path.into_inner();
let payload = json_payload.into_inner();
let merchant_id = payload.merchant_id.clone();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, req, _| update_connector(state, merchant_id.clone(), None, &id, req),
auth::auth_type(
&auth::V2AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Merchant Connector - Delete
///
/// Delete or Detach a Merchant Connector from Merchant Account
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsDelete))]
pub async fn connector_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::MerchantConnectorAccountId,
)>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsDelete;
let (merchant_id, merchant_connector_id) = path.into_inner();
let payload = web::Json(admin::MerchantConnectorId {
merchant_id: merchant_id.clone(),
merchant_connector_id,
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, req, _| delete_connector(state, req.merchant_id, req.merchant_connector_id),
auth::auth_type(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Merchant Connector - Delete
///
/// Delete or Detach a Merchant Connector from Merchant Account
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsDelete))]
pub async fn connector_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantConnectorAccountId>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsDelete;
let id = path.into_inner();
let payload = web::Json(admin::MerchantConnectorId { id: id.clone() }).into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
delete_connector(state, auth.platform, req.id)
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Merchant Account - Toggle KV
///
/// Toggle KV mode for the Merchant Account
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn merchant_account_toggle_kv(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<admin::ToggleKVRequest>,
) -> HttpResponse {
let flow = Flow::ConfigKeyUpdate;
let mut payload = json_payload.into_inner();
payload.merchant_id = path.into_inner();
api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| kv_for_merchant(state, payload.merchant_id, payload.kv_enabled),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn merchant_account_toggle_kv(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<admin::ToggleKVRequest>,
) -> HttpResponse {
let flow = Flow::ConfigKeyUpdate;
let mut payload = json_payload.into_inner();
payload.merchant_id = path.into_inner();
api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| kv_for_merchant(state, payload.merchant_id, payload.kv_enabled),
&auth::V2AdminApiAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
/// Merchant Account - Transfer Keys
///
/// Transfer Merchant Encryption key to keymanager
#[instrument(skip_all)]
pub async fn merchant_account_toggle_all_kv(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<admin::ToggleAllKVRequest>,
) -> HttpResponse {
let flow = Flow::MerchantTransferKey;
let payload = json_payload.into_inner();
api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| toggle_kv_for_all_merchants(state, payload.kv_enabled),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
/// Merchant Account - KV Status
///
/// Toggle KV mode for the Merchant Account
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn merchant_account_kv_status(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::ConfigKeyFetch;
let merchant_id = path.into_inner();
api::server_wrap(
flow,
state,
&req,
merchant_id,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/payouts.rs | crates/router/src/routes/payouts.rs | use actix_web::{
body::{BoxBody, MessageBody},
web, HttpRequest, HttpResponse, Responder,
};
#[cfg(feature = "v1")]
use api_models::payments::BrowserInformation;
use common_utils::id_type;
#[cfg(feature = "v2")]
use common_utils::types::BrowserInformation;
use hyperswitch_domain_models::payments::HeaderPayload;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{
api_locking::{self, GetLockingInput},
errors::RouterResult,
payouts::*,
},
logger,
routes::lock_utils,
services::{
api,
authentication::{self as auth},
authorization::permissions::Permission,
},
types::{api::payouts as payout_types, transformers::ForeignTryFrom},
};
/// Payouts - Create
#[instrument(skip_all, fields(flow = ?Flow::PayoutsCreate))]
pub async fn payouts_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payout_types::PayoutCreateRequest>,
) -> HttpResponse {
let flow = Flow::PayoutsCreate;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => return api::log_and_return_error_response(err),
};
let mut payload = json_payload.into_inner();
if let Err(err) = populate_browser_info_for_payouts(&req, &mut payload, &header_payload) {
return api::log_and_return_error_response(err);
}
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_create_core(state, auth.platform, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "payouts"))]
/// Payouts - Retrieve
#[instrument(skip_all, fields(flow = ?Flow::PayoutsRetrieve))]
pub async fn payouts_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::PayoutId>,
query_params: web::Query<payout_types::PayoutRetrieveBody>,
) -> HttpResponse {
let payout_retrieve_request = payout_types::PayoutRetrieveRequest {
payout_id: path.into_inner(),
force_sync: query_params.force_sync.to_owned(),
merchant_id: query_params.merchant_id.to_owned(),
};
let flow = Flow::PayoutsRetrieve;
Box::pin(api::server_wrap(
flow,
state,
&req,
payout_retrieve_request,
|state, auth: auth::AuthenticationData, req, _| {
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
payouts_retrieve_core(state, auth.platform, profile_id, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Update
#[instrument(skip_all, fields(flow = ?Flow::PayoutsUpdate))]
pub async fn payouts_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::PayoutId>,
json_payload: web::Json<payout_types::PayoutCreateRequest>,
) -> HttpResponse {
let flow = Flow::PayoutsUpdate;
let payout_id = path.into_inner();
let mut payout_update_payload = json_payload.into_inner();
payout_update_payload.payout_id = Some(payout_id);
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => return api::log_and_return_error_response(err),
};
if let Err(err) =
populate_browser_info_for_payouts(&req, &mut payout_update_payload, &header_payload)
{
return api::log_and_return_error_response(err);
}
Box::pin(api::server_wrap(
flow,
state,
&req,
payout_update_payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_update_core(state, auth.platform, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PayoutsConfirm))]
pub async fn payouts_confirm(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payout_types::PayoutCreateRequest>,
path: web::Path<id_type::PayoutId>,
) -> HttpResponse {
let flow = Flow::PayoutsConfirm;
let mut payload = json_payload.into_inner();
let payout_id = path.into_inner();
tracing::Span::current().record("payout_id", payout_id.get_string_repr());
payload.payout_id = Some(payout_id);
payload.confirm = Some(true);
let api_auth = auth::ApiKeyAuth::default();
let (auth_type, _auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(e) => return api::log_and_return_error_response(e),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => return api::log_and_return_error_response(err),
};
if let Err(err) = populate_browser_info_for_payouts(&req, &mut payload, &header_payload) {
return api::log_and_return_error_response(err);
}
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, req, _| payouts_confirm_core(state, auth.platform, req),
&*auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Cancel
#[instrument(skip_all, fields(flow = ?Flow::PayoutsCancel))]
pub async fn payouts_cancel(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::PayoutId>,
) -> HttpResponse {
let flow = Flow::PayoutsCancel;
let payload = payout_types::PayoutActionRequest {
payout_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_cancel_core(state, auth.platform, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Fulfill
#[instrument(skip_all, fields(flow = ?Flow::PayoutsFulfill))]
pub async fn payouts_fulfill(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::PayoutId>,
) -> HttpResponse {
let flow = Flow::PayoutsFulfill;
let payload = payout_types::PayoutActionRequest {
payout_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_fulfill_core(state, auth.platform, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - List
#[cfg(feature = "olap")]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
pub async fn payouts_list(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Query<payout_types::PayoutListConstraints>,
) -> HttpResponse {
let flow = Flow::PayoutsList;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_list_core(state, auth.platform, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantPayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - List Profile
#[cfg(all(feature = "olap", feature = "payouts", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
pub async fn payouts_list_profile(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Query<payout_types::PayoutListConstraints>,
) -> HttpResponse {
let flow = Flow::PayoutsList;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_list_core(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Filtered list
#[cfg(feature = "olap")]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
pub async fn payouts_list_by_filter(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payout_types::PayoutListFilterConstraints>,
) -> HttpResponse {
let flow = Flow::PayoutsList;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_filtered_list_core(state, auth.platform, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantPayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Filtered list
#[cfg(all(feature = "olap", feature = "payouts", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
pub async fn payouts_list_by_filter_profile(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payout_types::PayoutListFilterConstraints>,
) -> HttpResponse {
let flow = Flow::PayoutsList;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_filtered_list_core(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Available filters for Merchant
#[cfg(feature = "olap")]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))]
pub async fn payouts_list_available_filters_for_merchant(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::PayoutsFilter;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_list_available_filters_core(state, auth.platform, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantPayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Available filters for Profile
#[cfg(all(feature = "olap", feature = "payouts", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))]
pub async fn payouts_list_available_filters_for_profile(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::PayoutsFilter;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_list_available_filters_core(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PayoutsAccounts))]
// #[get("/accounts")]
pub async fn payouts_accounts() -> impl Responder {
let _flow = Flow::PayoutsAccounts;
http_response("accounts")
}
fn http_response<T: MessageBody + 'static>(response: T) -> HttpResponse<BoxBody> {
HttpResponse::Ok().body(response)
}
/// Payouts - Available filters for Profile
#[cfg(all(feature = "olap", feature = "payouts", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))]
pub async fn get_payout_filters(state: web::Data<AppState>, req: HttpRequest) -> impl Responder {
let flow = Flow::PayoutsFilter;
api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| get_payout_filters_core(state, auth.platform),
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
)
.await
}
pub fn populate_browser_info_for_payouts(
req: &HttpRequest,
payload: &mut payout_types::PayoutCreateRequest,
header_payload: &HeaderPayload,
) -> RouterResult<()> {
let mut browser_info = payload.browser_info.clone().unwrap_or(BrowserInformation {
color_depth: None,
java_enabled: None,
java_script_enabled: None,
language: None,
screen_height: None,
screen_width: None,
time_zone: None,
ip_address: None,
accept_header: None,
user_agent: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
referer: None,
});
let ip_address = req
.connection_info()
.realip_remote_addr()
.map(ToOwned::to_owned);
if ip_address.is_some() {
logger::debug!("Extracted IP address from payout request");
}
browser_info.ip_address = browser_info.ip_address.or_else(|| {
ip_address
.as_ref()
.map(|ip| ip.parse())
.transpose()
.unwrap_or_else(|error| {
logger::error!(
?error,
"Failed to parse IP address extracted from payout request"
);
None
})
});
if let Some(locale) = &header_payload.locale {
browser_info.accept_language = browser_info.accept_language.or(Some(locale.clone()));
}
payload.browser_info = Some(browser_info);
Ok(())
}
#[instrument(skip_all, fields(flow = ?Flow::PayoutsAggregate))]
#[cfg(feature = "olap")]
pub async fn get_payouts_aggregates(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PayoutsAggregate;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
get_aggregates_for_payouts(state, auth.platform, None, req)
},
&auth::JWTAuth {
permission: Permission::MerchantPayoutRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PayoutsAggregate))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn get_payouts_aggregates_profile(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PayoutsAggregate;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
get_aggregates_for_payouts(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
req,
)
},
&auth::JWTAuth {
permission: Permission::ProfilePayoutRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "payouts"))]
impl GetLockingInput for payout_types::PayoutsManualUpdateRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: router_env::types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payout_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(all(feature = "olap", feature = "payouts"))]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsManualUpdate))]
pub async fn payouts_manual_update(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payout_types::PayoutsManualUpdateRequest>,
path: web::Path<id_type::PayoutId>,
) -> HttpResponse {
let flow = Flow::PayoutsManualUpdate;
let mut payload = json_payload.into_inner();
let payout_id = path.into_inner();
let locking_action = payload.get_locking_input(flow.clone());
tracing::Span::current().record("payout_id", payout_id.get_string_repr());
payload.payout_id = payout_id;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _auth, req, _req_state| payouts_manual_update_core(state, req),
&auth::AdminApiAuth,
locking_action,
))
.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/routes/oidc.rs | crates/router/src/routes/oidc.rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};
use crate::{
core::api_locking,
routes::app::AppState,
services::{api, authentication as auth, oidc_provider},
};
/// OpenID Connect Discovery Document
#[instrument(skip_all, fields(flow = ?Flow::OidcDiscovery))]
pub async fn oidc_discovery(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::OidcDiscovery;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, _: (), _, _| oidc_provider::get_discovery_document(state),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
/// JWKS Endpoint - Exposes public keys for ID token verification
#[instrument(skip_all, fields(flow = ?Flow::OidcJwks))]
pub async fn jwks_endpoint(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::OidcJwks;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, _: (), _, _| oidc_provider::get_jwks(state),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.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/routes/health.rs | crates/router/src/routes/health.rs | use actix_web::{web, HttpRequest};
use api_models::health_check::RouterHealthCheckResponse;
use router_env::{instrument, logger, tracing, Flow};
use super::app;
use crate::{
core::{api_locking, health_check::HealthCheckInterface},
errors::{self, RouterResponse},
routes::metrics,
services::{api, authentication as auth},
};
/// .
// #[logger::instrument(skip_all, name = "name1", level = "warn", fields( key1 = "val1" ))]
#[instrument(skip_all, fields(flow = ?Flow::HealthCheck))]
// #[actix_web::get("/health")]
pub async fn health() -> impl actix_web::Responder {
metrics::HEALTH_METRIC.add(1, &[]);
logger::info!("Health was called");
actix_web::HttpResponse::Ok().body("health is good")
}
#[instrument(skip_all, fields(flow = ?Flow::DeepHealthCheck))]
pub async fn deep_health_check(
state: web::Data<app::AppState>,
request: HttpRequest,
) -> impl actix_web::Responder {
metrics::HEALTH_METRIC.add(1, &[]);
let flow = Flow::DeepHealthCheck;
Box::pin(api::server_wrap(
flow,
state,
&request,
(),
|state, _: (), _, _| deep_health_check_func(state),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
async fn deep_health_check_func(
state: app::SessionState,
) -> RouterResponse<RouterHealthCheckResponse> {
logger::info!("Deep health check was called");
logger::debug!("Database health check begin");
let db_status = state.health_check_db().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Database",
message,
})
})?;
logger::debug!("Database health check end");
logger::debug!("Redis health check begin");
let redis_status = state.health_check_redis().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Redis",
message,
})
})?;
logger::debug!("Redis health check end");
logger::debug!("Locker health check begin");
let locker_status = state.health_check_locker().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Locker",
message,
})
})?;
logger::debug!("Locker health check end");
logger::debug!("Analytics health check begin");
#[cfg(feature = "olap")]
let analytics_status = state.health_check_analytics().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Analytics",
message,
})
})?;
logger::debug!("Analytics health check end");
logger::debug!("gRPC health check begin");
#[cfg(feature = "dynamic_routing")]
let grpc_health_check = state.health_check_grpc().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "gRPC services",
message,
})
})?;
logger::debug!("gRPC health check end");
logger::debug!("Decision Engine health check begin");
#[cfg(feature = "dynamic_routing")]
let decision_engine_health_check =
state
.health_check_decision_engine()
.await
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Decision Engine service",
message,
})
})?;
logger::debug!("Decision Engine health check end");
logger::debug!("Opensearch health check begin");
#[cfg(feature = "olap")]
let opensearch_status = state.health_check_opensearch().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Opensearch",
message,
})
})?;
logger::debug!("Opensearch health check end");
logger::debug!("Outgoing Request health check begin");
let outgoing_check = state.health_check_outgoing().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Outgoing Request",
message,
})
})?;
logger::debug!("Outgoing Request health check end");
logger::debug!("Unified Connector Service health check begin");
let unified_connector_service_status = state
.health_check_unified_connector_service()
.await
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Unified Connector Service",
message,
})
})?;
logger::debug!("Unified Connector Service health check end");
let response = RouterHealthCheckResponse {
database: db_status.into(),
redis: redis_status.into(),
vault: locker_status.into(),
#[cfg(feature = "olap")]
analytics: analytics_status.into(),
#[cfg(feature = "olap")]
opensearch: opensearch_status.into(),
outgoing_request: outgoing_check.into(),
#[cfg(feature = "dynamic_routing")]
grpc_health_check,
#[cfg(feature = "dynamic_routing")]
decision_engine: decision_engine_health_check.into(),
unified_connector_service: unified_connector_service_status.into(),
};
Ok(api::ApplicationResponse::Json(response))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/verify_connector.rs | crates/router/src/routes/verify_connector.rs | use actix_web::{web, HttpRequest, HttpResponse};
use api_models::verify_connector::VerifyConnectorRequest;
use router_env::{instrument, tracing, Flow};
use super::AppState;
use crate::{
core::{api_locking, verify_connector},
services::{self, authentication as auth, authorization::permissions::Permission},
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::VerifyPaymentConnector))]
pub async fn payment_connector_verify(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<VerifyConnectorRequest>,
) -> HttpResponse {
let flow = Flow::VerifyPaymentConnector;
Box::pin(services::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
verify_connector::verify_connector_credentials(
state,
req,
auth.profile.map(|profile| profile.get_id().clone()),
)
},
&auth::JWTAuth {
permission: Permission::MerchantConnectorWrite,
},
api_locking::LockAction::NotApplicable,
))
.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/routes/chat.rs | crates/router/src/routes/chat.rs | use actix_web::{web, HttpRequest, HttpResponse};
#[cfg(feature = "olap")]
use api_models::chat as chat_api;
use router_env::{instrument, tracing, Flow};
use super::AppState;
use crate::{
core::{api_locking, chat as chat_core},
routes::metrics,
services::{
api,
authentication::{self as auth},
authorization::permissions::Permission,
},
};
#[instrument(skip_all)]
pub async fn get_data_from_hyperswitch_ai_workflow(
state: web::Data<AppState>,
http_req: HttpRequest,
payload: web::Json<chat_api::ChatRequest>,
) -> HttpResponse {
let flow = Flow::GetDataFromHyperswitchAiFlow;
let session_id = http_req
.headers()
.get(common_utils::consts::X_CHAT_SESSION_ID)
.and_then(|header_value| header_value.to_str().ok());
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
payload.into_inner(),
|state, user: auth::UserFromToken, payload, _| {
metrics::CHAT_REQUEST_COUNT.add(
1,
router_env::metric_attributes!(("merchant_id", user.merchant_id.clone())),
);
chat_core::get_data_from_hyperswitch_ai_workflow(state, user, payload, session_id)
},
// At present, the AI service retrieves data scoped to the merchant level
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all)]
pub async fn get_all_conversations(
state: web::Data<AppState>,
http_req: HttpRequest,
payload: web::Query<chat_api::ChatListRequest>,
) -> HttpResponse {
let flow = Flow::ListAllChatInteractions;
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
payload.into_inner(),
|state, user: auth::UserFromToken, payload, _| {
chat_core::list_chat_conversations(state, user, payload)
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.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/routes/gsm.rs | crates/router/src/routes/gsm.rs | use actix_web::{web, HttpRequest, Responder};
use api_models::gsm as gsm_api_types;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, gsm},
services::{api, authentication as auth},
};
#[cfg(feature = "v1")]
const ADMIN_API_AUTH: auth::AdminApiAuth = auth::AdminApiAuth;
#[cfg(feature = "v2")]
const ADMIN_API_AUTH: auth::V2AdminApiAuth = auth::V2AdminApiAuth;
/// Gsm - Create
///
/// To create a Gsm Rule
#[utoipa::path(
post,
path = "/gsm",
request_body(
content = GsmCreateRequest,
),
responses(
(status = 200, description = "Gsm created", body = GsmResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Create Gsm Rule",
security(("admin_api_key" = [])),
)]
#[instrument(skip_all, fields(flow = ?Flow::GsmRuleCreate))]
pub async fn create_gsm_rule(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<gsm_api_types::GsmCreateRequest>,
) -> impl Responder {
let payload = json_payload.into_inner();
let flow = Flow::GsmRuleCreate;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, _, payload, _| gsm::create_gsm_rule(state, payload),
&ADMIN_API_AUTH,
api_locking::LockAction::NotApplicable,
))
.await
}
/// Gsm - Get
///
/// To get a Gsm Rule
#[utoipa::path(
post,
path = "/gsm/get",
request_body(
content = GsmRetrieveRequest,
),
responses(
(status = 200, description = "Gsm retrieved", body = GsmResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Retrieve Gsm Rule",
security(("admin_api_key" = [])),
)]
#[instrument(skip_all, fields(flow = ?Flow::GsmRuleRetrieve))]
pub async fn get_gsm_rule(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<gsm_api_types::GsmRetrieveRequest>,
) -> impl Responder {
let gsm_retrieve_req = json_payload.into_inner();
let flow = Flow::GsmRuleRetrieve;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
gsm_retrieve_req,
|state, _, gsm_retrieve_req, _| gsm::retrieve_gsm_rule(state, gsm_retrieve_req),
&ADMIN_API_AUTH,
api_locking::LockAction::NotApplicable,
))
.await
}
/// Gsm - Update
///
/// To update a Gsm Rule
#[utoipa::path(
post,
path = "/gsm/update",
request_body(
content = GsmUpdateRequest,
),
responses(
(status = 200, description = "Gsm updated", body = GsmResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Update Gsm Rule",
security(("admin_api_key" = [])),
)]
#[instrument(skip_all, fields(flow = ?Flow::GsmRuleUpdate))]
pub async fn update_gsm_rule(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<gsm_api_types::GsmUpdateRequest>,
) -> impl Responder {
let payload = json_payload.into_inner();
let flow = Flow::GsmRuleUpdate;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, _, payload, _| gsm::update_gsm_rule(state, payload),
&ADMIN_API_AUTH,
api_locking::LockAction::NotApplicable,
))
.await
}
/// Gsm - Delete
///
/// To delete a Gsm Rule
#[utoipa::path(
post,
path = "/gsm/delete",
request_body(
content = GsmDeleteRequest,
),
responses(
(status = 200, description = "Gsm deleted", body = GsmDeleteResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Delete Gsm Rule",
security(("admin_api_key" = [])),
)]
#[instrument(skip_all, fields(flow = ?Flow::GsmRuleDelete))]
pub async fn delete_gsm_rule(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<gsm_api_types::GsmDeleteRequest>,
) -> impl Responder {
let payload = json_payload.into_inner();
let flow = Flow::GsmRuleDelete;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| gsm::delete_gsm_rule(state, payload),
&ADMIN_API_AUTH,
api_locking::LockAction::NotApplicable,
))
.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/routes/payment_methods.rs | crates/router/src/routes/payment_methods.rs | #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
use std::collections::HashMap;
use ::payment_methods::{
controller::PaymentMethodsController,
core::{migration, migration::payment_methods::migrate_payment_method},
};
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
use common_utils::{errors::CustomResult, id_type, transformers::ForeignFrom};
use diesel_models::enums::IntentStatus;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
bulk_tokenization::CardNetworkTokenizeRequest, merchant_key_store::MerchantKeyStore,
payment_methods::PaymentMethodCustomerMigrate, transformers::ForeignTryFrom,
};
use router_env::{instrument, logger, tracing, Flow};
use super::app::{AppState, SessionState};
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
use crate::core::{
customers,
payment_methods::{batch_retrieve, tokenize},
};
use crate::{
core::{
api_locking,
errors::{self, utils::StorageErrorExt},
payment_methods::{self as payment_methods_routes, cards, migration as update_migration},
},
services::{self, api, authentication as auth, authorization::permissions::Permission},
types::{
api::payment_methods::{self, PaymentMethodId},
domain,
storage::payment_method::PaymentTokenData,
},
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| async move {
Box::pin(cards::get_client_secret_or_add_payment_method(
&state,
req,
auth.platform.get_provider(),
))
.await
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, req_state| async move {
Box::pin(payment_methods_routes::create_payment_method(
&state,
&req_state,
req,
&auth.platform,
&auth.profile,
))
.await
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_intent_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodIntentCreate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| async move {
Box::pin(payment_methods_routes::payment_method_intent_create(
&state,
req,
auth.platform.get_provider().clone(),
))
.await
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// This struct is used internally only
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct PaymentMethodIntentConfirmInternal {
pub id: id_type::GlobalPaymentMethodId,
pub request: payment_methods::PaymentMethodIntentConfirm,
}
#[cfg(feature = "v2")]
impl From<PaymentMethodIntentConfirmInternal> for payment_methods::PaymentMethodIntentConfirm {
fn from(item: PaymentMethodIntentConfirmInternal) -> Self {
item.request
}
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for PaymentMethodIntentConfirmInternal {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::PaymentMethod {
payment_method_id: self.id.clone(),
payment_method_type: Some(self.request.payment_method_type),
payment_method_subtype: Some(self.request.payment_method_subtype),
})
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))]
pub async fn payment_method_update_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodId>,
json_payload: web::Json<payment_methods::PaymentMethodUpdate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsUpdate;
let payment_method_id = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payment_methods_routes::update_payment_method(
state,
auth.platform,
auth.profile,
req,
&payment_method_id,
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))]
pub async fn payment_method_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsRetrieve;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| {
payment_methods_routes::retrieve_payment_method(
state,
pm,
auth.platform.get_provider().clone(),
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))]
pub async fn payment_method_delete_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsDelete;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| {
payment_methods_routes::delete_payment_method(state, pm, auth.platform, auth.profile)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodMigrate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsMigrate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| async move {
let merchant_id = req.merchant_id.clone();
let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?;
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account,
key_store,
None,
);
Box::pin(migrate_payment_method(
&(&state).into(),
req,
&merchant_id,
&platform,
&cards::PmCards {
state: &state,
provider: platform.get_provider(),
},
))
.await
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
async fn get_merchant_account(
state: &SessionState,
merchant_id: &id_type::MerchantId,
) -> CustomResult<(MerchantKeyStore, domain::MerchantAccount), errors::ApiErrorResponse> {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
Ok((key_store, merchant_account))
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_methods(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<migration::PaymentMethodsMigrateForm>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsMigrate;
let (merchant_id, records, merchant_connector_ids) =
match form.validate_and_get_payment_method_records() {
Ok((merchant_id, records, merchant_connector_ids)) => {
(merchant_id, records, merchant_connector_ids)
}
Err(e) => return api::log_and_return_error_response(e.into()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
records,
|state, _, req, _| {
let merchant_id = merchant_id.clone();
let merchant_connector_ids = merchant_connector_ids.clone();
async move {
let (key_store, merchant_account) =
get_merchant_account(&state, &merchant_id).await?;
// Create customers if they are not already present
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account,
key_store,
None,
);
let mut mca_cache = HashMap::new();
let customers = Vec::<PaymentMethodCustomerMigrate>::foreign_try_from((
&req,
merchant_id.clone(),
))
.map_err(|e| errors::ApiErrorResponse::InvalidRequestData {
message: e.to_string(),
})?;
for record in &customers {
if let Some(connector_customer_details) = &record.connector_customer_details {
for connector_customer in connector_customer_details {
if !mca_cache.contains_key(&connector_customer.merchant_connector_id) {
let mca = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&merchant_id,
&connector_customer.merchant_connector_id,
platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_customer.merchant_connector_id.get_string_repr().to_string(),
},
)?;
mca_cache
.insert(connector_customer.merchant_connector_id.clone(), mca);
}
}
}
}
customers::migrate_customers(state.clone(), customers, platform.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let controller = cards::PmCards {
state: &state,
provider: platform.get_provider(),
};
Box::pin(migration::migrate_payment_methods(
&(&state).into(),
req,
&merchant_id,
&platform,
merchant_connector_ids,
&controller,
))
.await
}
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsBatchUpdate))]
pub async fn update_payment_methods(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<update_migration::PaymentMethodsUpdateForm>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsBatchUpdate;
let (merchant_id, records) = match form.validate_and_get_payment_method_records() {
Ok((merchant_id, records)) => (merchant_id, records),
Err(e) => return api::log_and_return_error_response(e.into()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
records,
|state, _, req, _| {
let merchant_id = merchant_id.clone();
async move {
let (key_store, merchant_account) =
get_merchant_account(&state, &merchant_id).await?;
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account,
key_store,
None,
);
Box::pin(update_migration::update_payment_methods(
&state,
req,
&merchant_id,
&platform,
))
.await
}
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsBatchRetrieve))]
pub async fn payment_methods_batch_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<batch_retrieve::PaymentMethodsBatchRetrieveForm>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsBatchRetrieve;
let (merchant_id, records) = match batch_retrieve::get_payment_method_batch_records(form) {
Ok(result) => result,
Err(error) => return api::log_and_return_error_response(error.into()),
};
if records.is_empty() {
return api::log_and_return_error_response(
errors::ApiErrorResponse::InvalidRequestData {
message: "No payment_method_ids provided".to_string(),
}
.into(),
);
}
if records.len() > 200 {
return api::log_and_return_error_response(
errors::ApiErrorResponse::InvalidRequestData {
message: "A maximum of 200 payment_method_ids are allowed per request".to_string(),
}
.into(),
);
}
let payload_records = records.clone();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload_records,
|state, _, _, _| {
let merchant_id = merchant_id.clone();
let records = records.clone();
async move {
let (key_store, merchant_account) =
get_merchant_account(&state, &merchant_id).await?;
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account,
key_store,
None,
);
let responses = batch_retrieve::retrieve_payment_method_data(
&state,
&merchant_id,
&platform,
records,
)
.await?;
Ok(services::ApplicationResponse::Json(responses))
}
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSave))]
pub async fn save_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSave;
let payload = json_payload.into_inner();
let pm_id = path.into_inner();
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
};
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
{
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
Box::pin(cards::add_payment_method_data(
state,
req,
auth.platform.get_provider().clone(),
pm_id.clone(),
))
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))]
pub async fn list_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsList;
let payload = json_payload.into_inner();
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
};
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
{
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
// TODO (#7195): Fill platform_merchant_account in the client secret auth and pass it here.
cards::list_payment_methods(state, auth.platform, req)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// List payment methods for a Customer
///
/// To filter and list the applicable payment methods for a particular Customer ID
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api(
state: web::Data<AppState>,
customer_id: web::Path<(id_type::CustomerId,)>,
req: HttpRequest,
query_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let customer_id = customer_id.into_inner().0;
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
};
let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::do_list_customer_pm_fetch_customer_if_not_passed(
state,
auth.platform,
Some(req),
Some(&customer_id),
None,
)
},
&*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// List payment methods for a Customer
///
/// To filter and list the applicable payment methods for a particular Customer ID
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api_client(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let api_key = auth::get_api_key(req.headers()).ok();
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
};
let (auth, _, is_ephemeral_auth) =
match auth::get_ephemeral_or_other_auth(req.headers(), false, Some(&payload), api_auth)
.await
{
Ok((auth, _auth_flow, is_ephemeral_auth)) => (auth, _auth_flow, is_ephemeral_auth),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::do_list_customer_pm_fetch_customer_if_not_passed(
state,
auth.platform,
Some(req),
None,
is_ephemeral_auth.then_some(api_key).flatten(),
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
/// Generate a form link for collecting payment methods for a customer
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))]
pub async fn initiate_pm_collect_link_flow(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCollectLinkRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodCollectLink;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
payment_methods_routes::initiate_pm_collect_link(state, auth.platform, req)
},
&auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api(
state: web::Data<AppState>,
customer_id: web::Path<id_type::GlobalCustomerId>,
req: HttpRequest,
query_payload: web::Query<api_models::payment_methods::ListMethodsForPaymentMethodsRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let customer_id = customer_id.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, _, _| {
payment_methods_routes::list_saved_payment_methods_for_customer(
state,
auth.platform.get_provider().clone(),
customer_id.clone(),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::GetPaymentMethodTokenData))]
pub async fn get_payment_method_token_data(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodId>,
json_payload: web::Json<api_models::payment_methods::GetTokenDataRequest>,
) -> HttpResponse {
let flow = Flow::GetPaymentMethodTokenData;
let payment_method_id = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payment_methods_routes::get_token_data_for_payment_method(
state,
auth.platform.get_provider().clone(),
auth.profile,
req,
payment_method_id.clone(),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::TotalPaymentMethodCount))]
pub async fn get_total_payment_method_count(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::TotalPaymentMethodCount;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
payment_methods_routes::get_total_saved_payment_methods_for_merchant(
state,
auth.platform.get_provider().clone(),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Generate a form link for collecting payment methods for a customer
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))]
pub async fn render_pm_collect_link(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(id_type::MerchantId, String)>,
) -> HttpResponse {
let flow = Flow::PaymentMethodCollectLink;
let (merchant_id, pm_collect_link_id) = path.into_inner();
let payload = payment_methods::PaymentMethodCollectLinkRenderRequest {
merchant_id: merchant_id.clone(),
pm_collect_link_id,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payment_methods_routes::render_pm_collect_link(
state,
auth.platform.get_provider().clone(),
req,
)
},
&auth::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))]
pub async fn payment_method_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsRetrieve;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| async move {
cards::PmCards {
state: &state,
provider: auth.platform.get_provider(),
}
.retrieve_payment_method(pm)
.await
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))]
pub async fn payment_method_update_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Json<payment_methods::PaymentMethodUpdate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsUpdate;
let payment_method_id = path.into_inner();
let payload = json_payload.into_inner();
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
};
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
{
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::update_customer_payment_method(
state,
auth.platform.get_provider().clone(),
req,
&payment_method_id,
None,
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))]
pub async fn payment_method_delete_api(
state: web::Data<AppState>,
req: HttpRequest,
payment_method_id: web::Path<(String,)>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsDelete;
let pm = PaymentMethodId {
payment_method_id: payment_method_id.into_inner().0,
};
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
};
let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
pm,
|state, auth: auth::AuthenticationData, req, _| async move {
cards::PmCards {
state: &state,
provider: auth.platform.get_provider(),
}
.delete_payment_method(req)
.await
},
&*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))]
pub async fn list_countries_currencies_for_connector_payment_method(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>,
) -> HttpResponse {
let flow = Flow::ListCountriesCurrencies;
let payload = query_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::list_countries_currencies_for_connector_payment_method(
state,
req,
auth.profile.map(|profile| profile.get_id().clone()),
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
}),
&auth::JWTAuth {
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/currency.rs | crates/router/src/routes/currency.rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::Flow;
use crate::{
core::{api_locking, currency},
routes::AppState,
services::{api, authentication as auth},
};
#[cfg(feature = "v1")]
pub async fn retrieve_forex(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::RetrieveForexFlow;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, _auth: auth::AuthenticationData, _, _| currency::retrieve_forex(state),
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::DashboardNoPermissionAuth,
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn convert_forex(
state: web::Data<AppState>,
req: HttpRequest,
params: web::Query<api_models::currency::CurrencyConversionParams>,
) -> HttpResponse {
let flow = Flow::RetrieveForexFlow;
let amount = params.amount;
let to_currency = ¶ms.to_currency;
let from_currency = ¶ms.from_currency;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, _: auth::AuthenticationData, _, _| {
currency::convert_forex(
state,
amount.get_amount_as_i64(),
to_currency.to_string(),
from_currency.to_string(),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::DashboardNoPermissionAuth,
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/authentication.rs | crates/router/src/routes/authentication.rs | use actix_web::{web, HttpRequest, Responder};
use api_models::authentication::{AuthenticationAuthenticateRequest, AuthenticationCreateRequest};
#[cfg(feature = "v1")]
use api_models::authentication::{
AuthenticationEligibilityCheckRequest, AuthenticationEligibilityRequest,
AuthenticationRetrieveEligibilityCheckRequest, AuthenticationSessionTokenRequest,
AuthenticationSyncPostUpdateRequest, AuthenticationSyncRequest,
};
use router_env::{instrument, tracing, Flow};
use crate::{
core::{api_locking, unified_authentication_service},
routes::app::{self},
services::{api, authentication as auth},
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::AuthenticationCreate))]
pub async fn authentication_create(
state: web::Data<app::AppState>,
req: HttpRequest,
json_payload: web::Json<AuthenticationCreateRequest>,
) -> impl Responder {
let flow = Flow::AuthenticationCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
unified_authentication_service::authentication_create_core(state, auth.platform, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::AuthenticationEligibility))]
pub async fn authentication_eligibility(
state: web::Data<app::AppState>,
req: HttpRequest,
json_payload: web::Json<AuthenticationEligibilityRequest>,
path: web::Path<common_utils::id_type::AuthenticationId>,
) -> impl Responder {
let flow = Flow::AuthenticationEligibility;
let api_auth = auth::ApiKeyAuth::default();
let payload = json_payload.into_inner();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
{
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
let authentication_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
unified_authentication_service::authentication_eligibility_core(
state,
auth.platform,
req,
authentication_id.clone(),
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::AuthenticationAuthenticate))]
pub async fn authentication_authenticate(
state: web::Data<app::AppState>,
req: HttpRequest,
json_payload: web::Json<AuthenticationAuthenticateRequest>,
path: web::Path<common_utils::id_type::AuthenticationId>,
) -> impl Responder {
let flow = Flow::AuthenticationAuthenticate;
let authentication_id = path.into_inner();
let api_auth = auth::ApiKeyAuth::default();
let payload = AuthenticationAuthenticateRequest {
authentication_id,
..json_payload.into_inner()
};
let (auth, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, auth_flow)) => (auth, auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
unified_authentication_service::authentication_authenticate_core(
state,
auth.platform,
req,
auth_flow,
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::AuthenticationEligibilityCheck))]
pub async fn authentication_eligibility_check(
state: web::Data<app::AppState>,
req: HttpRequest,
json_payload: web::Json<AuthenticationEligibilityCheckRequest>,
path: web::Path<common_utils::id_type::AuthenticationId>,
) -> impl Responder {
let flow = Flow::AuthenticationEligibilityCheck;
let authentication_id = path.into_inner();
let api_auth = auth::ApiKeyAuth::default();
let payload = AuthenticationEligibilityCheckRequest {
authentication_id,
..json_payload.into_inner()
};
let (auth, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, auth_flow)) => (auth, auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
unified_authentication_service::authentication_eligibility_check_core(
state,
auth.platform,
req,
auth_flow,
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::AuthenticationRetrieveEligibilityCheck))]
pub async fn authentication_retrieve_eligibility_check(
state: web::Data<app::AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::AuthenticationId>,
) -> impl Responder {
let flow = Flow::AuthenticationRetrieveEligibilityCheck;
let authentication_id = path.into_inner();
let payload = AuthenticationRetrieveEligibilityCheckRequest { authentication_id };
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
unified_authentication_service::authentication_retrieve_eligibility_check_core(
state,
auth.platform,
req,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::AuthenticationSync))]
pub async fn authentication_sync(
state: web::Data<app::AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::AuthenticationId,
)>,
json_payload: web::Json<AuthenticationSyncRequest>,
) -> impl Responder {
let flow = Flow::AuthenticationSync;
let api_auth = auth::ApiKeyAuth::default();
let (_merchant_id, authentication_id) = path.into_inner();
let payload = AuthenticationSyncRequest {
authentication_id,
..json_payload.into_inner()
};
let (auth, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, auth_flow)) => (auth, auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
unified_authentication_service::authentication_sync_core(
state,
auth.platform,
auth_flow,
req,
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::AuthenticationSyncPostUpdate))]
pub async fn authentication_sync_post_update(
state: web::Data<app::AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::AuthenticationId,
)>,
) -> impl Responder {
let flow = Flow::AuthenticationSyncPostUpdate;
let (merchant_id, authentication_id) = path.into_inner();
let payload = AuthenticationSyncPostUpdateRequest { authentication_id };
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
unified_authentication_service::authentication_post_sync_core(state, auth.platform, req)
},
&auth::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::AuthenticationSessionToken))]
pub async fn authentication_session_token(
state: web::Data<app::AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::AuthenticationId>,
json_payload: web::Json<AuthenticationSessionTokenRequest>,
) -> impl Responder {
let flow = Flow::AuthenticationSessionToken;
let authentication_id = path.into_inner();
let api_auth = auth::ApiKeyAuth::default();
let payload = AuthenticationSessionTokenRequest {
authentication_id: authentication_id.clone(),
..json_payload.into_inner()
};
let (auth, _auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, auth_flow)) => (auth, auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
unified_authentication_service::authentication_session_core(state, auth.platform, req)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.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/routes/files.rs | crates/router/src/routes/files.rs | use actix_multipart::Multipart;
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::files as file_types;
use router_env::{instrument, tracing, Flow};
use crate::core::api_locking;
pub mod transformers;
use super::app::AppState;
use crate::{
core::files::*,
services::{api, authentication as auth},
types::api::files,
};
#[cfg(feature = "v1")]
/// Files - Create
///
/// To create a file
#[utoipa::path(
post,
path = "/files",
request_body=MultipartRequestWithFile,
responses(
(status = 200, description = "File created", body = CreateFileResponse),
(status = 400, description = "Bad Request")
),
tag = "Files",
operation_id = "Create a File",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::CreateFile))]
pub async fn files_create(
state: web::Data<AppState>,
req: HttpRequest,
payload: Multipart,
) -> HttpResponse {
let flow = Flow::CreateFile;
let create_file_request_result = transformers::get_create_file_request(payload).await;
let create_file_request = match create_file_request_result {
Ok(valid_request) => valid_request,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
create_file_request,
|state, auth: auth::AuthenticationData, req, _| {
files_create_core(state, auth.platform, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::DashboardNoPermissionAuth,
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Files - Delete
///
/// To delete a file
#[utoipa::path(
delete,
path = "/files/{file_id}",
params(
("file_id" = String, Path, description = "The identifier for file")
),
responses(
(status = 200, description = "File deleted"),
(status = 404, description = "File not found")
),
tag = "Files",
operation_id = "Delete a File",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DeleteFile))]
pub async fn files_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::DeleteFile;
let file_id = files::FileId {
file_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
file_id,
|state, auth: auth::AuthenticationData, req, _| {
files_delete_core(state, auth.platform, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::DashboardNoPermissionAuth,
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Files - Retrieve
///
/// To retrieve a file
#[utoipa::path(
get,
path = "/files/{file_id}",
params(
("file_id" = String, Path, description = "The identifier for file")
),
responses(
(status = 200, description = "File body"),
(status = 400, description = "Bad Request")
),
tag = "Files",
operation_id = "Retrieve a File",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::RetrieveFile))]
pub async fn files_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Query<file_types::FileRetrieveQuery>,
) -> HttpResponse {
let flow = Flow::RetrieveFile;
let file_id = files::FileRetrieveRequest {
file_id: path.into_inner(),
dispute_id: json_payload.dispute_id.clone(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
file_id,
|state, auth: auth::AuthenticationData, req, _| {
files_retrieve_core(state, auth.platform, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::DashboardNoPermissionAuth,
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/revenue_recovery_redis.rs | crates/router/src/routes/revenue_recovery_redis.rs | use actix_web::{web, HttpRequest, HttpResponse};
use api_models::revenue_recovery_data_backfill::GetRedisDataQuery;
use router_env::{instrument, tracing, Flow};
use crate::{
core::{api_locking, revenue_recovery_data_backfill},
routes::AppState,
services::{api, authentication as auth},
};
#[instrument(skip_all, fields(flow = ?Flow::RevenueRecoveryRedis))]
pub async fn get_revenue_recovery_redis_data(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
query: web::Query<GetRedisDataQuery>,
) -> HttpResponse {
let flow = Flow::RevenueRecoveryRedis;
let connector_customer_id = path.into_inner();
let key_type = &query.key_type;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, _: (), _, _| {
revenue_recovery_data_backfill::get_redis_data(state, &connector_customer_id, key_type)
},
&auth::V2AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.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/routes/metrics.rs | crates/router/src/routes/metrics.rs | pub mod bg_metrics_collector;
pub mod request;
use router_env::{counter_metric, global_meter, histogram_metric_f64};
global_meter!(GLOBAL_METER, "ROUTER_API");
counter_metric!(HEALTH_METRIC, GLOBAL_METER); // No. of health API hits
counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses
// API Level Metrics
counter_metric!(REQUESTS_RECEIVED, GLOBAL_METER);
histogram_metric_f64!(REQUEST_TIME, GLOBAL_METER);
// Operation Level Metrics
counter_metric!(PAYMENT_OPS_COUNT, GLOBAL_METER);
counter_metric!(PAYMENT_COUNT, GLOBAL_METER);
counter_metric!(SUCCESSFUL_PAYMENT, GLOBAL_METER);
//TODO: This can be removed, added for payment list debugging
histogram_metric_f64!(PAYMENT_LIST_LATENCY, GLOBAL_METER);
counter_metric!(REFUND_COUNT, GLOBAL_METER);
counter_metric!(SUCCESSFUL_REFUND, GLOBAL_METER);
counter_metric!(PAYMENT_CANCEL_COUNT, GLOBAL_METER);
counter_metric!(SUCCESSFUL_CANCEL, GLOBAL_METER);
counter_metric!(PAYMENT_EXTEND_AUTHORIZATION_COUNT, GLOBAL_METER);
counter_metric!(SUCCESSFUL_EXTEND_AUTHORIZATION_COUNT, GLOBAL_METER);
counter_metric!(MANDATE_COUNT, GLOBAL_METER);
counter_metric!(SUBSEQUENT_MANDATE_PAYMENT, GLOBAL_METER);
// Manual retry metrics
counter_metric!(MANUAL_RETRY_REQUEST_COUNT, GLOBAL_METER);
counter_metric!(MANUAL_RETRY_COUNT, GLOBAL_METER);
counter_metric!(MANUAL_RETRY_VALIDATION_FAILED, GLOBAL_METER);
counter_metric!(STORED_TO_LOCKER, GLOBAL_METER);
counter_metric!(GET_FROM_LOCKER, GLOBAL_METER);
counter_metric!(DELETE_FROM_LOCKER, GLOBAL_METER);
counter_metric!(CREATED_TOKENIZED_CARD, GLOBAL_METER);
counter_metric!(DELETED_TOKENIZED_CARD, GLOBAL_METER);
counter_metric!(GET_TOKENIZED_CARD, GLOBAL_METER);
counter_metric!(TOKENIZED_DATA_COUNT, GLOBAL_METER); // Tokenized data added
counter_metric!(RETRIED_DELETE_DATA_COUNT, GLOBAL_METER); // Tokenized data retried
counter_metric!(CUSTOMER_CREATED, GLOBAL_METER);
counter_metric!(CUSTOMER_REDACTED, GLOBAL_METER);
counter_metric!(API_KEY_CREATED, GLOBAL_METER);
counter_metric!(API_KEY_REVOKED, GLOBAL_METER);
counter_metric!(MCA_CREATE, GLOBAL_METER);
// Flow Specific Metrics
histogram_metric_f64!(CONNECTOR_REQUEST_TIME, GLOBAL_METER);
counter_metric!(SESSION_TOKEN_CREATED, GLOBAL_METER);
counter_metric!(CONNECTOR_CALL_COUNT, GLOBAL_METER); // Attributes needed
counter_metric!(THREE_DS_PAYMENT_COUNT, GLOBAL_METER);
counter_metric!(THREE_DS_DOWNGRADE_COUNT, GLOBAL_METER);
counter_metric!(RESPONSE_DESERIALIZATION_FAILURE, GLOBAL_METER);
counter_metric!(CONNECTOR_ERROR_RESPONSE_COUNT, GLOBAL_METER);
counter_metric!(REQUEST_TIMEOUT_COUNT, GLOBAL_METER);
counter_metric!(EXECUTE_PRETASK_COUNT, GLOBAL_METER);
counter_metric!(CONNECTOR_PAYMENT_METHOD_TOKENIZATION, GLOBAL_METER);
counter_metric!(PREPROCESSING_STEPS_COUNT, GLOBAL_METER);
counter_metric!(CONNECTOR_CUSTOMER_CREATE, GLOBAL_METER);
counter_metric!(REDIRECTION_TRIGGERED, GLOBAL_METER);
// Connector Level Metric
counter_metric!(REQUEST_BUILD_FAILURE, GLOBAL_METER);
// Connector http status code metrics
counter_metric!(CONNECTOR_HTTP_STATUS_CODE_1XX_COUNT, GLOBAL_METER);
counter_metric!(CONNECTOR_HTTP_STATUS_CODE_2XX_COUNT, GLOBAL_METER);
counter_metric!(CONNECTOR_HTTP_STATUS_CODE_3XX_COUNT, GLOBAL_METER);
counter_metric!(CONNECTOR_HTTP_STATUS_CODE_4XX_COUNT, GLOBAL_METER);
counter_metric!(CONNECTOR_HTTP_STATUS_CODE_5XX_COUNT, GLOBAL_METER);
// Service Level
counter_metric!(CARD_LOCKER_FAILURES, GLOBAL_METER);
counter_metric!(CARD_LOCKER_SUCCESSFUL_RESPONSE, GLOBAL_METER);
counter_metric!(TEMP_LOCKER_FAILURES, GLOBAL_METER);
histogram_metric_f64!(CARD_ADD_TIME, GLOBAL_METER);
histogram_metric_f64!(CARD_GET_TIME, GLOBAL_METER);
histogram_metric_f64!(CARD_DELETE_TIME, GLOBAL_METER);
// Apple Pay Flow Metrics
counter_metric!(APPLE_PAY_MANUAL_FLOW, GLOBAL_METER);
counter_metric!(APPLE_PAY_SIMPLIFIED_FLOW, GLOBAL_METER);
counter_metric!(APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT, GLOBAL_METER);
counter_metric!(APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT, GLOBAL_METER);
counter_metric!(APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT, GLOBAL_METER);
counter_metric!(APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT, GLOBAL_METER);
// Metrics for Payment Auto Retries
counter_metric!(AUTO_RETRY_ELIGIBLE_REQUEST_COUNT, GLOBAL_METER);
counter_metric!(AUTO_RETRY_GSM_MISS_COUNT, GLOBAL_METER);
counter_metric!(AUTO_RETRY_GSM_FETCH_FAILURE_COUNT, GLOBAL_METER);
counter_metric!(AUTO_RETRY_GSM_MATCH_COUNT, GLOBAL_METER);
counter_metric!(AUTO_RETRY_EXHAUSTED_COUNT, GLOBAL_METER);
counter_metric!(AUTO_RETRY_PAYMENT_COUNT, GLOBAL_METER);
// Metrics for Payout Auto Retries
counter_metric!(AUTO_PAYOUT_RETRY_ELIGIBLE_REQUEST_COUNT, GLOBAL_METER);
counter_metric!(AUTO_PAYOUT_RETRY_GSM_MISS_COUNT, GLOBAL_METER);
counter_metric!(AUTO_PAYOUT_RETRY_GSM_FETCH_FAILURE_COUNT, GLOBAL_METER);
counter_metric!(AUTO_PAYOUT_RETRY_GSM_MATCH_COUNT, GLOBAL_METER);
counter_metric!(AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT, GLOBAL_METER);
counter_metric!(AUTO_RETRY_PAYOUT_COUNT, GLOBAL_METER);
// Scheduler / Process Tracker related metrics
counter_metric!(TASKS_ADDED_COUNT, GLOBAL_METER); // Tasks added to process tracker
counter_metric!(TASK_ADDITION_FAILURES_COUNT, GLOBAL_METER); // Failures in task addition to process tracker
counter_metric!(TASKS_RESET_COUNT, GLOBAL_METER); // Tasks reset in process tracker for requeue flow
// Access token metrics
//
// A counter to indicate the number of new access tokens created
counter_metric!(ACCESS_TOKEN_CREATION, GLOBAL_METER);
// A counter to indicate the access token cache hits
counter_metric!(ACCESS_TOKEN_CACHE_HIT, GLOBAL_METER);
// A counter to indicate the access token cache miss
counter_metric!(ACCESS_TOKEN_CACHE_MISS, GLOBAL_METER);
// A counter to indicate the integrity check failures
counter_metric!(INTEGRITY_CHECK_FAILED, GLOBAL_METER);
// Network Tokenization metrics
histogram_metric_f64!(GENERATE_NETWORK_TOKEN_TIME, GLOBAL_METER);
histogram_metric_f64!(FETCH_NETWORK_TOKEN_TIME, GLOBAL_METER);
histogram_metric_f64!(DELETE_NETWORK_TOKEN_TIME, GLOBAL_METER);
histogram_metric_f64!(CHECK_NETWORK_TOKEN_STATUS_TIME, GLOBAL_METER);
// A counter to indicate allowed payment method types mismatch
counter_metric!(PAYMENT_METHOD_TYPES_MISCONFIGURATION_METRIC, GLOBAL_METER);
// AI chat metric to track number of chat request
counter_metric!(CHAT_REQUEST_COUNT, GLOBAL_METER);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/recon.rs | crates/router/src/routes/recon.rs | use actix_web::{web, HttpRequest, HttpResponse};
use api_models::recon as recon_api;
use router_env::Flow;
use super::AppState;
use crate::{
core::{api_locking, recon},
services::{api, authentication, authorization::permissions::Permission},
};
pub async fn update_merchant(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<recon_api::ReconUpdateMerchantRequest>,
) -> HttpResponse {
let flow = Flow::ReconMerchantUpdate;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: authentication::AuthenticationData, req, _| {
recon::recon_merchant_account_update(state, auth.platform.get_processor().clone(), req)
},
&authentication::AdminApiAuthWithMerchantIdFromRoute(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn request_for_recon(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse {
let flow = Flow::ReconServiceRequest;
Box::pin(api::server_wrap(
flow,
state,
&http_req,
(),
|state, user, _, _| recon::send_recon_request(state, user),
&authentication::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_recon_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::ReconTokenRequest;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, user, _, _| recon::generate_recon_token(state, user),
&authentication::JWTAuth {
permission: Permission::MerchantReconTokenRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "recon")]
pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse {
let flow = Flow::ReconVerifyToken;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
(),
|state, user, _req, _| recon::verify_recon_token(state, user),
&authentication::JWTAuth {
permission: Permission::MerchantReconTokenRead,
},
api_locking::LockAction::NotApplicable,
))
.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/routes/locker_migration.rs | crates/router/src/routes/locker_migration.rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::Flow;
use super::AppState;
use crate::{
core::{api_locking, locker_migration},
services::{api, authentication as auth},
};
pub async fn rust_locker_migration(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::RustLockerMigration;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
&merchant_id,
|state, _, _, _| locker_migration::rust_locker_migration(state, &merchant_id),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.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/routes/cache.rs | crates/router/src/routes/cache.rs | use actix_web::{web, HttpRequest, Responder};
use router_env::{instrument, tracing, Flow};
use super::AppState;
use crate::{
core::{api_locking, cache},
services::{api, authentication as auth},
};
#[instrument(skip_all)]
pub async fn invalidate(
state: web::Data<AppState>,
req: HttpRequest,
key: web::Path<String>,
) -> impl Responder {
let flow = Flow::CacheInvalidate;
let key = key.into_inner().to_owned();
api::server_wrap(
flow,
state,
&req,
&key,
|state, _, key, _| cache::invalidate(state, key),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
)
.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/routes/configs.rs | crates/router/src/routes/configs.rs | use actix_web::{web, HttpRequest, Responder};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, configs},
services::{api, authentication as auth},
types::api as api_types,
};
#[cfg(feature = "v1")]
const ADMIN_API_AUTH: auth::AdminApiAuth = auth::AdminApiAuth;
#[cfg(feature = "v2")]
const ADMIN_API_AUTH: auth::V2AdminApiAuth = auth::V2AdminApiAuth;
#[instrument(skip_all, fields(flow = ?Flow::CreateConfigKey))]
pub async fn config_key_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_types::Config>,
) -> impl Responder {
let flow = Flow::CreateConfigKey;
let payload = json_payload.into_inner();
api::server_wrap(
flow,
state,
&req,
payload,
|state, _, data, _| configs::set_config(state, data),
&ADMIN_API_AUTH,
api_locking::LockAction::NotApplicable,
)
.await
}
#[instrument(skip_all, fields(flow = ?Flow::ConfigKeyFetch))]
pub async fn config_key_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> impl Responder {
let flow = Flow::ConfigKeyFetch;
let key = path.into_inner();
api::server_wrap(
flow,
state,
&req,
&key,
|state, _, key, _| configs::read_config(state, key),
&ADMIN_API_AUTH,
api_locking::LockAction::NotApplicable,
)
.await
}
#[instrument(skip_all, fields(flow = ?Flow::ConfigKeyUpdate))]
pub async fn config_key_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Json<api_types::ConfigUpdate>,
) -> impl Responder {
let flow = Flow::ConfigKeyUpdate;
let mut payload = json_payload.into_inner();
let key = path.into_inner();
payload.key = key;
api::server_wrap(
flow,
state,
&req,
&payload,
|state, _, payload, _| configs::update_config(state, payload),
&ADMIN_API_AUTH,
api_locking::LockAction::NotApplicable,
)
.await
}
#[instrument(skip_all, fields(flow = ?Flow::ConfigKeyDelete))]
pub async fn config_key_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> impl Responder {
let flow = Flow::ConfigKeyDelete;
let key = path.into_inner();
api::server_wrap(
flow,
state,
&req,
key,
|state, _, key, _| configs::config_delete(state, key),
&ADMIN_API_AUTH,
api_locking::LockAction::NotApplicable,
)
.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/routes/proxy.rs | crates/router/src/routes/proxy.rs | use actix_web::{web, Responder};
use router_env::{instrument, tracing, Flow};
use crate::{
self as app,
core::{api_locking, proxy},
services::{api, authentication as auth},
types::domain,
};
#[instrument(skip_all, fields(flow = ?Flow::Proxy))]
pub async fn proxy(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<api_models::proxy::ProxyRequest>,
) -> impl Responder {
let flow = Flow::Proxy;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
proxy::proxy_core(state, auth.platform, req)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.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/routes/dummy_connector.rs | crates/router/src/routes/dummy_connector.rs | use actix_web::web;
use router_env::{instrument, tracing};
use super::app;
use crate::{
core::api_locking,
services::{api, authentication as auth},
};
mod consts;
mod core;
mod errors;
pub mod types;
mod utils;
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))]
pub async fn dummy_connector_authorize_payment(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<String>,
) -> impl actix_web::Responder {
let flow = types::Flow::DummyPaymentAuthorize;
let attempt_id = path.into_inner();
let payload = types::DummyConnectorPaymentConfirmRequest { attempt_id };
api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| core::payment_authorize(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))]
pub async fn dummy_connector_complete_payment(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<String>,
json_payload: web::Query<types::DummyConnectorPaymentCompleteBody>,
) -> impl actix_web::Responder {
let flow = types::Flow::DummyPaymentComplete;
let attempt_id = path.into_inner();
let payload = types::DummyConnectorPaymentCompleteRequest {
attempt_id,
confirm: json_payload.confirm,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| core::payment_complete(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "dummy_connector")]
#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))]
pub async fn dummy_connector_payment(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<types::DummyConnectorPaymentRequest>,
) -> impl actix_web::Responder {
let payload = json_payload.into_inner();
let flow = types::Flow::DummyPaymentCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| core::payment(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "dummy_connector")]
#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentRetrieve))]
pub async fn dummy_connector_payment_data(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<String>,
) -> impl actix_web::Responder {
let flow = types::Flow::DummyPaymentRetrieve;
let payment_id = path.into_inner();
let payload = types::DummyConnectorPaymentRetrieveRequest { payment_id };
api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| core::payment_data(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?types::Flow::DummyRefundCreate))]
pub async fn dummy_connector_refund(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<types::DummyConnectorRefundRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl actix_web::Responder {
let flow = types::Flow::DummyRefundCreate;
let mut payload = json_payload.into_inner();
payload.payment_id = Some(path.into_inner());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| core::refund_payment(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?types::Flow::DummyRefundRetrieve))]
pub async fn dummy_connector_refund_data(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<String>,
) -> impl actix_web::Responder {
let flow = types::Flow::DummyRefundRetrieve;
let refund_id = path.into_inner();
let payload = types::DummyConnectorRefundRetrieveRequest { refund_id };
api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| core::refund_data(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
)
.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/routes/payments.rs | crates/router/src/routes/payments.rs | use crate::{
core::api_locking::{self, GetLockingInput},
services::authorization::permissions::Permission,
};
pub mod helpers;
use actix_web::{web, Responder};
use error_stack::report;
use hyperswitch_domain_models::payments::HeaderPayload;
use masking::PeekInterface;
use router_env::{env, instrument, logger, tracing, types, Flow};
use super::app::ReqState;
#[cfg(feature = "v2")]
use crate::core::payment_method_balance;
#[cfg(feature = "v2")]
use crate::core::revenue_recovery::api as recovery;
use crate::{
self as app,
core::{
errors::{self, http_not_implemented},
payments::{self, PaymentRedirectFlow},
},
routes::lock_utils,
services::{api, authentication as auth},
types::{
api::{
self as api_types, enums as api_enums,
payments::{self as payment_types, PaymentIdTypeExt},
},
domain,
transformers::ForeignTryFrom,
},
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate, payment_id))]
pub async fn payments_create(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
) -> impl Responder {
let flow = Flow::PaymentsCreate;
let mut payload = json_payload.into_inner();
if let Err(err) = payload
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
{
return api::log_and_return_error_response(err.into());
};
if let Err(err) = payload
.payment_link_config
.as_ref()
.map(|cfg| {
cfg.theme_config
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
})
.transpose()
{
return api::log_and_return_error_response(err.into());
};
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
return http_not_implemented();
};
if let Err(err) = get_or_generate_payment_id(&mut payload) {
return api::log_and_return_error_response(err);
}
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
tracing::Span::current().record(
"payment_id",
payload
.payment_id
.as_ref()
.map(|payment_id_type| payment_id_type.get_payment_intent_id())
.transpose()
.unwrap_or_default()
.as_ref()
.map(|id| id.get_string_repr())
.unwrap_or_default(),
);
let locking_action = payload.get_locking_input(flow.clone());
let auth_type = match env::which() {
env::Env::Production => {
&auth::InternalMerchantIdProfileIdAuth(auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}))
}
_ => auth::auth_type(
&auth::InternalMerchantIdProfileIdAuth(auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
})),
&auth::InternalMerchantIdProfileIdAuth(auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
}),
req.headers(),
),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
authorize_verify_select::<_>(
payments::PaymentCreate,
state,
req_state,
auth.platform,
auth.profile.map(|profile| profile.get_id().clone()),
header_payload.clone(),
req,
api::AuthFlow::Client,
)
},
auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v2")]
pub async fn recovery_payments_create(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::RecoveryPaymentsCreate>,
) -> impl Responder {
let flow = Flow::RecoveryPaymentsCreate;
let mut payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req.clone(),
payload,
|state, auth: auth::AuthenticationData, req_payload, req_state| {
recovery::custom_revenue_recovery_core(
state.to_owned(),
req_state,
auth.platform,
auth.profile,
req_payload,
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreateIntent, payment_id))]
pub async fn payments_create_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsCreateIntentRequest>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsCreateIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let global_payment_id =
common_utils::id_type::GlobalPaymentId::generate(&state.conf.cell_information.id);
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_intent_core::<
api_types::PaymentCreateIntent,
payment_types::PaymentsIntentResponse,
_,
_,
PaymentIntentData<api_types::PaymentCreateIntent>,
>(
state,
req_state,
auth.platform,
auth.profile,
payments::operations::PaymentIntentCreate,
req,
global_payment_id.clone(),
header_payload.clone(),
)
},
match env::which() {
env::Env::Production => &auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
_ => auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsGetIntent, payment_id))]
pub async fn payments_get_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use api_models::payments::PaymentsGetIntentRequest;
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsGetIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let payload = PaymentsGetIntentRequest {
id: path.into_inner(),
};
let global_payment_id = payload.id.clone();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_intent_core::<
api_types::PaymentGetIntent,
payment_types::PaymentsIntentResponse,
_,
_,
PaymentIntentData<api_types::PaymentGetIntent>,
>(
state,
req_state,
auth.platform,
auth.profile,
payments::operations::PaymentGetIntent,
req,
global_payment_id.clone(),
header_payload.clone(),
)
},
auth::api_or_client_or_jwt_auth(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
global_payment_id.clone(),
)),
&auth::JWTAuth {
permission: Permission::ProfileRevenueRecoveryRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsGetIntent, payment_id))]
pub async fn revenue_recovery_get_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use api_models::payments::PaymentsGetIntentRequest;
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsGetIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let payload = PaymentsGetIntentRequest {
id: path.into_inner(),
};
let global_payment_id = payload.id.clone();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::revenue_recovery_get_intent_core(
state,
req_state,
auth.platform,
auth.profile,
req,
global_payment_id.clone(),
header_payload.clone(),
)
},
auth::api_or_client_or_jwt_auth(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
global_payment_id.clone(),
)),
&auth::JWTAuth {
permission: Permission::ProfileRevenueRecoveryRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentAttemptsList, payment_id,))]
pub async fn list_payment_attempts(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
let flow = Flow::PaymentAttemptsList;
let payment_intent_id = path.into_inner();
let payload = api_models::payments::PaymentAttemptListRequest {
payment_intent_id: payment_intent_id.clone(),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.clone(),
|session_state, auth, req_payload, req_state| {
payments::payments_list_attempts_using_payment_intent_id::<
payments::operations::PaymentGetListAttempts,
api_models::payments::PaymentAttemptListResponse,
api_models::payments::PaymentAttemptListRequest,
payments::operations::payment_attempt_list::PaymentGetListAttempts,
hyperswitch_domain_models::payments::PaymentAttemptListData<
payments::operations::PaymentGetListAttempts,
>,
>(
session_state,
req_state,
auth.platform,
auth.profile,
payments::operations::PaymentGetListAttempts,
payload.clone(),
req_payload.payment_intent_id,
header_payload.clone(),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreateAndConfirmIntent, payment_id))]
pub async fn payments_create_and_confirm_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
) -> impl Responder {
let flow = Flow::PaymentsCreateAndConfirmIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let auth_type = if state.conf.merchant_id_auth.merchant_id_auth_enabled {
&auth::MerchantIdAuth
} else {
match env::which() {
env::Env::Production => &auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
_ => auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, request, req_state| {
payments::payments_create_and_confirm_intent(
state,
req_state,
auth.platform,
auth.profile,
request,
header_payload.clone(),
)
},
auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdateIntent, payment_id))]
pub async fn payments_update_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsUpdateIntentRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsUpdateIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: path.into_inner(),
payload: json_payload.into_inner(),
};
let global_payment_id = internal_payload.global_payment_id.clone();
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_intent_core::<
api_types::PaymentUpdateIntent,
payment_types::PaymentsIntentResponse,
_,
_,
PaymentIntentData<api_types::PaymentUpdateIntent>,
>(
state,
req_state,
auth.platform,
auth.profile,
payments::operations::PaymentUpdateIntent,
req.payload,
global_payment_id.clone(),
header_payload.clone(),
)
},
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip(state, req), fields(flow = ?Flow::PaymentsStart, payment_id))]
pub async fn payments_start(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
)>,
) -> impl Responder {
let flow = Flow::PaymentsStart;
let (payment_id, merchant_id, attempt_id) = path.into_inner();
let payload = payment_types::PaymentsStartRequest {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
attempt_id: attempt_id.clone(),
};
let locking_action = payload.get_locking_input(flow.clone());
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_core::<
api_types::Authorize,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
auth.platform,
auth.profile.map(|profile| profile.get_id().clone()),
payments::operations::PaymentStart,
req,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
None,
HeaderPayload::default(),
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payments_retrieve(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::PaymentId>,
json_payload: web::Query<payment_types::PaymentRetrieveBody>,
) -> impl Responder {
let flow = match json_payload.force_sync {
Some(true) => Flow::PaymentsRetrieveForceSync,
_ => Flow::PaymentsRetrieve,
};
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: json_payload.merchant_id.clone(),
force_sync: json_payload.force_sync.unwrap_or(false),
client_secret: json_payload.client_secret.clone(),
expand_attempts: json_payload.expand_attempts,
expand_captures: json_payload.expand_captures,
all_keys_required: json_payload.all_keys_required,
..Default::default()
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
tracing::Span::current().record("flow", flow.to_string());
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
};
let (auth_type, auth_flow) = match auth::check_internal_api_key_auth(
req.headers(),
&payload,
api_auth,
state.conf.internal_merchant_id_profile_id_auth.clone(),
) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_core::<
api_types::PSync,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
auth.platform,
auth.profile.map(|profile| profile.get_id().clone()),
payments::PaymentStatus,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
None,
header_payload.clone(),
)
},
auth::auth_type(
&*auth_type,
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payments_retrieve_with_gateway_creds(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentRetrieveBodyWithCredentials>,
) -> impl Responder {
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
};
let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
tracing::Span::current().record("payment_id", json_payload.payment_id.get_string_repr());
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: payment_types::PaymentIdType::PaymentIntentId(json_payload.payment_id.clone()),
merchant_id: json_payload.merchant_id.clone(),
force_sync: json_payload.force_sync.unwrap_or(false),
merchant_connector_details: json_payload.merchant_connector_details.clone(),
..Default::default()
};
let flow = match json_payload.force_sync {
Some(true) => Flow::PaymentsRetrieveForceSync,
_ => Flow::PaymentsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_core::<
api_types::PSync,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
auth.platform,
auth.profile.map(|profile| profile.get_id().clone()),
payments::PaymentStatus,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
None,
HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate, payment_id))]
pub async fn payments_update(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsUpdate;
let mut payload = json_payload.into_inner();
if let Err(err) = payload
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
{
return api::log_and_return_error_response(err.into());
};
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
return http_not_implemented();
};
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id));
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
};
let (auth_type, auth_flow) = match auth::check_internal_api_key_auth_no_client_secret(
req.headers(),
api_auth,
state.conf.internal_merchant_id_profile_id_auth.clone(),
) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
authorize_verify_select::<_>(
payments::PaymentUpdate,
state,
req_state,
auth.platform,
auth.profile.map(|profile| profile.get_id().clone()),
HeaderPayload::default(),
req,
auth_flow,
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsPostSessionTokens, payment_id))]
pub async fn payments_post_session_tokens(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsPostSessionTokensRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsPostSessionTokens;
let payment_id = path.into_inner();
let payload = payment_types::PaymentsPostSessionTokensRequest {
payment_id,
..json_payload.into_inner()
};
tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr());
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, req, req_state| {
payments::payments_core::<
api_types::PostSessionTokens,
payment_types::PaymentsPostSessionTokensResponse,
_,
_,
_,
payments::PaymentData<api_types::PostSessionTokens>,
>(
state,
req_state,
auth.platform,
auth.profile.map(|profile| profile.get_id().clone()),
payments::PaymentPostSessionTokens,
req,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
None,
header_payload.clone(),
)
},
&auth::PublishableKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdateMetadata, payment_id))]
pub async fn payments_update_metadata(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsUpdateMetadataRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsUpdateMetadata;
let payment_id = path.into_inner();
let payload = payment_types::PaymentsUpdateMetadataRequest {
payment_id,
..json_payload.into_inner()
};
tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr());
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, req, req_state| {
payments::payments_core::<
api_types::UpdateMetadata,
payment_types::PaymentsUpdateMetadataResponse,
_,
_,
_,
payments::PaymentData<api_types::UpdateMetadata>,
>(
state,
req_state,
auth.platform,
auth.profile.map(|profile| profile.get_id().clone()),
payments::PaymentUpdateMetadata,
req,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
None,
header_payload.clone(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm, payment_id))]
pub async fn payments_confirm(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsConfirm;
let mut payload = json_payload.into_inner();
if let Err(err) = payload
.validate()
.map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })
{
return api::log_and_return_error_response(err.into());
};
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
return http_not_implemented();
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
if let Err(err) = helpers::populate_browser_info(&req, &mut payload, &header_payload) {
return api::log_and_return_error_response(err);
}
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id));
payload.confirm = Some(true);
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
};
let (auth_type, auth_flow) = match auth::check_internal_api_key_auth(
req.headers(),
&payload,
api_auth,
state.conf.internal_merchant_id_profile_id_auth.clone(),
) {
Ok(auth) => auth,
Err(e) => return api::log_and_return_error_response(e),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
authorize_verify_select::<_>(
payments::PaymentConfirm,
state,
req_state,
auth.platform,
auth.profile.map(|profile| profile.get_id().clone()),
header_payload.clone(),
req,
auth_flow,
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCapture, payment_id))]
pub async fn payments_capture(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsCaptureRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let flow = Flow::PaymentsCapture;
let payload = payment_types::PaymentsCaptureRequest {
payment_id,
..json_payload.into_inner()
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/tokenization.rs | crates/router/src/routes/tokenization.rs | #[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use std::sync::Arc;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use actix_web::{web, HttpRequest, HttpResponse};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use common_utils::{
ext_traits::{BytesExt, Encode},
id_type,
};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use error_stack::ResultExt;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use masking::Secret;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use router_env::{instrument, logger, tracing, Flow};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use serde::Serialize;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use crate::{
core::{
api_locking,
errors::{self, RouterResult},
tokenization,
},
headers::X_CUSTOMER_ID,
routes::{app::StorageInterface, AppState, SessionState},
services::{self, api as api_service, authentication as auth},
types::{api, domain, payment_methods as pm_types},
};
#[instrument(skip_all, fields(flow = ?Flow::TokenizationCreate))]
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
pub async fn create_token_vault_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_models::tokenization::GenericTokenizationRequest>,
) -> HttpResponse {
let flow = Flow::TokenizationCreate;
let payload = json_payload.into_inner();
let customer_id = payload.customer_id.clone();
Box::pin(api_service::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| async move {
tokenization::create_vault_token_core(
state,
auth.platform.get_provider().clone(),
request,
)
.await
},
auth::api_or_client_auth(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Customer(
customer_id,
)),
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::TokenizationDelete))]
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
pub async fn delete_tokenized_data_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalTokenId>,
json_payload: web::Json<api_models::tokenization::DeleteTokenDataRequest>,
) -> HttpResponse {
let flow = Flow::TokenizationDelete;
let payload = json_payload.into_inner();
let session_id = payload.session_id.clone();
let token_id = path.into_inner();
Box::pin(api_service::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
tokenization::delete_tokenized_data_core(state, auth.platform, &token_id, req)
},
auth::api_or_client_auth(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::PaymentMethodSession(session_id),
),
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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/routes/payments/helpers.rs | crates/router/src/routes/payments/helpers.rs | use error_stack::ResultExt;
use crate::{
core::errors::{self, RouterResult},
logger,
types::{self, api},
utils::{Encode, ValueExt},
};
#[cfg(feature = "v1")]
pub fn populate_browser_info(
req: &actix_web::HttpRequest,
payload: &mut api::PaymentsRequest,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<()> {
let mut browser_info: types::BrowserInformation = payload
.browser_info
.clone()
.map(|v| v.parse_value("BrowserInformation"))
.transpose()
.change_context_lazy(|| errors::ApiErrorResponse::InvalidRequestData {
message: "invalid format for 'browser_info' provided".to_string(),
})?
.unwrap_or(types::BrowserInformation {
color_depth: None,
java_enabled: None,
java_script_enabled: None,
language: None,
screen_height: None,
screen_width: None,
time_zone: None,
accept_header: None,
user_agent: None,
ip_address: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
referer: None,
});
let ip_address = req
.connection_info()
.realip_remote_addr()
.map(ToOwned::to_owned);
if ip_address.is_some() {
logger::debug!("Extracted ip address from request");
}
browser_info.ip_address = browser_info.ip_address.or_else(|| {
ip_address
.as_ref()
.map(|ip| ip.parse())
.transpose()
.unwrap_or_else(|error| {
logger::error!(
?error,
"failed to parse ip address which is extracted from the request"
);
None
})
});
// If the locale is present in the header payload, we will use it as the accept language
if header_payload.locale.is_some() {
browser_info.accept_language = browser_info
.accept_language
.or(header_payload.locale.clone());
}
if let Some(api::MandateData {
customer_acceptance:
Some(api::CustomerAcceptance {
online:
Some(api::OnlineMandate {
ip_address: req_ip, ..
}),
..
}),
..
}) = &mut payload.mandate_data
{
*req_ip = req_ip
.clone()
.or_else(|| ip_address.map(|ip| masking::Secret::new(ip.to_string())));
}
let encoded = browser_info
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"failed to re-encode browser information to json after setting ip address",
)?;
payload.browser_info = Some(encoded);
Ok(())
}
#[cfg(feature = "v1")]
pub fn should_call_proxy_for_payments_core(payment_request: api::PaymentsRequest) -> bool {
payment_request
.recurring_details
.clone()
.map(|recurring_details| {
recurring_details
.clone()
.is_network_transaction_id_and_card_details_flow()
|| recurring_details
.clone()
.is_network_transaction_id_and_network_token_details_flow()
})
.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/routes/user/theme.rs | crates/router/src/routes/user/theme.rs | use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::user::theme as theme_api;
use common_utils::types::user::ThemeLineage;
use masking::Secret;
use router_env::Flow;
use crate::{
core::{api_locking, user::theme as theme_core},
routes::AppState,
services::{api, authentication as auth, authorization::permissions::Permission},
};
pub async fn get_theme_using_lineage(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<ThemeLineage>,
) -> HttpResponse {
let flow = Flow::GetThemeUsingLineage;
let lineage = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
lineage,
|state, _, lineage, _| theme_core::get_theme_using_lineage(state, lineage),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_theme_using_theme_id(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::GetThemeUsingThemeId;
let payload = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| theme_core::get_theme_using_theme_id(state, payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn upload_file_to_theme_storage(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
MultipartForm(payload): MultipartForm<theme_api::UploadFileAssetData>,
) -> HttpResponse {
let flow = Flow::UploadFileToThemeStorage;
let theme_id = path.into_inner();
let payload = theme_api::UploadFileRequest {
asset_name: payload.asset_name.into_inner(),
asset_data: Secret::new(payload.asset_data.data.to_vec()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| {
theme_core::upload_file_to_theme_storage(state, theme_id.clone(), payload)
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn create_theme(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<theme_api::CreateThemeRequest>,
) -> HttpResponse {
let flow = Flow::CreateTheme;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| theme_core::create_theme(state, payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn update_theme(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
payload: web::Json<theme_api::UpdateThemeRequest>,
) -> HttpResponse {
let flow = Flow::UpdateTheme;
let theme_id = path.into_inner();
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| theme_core::update_theme(state, theme_id.clone(), payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn delete_theme(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::DeleteTheme;
let theme_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
theme_id,
|state, _, theme_id, _| theme_core::delete_theme(state, theme_id),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn create_user_theme(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<theme_api::CreateUserThemeRequest>,
) -> HttpResponse {
let flow = Flow::CreateUserTheme;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, user: auth::UserFromToken, payload, _| {
theme_core::create_user_theme(state, user, payload)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_user_theme_using_theme_id(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::GetUserThemeUsingThemeId;
let payload = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, user: auth::UserFromToken, payload, _| {
theme_core::get_user_theme_using_theme_id(state, user, payload)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn update_user_theme(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
payload: web::Json<theme_api::UpdateThemeRequest>,
) -> HttpResponse {
let flow = Flow::UpdateUserTheme;
let theme_id = path.into_inner();
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, user: auth::UserFromToken, payload, _| {
theme_core::update_user_theme(state, theme_id.clone(), user, payload)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn delete_user_theme(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::DeleteUserTheme;
let theme_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
theme_id,
|state, user: auth::UserFromToken, theme_id, _| {
theme_core::delete_user_theme(state, user, theme_id)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn upload_file_to_user_theme_storage(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
MultipartForm(payload): MultipartForm<theme_api::UploadFileAssetData>,
) -> HttpResponse {
let flow = Flow::UploadFileToUserThemeStorage;
let theme_id = path.into_inner();
let payload = theme_api::UploadFileRequest {
asset_name: payload.asset_name.into_inner(),
asset_data: Secret::new(payload.asset_data.data.to_vec()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, user: auth::UserFromToken, payload, _| {
theme_core::upload_file_to_user_theme_storage(state, theme_id.clone(), user, payload)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn list_all_themes_in_lineage(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<theme_api::EntityTypeQueryParam>,
) -> HttpResponse {
let flow = Flow::ListAllThemesInLineage;
let entity_type = query.into_inner().entity_type;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, user: auth::UserFromToken, _payload, _| {
theme_core::list_all_themes_in_lineage(state, user, entity_type)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_user_theme_using_lineage(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<theme_api::EntityTypeQueryParam>,
) -> HttpResponse {
let flow = Flow::GetUserThemeUsingLineage;
let entity_type = query.into_inner().entity_type;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, user: auth::UserFromToken, _payload, _| {
theme_core::get_user_theme_using_lineage(state, user, entity_type)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeRead,
},
api_locking::LockAction::NotApplicable,
))
.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/routes/process_tracker/revenue_recovery.rs | crates/router/src/routes/process_tracker/revenue_recovery.rs | use actix_web::{web, HttpRequest, HttpResponse};
use api_models::process_tracker::revenue_recovery as revenue_recovery_api;
use router_env::Flow;
use crate::{
core::{api_locking, revenue_recovery},
routes::AppState,
services::{api, authentication as auth, authorization::permissions::Permission},
};
pub async fn revenue_recovery_pt_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> HttpResponse {
let flow = Flow::RevenueRecoveryRetrieve;
let id = path.into_inner();
let payload = revenue_recovery_api::RevenueRecoveryId {
revenue_recovery_id: id,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), id, _| {
revenue_recovery::retrieve_revenue_recovery_process_tracker(
state,
id.revenue_recovery_id,
)
},
&auth::JWTAuth {
permission: Permission::ProfileRevenueRecoveryRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn revenue_recovery_resume_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
json_payload: web::Json<revenue_recovery_api::RevenueRecoveryRetriggerRequest>,
) -> HttpResponse {
let flow = Flow::RevenueRecoveryResume;
let id = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| {
revenue_recovery::resume_revenue_recovery_process_tracker(state, id.clone(), payload)
},
&auth::V2AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.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/routes/metrics/bg_metrics_collector.rs | crates/router/src/routes/metrics/bg_metrics_collector.rs | use storage_impl::redis::cache;
const DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS: u16 = 15;
pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: Option<u16>) {
let metrics_collection_interval = metrics_collection_interval_in_secs
.unwrap_or(DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS);
let cache_instances = [
&cache::CONFIG_CACHE,
&cache::ACCOUNTS_CACHE,
&cache::ROUTING_CACHE,
&cache::CGRAPH_CACHE,
&cache::PM_FILTERS_CGRAPH_CACHE,
&cache::DECISION_MANAGER_CACHE,
&cache::SURCHARGE_CACHE,
&cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE,
&cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE,
&cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE,
];
tokio::spawn(async move {
loop {
for instance in cache_instances {
instance.record_entry_count_metric().await
}
tokio::time::sleep(std::time::Duration::from_secs(
metrics_collection_interval.into(),
))
.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/routes/metrics/request.rs | crates/router/src/routes/metrics/request.rs | use crate::services::ApplicationResponse;
pub fn track_response_status_code<Q>(response: &ApplicationResponse<Q>) -> i64 {
match response {
ApplicationResponse::Json(_)
| ApplicationResponse::StatusOk
| ApplicationResponse::TextPlain(_)
| ApplicationResponse::Form(_)
| ApplicationResponse::GenericLinkForm(_)
| ApplicationResponse::PaymentLinkForm(_)
| ApplicationResponse::FileData(_)
| ApplicationResponse::JsonWithHeaders(_) => 200,
ApplicationResponse::JsonForRedirection(_) => 302,
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/files/transformers.rs | crates/router/src/routes/files/transformers.rs | use actix_multipart::Multipart;
use actix_web::web::Bytes;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use futures::{StreamExt, TryStreamExt};
use crate::{
core::{errors, files::helpers},
types::api::files::{self, CreateFileRequest},
utils::OptionExt,
};
pub async fn get_create_file_request(
mut payload: Multipart,
) -> CustomResult<CreateFileRequest, errors::ApiErrorResponse> {
let mut option_purpose: Option<files::FilePurpose> = None;
let mut dispute_id: Option<String> = None;
let mut file_name: Option<String> = None;
let mut file_content: Option<Vec<Bytes>> = None;
while let Ok(Some(mut field)) = payload.try_next().await {
let content_disposition = field.content_disposition();
let field_name = content_disposition.get_name();
// Parse the different parameters expected in the multipart request
match field_name {
Some("purpose") => {
option_purpose = helpers::get_file_purpose(&mut field).await;
}
Some("file") => {
file_name = content_disposition.get_filename().map(String::from);
//Collect the file content and throw error if something fails
let mut file_data = Vec::new();
let mut stream = field.into_stream();
while let Some(chunk) = stream.next().await {
match chunk {
Ok(bytes) => file_data.push(bytes),
Err(err) => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!("{}{}", "File parsing error: ", err))?,
}
}
file_content = Some(file_data)
}
Some("dispute_id") => {
dispute_id = helpers::read_string(&mut field).await;
}
// Can ignore other params
_ => (),
}
}
let purpose = option_purpose.get_required_value("purpose")?;
let file = match file_content {
Some(valid_file_content) => valid_file_content.concat().to_vec(),
None => Err(errors::ApiErrorResponse::MissingFile)
.attach_printable("Missing / Invalid file in the request")?,
};
//Get and validate file size
let file_size = i32::try_from(file.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("File size error")?;
// Check if empty file and throw error
if file_size <= 0 {
Err(errors::ApiErrorResponse::MissingFile)
.attach_printable("Missing / Invalid file in the request")?
}
// Get file mime type using 'infer'
let kind = infer::get(&file).ok_or(errors::ApiErrorResponse::MissingFileContentType)?;
let file_type = kind
.mime_type()
.parse::<mime::Mime>()
.change_context(errors::ApiErrorResponse::MissingFileContentType)
.attach_printable("File content type error")?;
Ok(CreateFileRequest {
file,
file_name,
file_size,
file_type,
purpose,
dispute_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/routes/disputes/utils.rs | crates/router/src/routes/disputes/utils.rs | use actix_multipart::{Field, Multipart};
use actix_web::web::Bytes;
use common_utils::{errors::CustomResult, ext_traits::StringExt, fp_utils};
use error_stack::ResultExt;
use futures::{StreamExt, TryStreamExt};
use crate::{
core::{errors, files::helpers},
types::api::{disputes, files},
utils::OptionExt,
};
pub async fn parse_evidence_type(
field: &mut Field,
) -> CustomResult<Option<disputes::EvidenceType>, errors::ApiErrorResponse> {
let purpose = helpers::read_string(field).await;
match purpose {
Some(evidence_type) => Ok(Some(
evidence_type
.parse_enum("Evidence Type")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing evidence type")?,
)),
_ => Ok(None),
}
}
pub async fn get_attach_evidence_request(
mut payload: Multipart,
) -> CustomResult<disputes::AttachEvidenceRequest, errors::ApiErrorResponse> {
let mut option_evidence_type: Option<disputes::EvidenceType> = None;
let mut dispute_id: Option<String> = None;
let mut file_name: Option<String> = None;
let mut file_content: Option<Vec<Bytes>> = None;
while let Ok(Some(mut field)) = payload.try_next().await {
let content_disposition = field.content_disposition();
let field_name = content_disposition.get_name();
// Parse the different parameters expected in the multipart request
match field_name {
Some("file") => {
file_name = content_disposition.get_filename().map(String::from);
//Collect the file content and throw error if something fails
let mut file_data = Vec::new();
let mut stream = field.into_stream();
while let Some(chunk) = stream.next().await {
match chunk {
Ok(bytes) => file_data.push(bytes),
Err(err) => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("File parsing error: {err}"))?,
}
}
file_content = Some(file_data)
}
Some("dispute_id") => {
dispute_id = helpers::read_string(&mut field).await;
}
Some("evidence_type") => {
option_evidence_type = parse_evidence_type(&mut field).await?;
}
// Can ignore other params
_ => (),
}
}
let evidence_type = option_evidence_type.get_required_value("evidence_type")?;
let file = file_content.get_required_value("file")?.concat().to_vec();
//Get and validate file size
let file_size = i32::try_from(file.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("File size error")?;
// Check if empty file and throw error
fp_utils::when(file_size <= 0, || {
Err(errors::ApiErrorResponse::MissingFile)
.attach_printable("Missing / Invalid file in the request")
})?;
// Get file mime type using 'infer'
let kind = infer::get(&file).ok_or(errors::ApiErrorResponse::MissingFileContentType)?;
let file_type = kind
.mime_type()
.parse::<mime::Mime>()
.change_context(errors::ApiErrorResponse::MissingFileContentType)
.attach_printable("File content type error")?;
let create_file_request = files::CreateFileRequest {
file,
file_name,
file_size,
file_type,
purpose: files::FilePurpose::DisputeEvidence,
dispute_id,
};
Ok(disputes::AttachEvidenceRequest {
evidence_type,
create_file_request,
})
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/dummy_connector/errors.rs | crates/router/src/routes/dummy_connector/errors.rs | #[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorType {
ServerNotAvailable,
ObjectNotFound,
InvalidRequestError,
}
#[derive(Debug, Clone, router_derive::ApiError)]
#[error(error_type_enum = ErrorType)]
// TODO: Remove this line if InternalServerError is used anywhere
#[allow(dead_code)]
pub enum DummyConnectorErrors {
#[error(error_type = ErrorType::ServerNotAvailable, code = "DC_00", message = "Something went wrong")]
InternalServerError,
#[error(error_type = ErrorType::ObjectNotFound, code = "DC_01", message = "Payment does not exist in our records")]
PaymentNotFound,
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_02", message = "Missing required param: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_03", message = "The refund amount exceeds the amount captured")]
RefundAmountExceedsPaymentAmount,
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_04", message = "Card not supported. Please use test cards")]
CardNotSupported,
#[error(error_type = ErrorType::ObjectNotFound, code = "DC_05", message = "Refund does not exist in our records")]
RefundNotFound,
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_06", message = "Payment is not successful")]
PaymentNotSuccessful,
#[error(error_type = ErrorType::ServerNotAvailable, code = "DC_07", message = "Error occurred while storing the payment")]
PaymentStoringError,
#[error(error_type = ErrorType::InvalidRequestError, code = "DC_08", message = "Payment declined: {message}")]
PaymentDeclined { message: &'static str },
}
impl core::fmt::Display for DummyConnectorErrors {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
r#"{{"error":{}}}"#,
serde_json::to_string(self)
.unwrap_or_else(|_| "Dummy connector error response".to_string())
)
}
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse>
for DummyConnectorErrors
{
fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
match self {
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("DC", 0, self.error_message(), None))
}
Self::PaymentNotFound => {
AER::NotFound(ApiError::new("DC", 1, self.error_message(), None))
}
Self::MissingRequiredField { field_name: _ } => {
AER::BadRequest(ApiError::new("DC", 2, self.error_message(), None))
}
Self::RefundAmountExceedsPaymentAmount => {
AER::InternalServerError(ApiError::new("DC", 3, self.error_message(), None))
}
Self::CardNotSupported => {
AER::BadRequest(ApiError::new("DC", 4, self.error_message(), None))
}
Self::RefundNotFound => {
AER::NotFound(ApiError::new("DC", 5, self.error_message(), None))
}
Self::PaymentNotSuccessful => {
AER::BadRequest(ApiError::new("DC", 6, self.error_message(), None))
}
Self::PaymentStoringError => {
AER::InternalServerError(ApiError::new("DC", 7, self.error_message(), None))
}
Self::PaymentDeclined { message: _ } => {
AER::BadRequest(ApiError::new("DC", 8, self.error_message(), None))
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/dummy_connector/consts.rs | crates/router/src/routes/dummy_connector/consts.rs | pub const ATTEMPT_ID_PREFIX: &str = "dummy_attempt";
pub const REFUND_ID_PREFIX: &str = "dummy_ref";
pub const THREE_DS_CSS: &str = include_str!("threeds_page.css");
pub const DUMMY_CONNECTOR_UPI_FAILURE_VPA_ID: &str = "failure@upi";
pub const DUMMY_CONNECTOR_UPI_SUCCESS_VPA_ID: &str = "success@upi";
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/dummy_connector/core.rs | crates/router/src/routes/dummy_connector/core.rs | use app::SessionState;
use common_utils::generate_id_with_default_len;
use error_stack::ResultExt;
use super::{errors, types, utils};
use crate::{
routes::{app, dummy_connector::consts},
services::api,
utils::OptionExt,
};
#[cfg(feature = "dummy_connector")]
pub async fn payment(
state: SessionState,
req: types::DummyConnectorPaymentRequest,
) -> types::DummyConnectorResponse<types::DummyConnectorPaymentResponse> {
utils::tokio_mock_sleep(
state.conf.dummy_connector.payment_duration,
state.conf.dummy_connector.payment_tolerance,
)
.await;
let payment_attempt: types::DummyConnectorPaymentAttempt = req.into();
let payment_data =
types::DummyConnectorPaymentData::process_payment_attempt(&state, payment_attempt)?;
utils::store_data_in_redis(
&state,
payment_data.attempt_id.clone(),
payment_data.payment_id.clone(),
state.conf.dummy_connector.authorize_ttl,
)
.await?;
utils::store_data_in_redis(
&state,
payment_data.payment_id.get_string_repr().to_owned(),
payment_data.clone(),
state.conf.dummy_connector.payment_ttl,
)
.await?;
Ok(api::ApplicationResponse::Json(payment_data.into()))
}
pub async fn payment_data(
state: SessionState,
req: types::DummyConnectorPaymentRetrieveRequest,
) -> types::DummyConnectorResponse<types::DummyConnectorPaymentResponse> {
utils::tokio_mock_sleep(
state.conf.dummy_connector.payment_retrieve_duration,
state.conf.dummy_connector.payment_retrieve_tolerance,
)
.await;
let payment_data = utils::get_payment_data_from_payment_id(&state, req.payment_id).await?;
Ok(api::ApplicationResponse::Json(payment_data.into()))
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
pub async fn payment_authorize(
state: SessionState,
req: types::DummyConnectorPaymentConfirmRequest,
) -> types::DummyConnectorResponse<String> {
let payment_data = utils::get_payment_data_by_attempt_id(&state, req.attempt_id.clone()).await;
let dummy_connector_conf = &state.conf.dummy_connector;
if let Ok(payment_data_inner) = payment_data {
let return_url = format!(
"{}/dummy-connector/complete/{}",
state.base_url, req.attempt_id
);
Ok(api::ApplicationResponse::FileData((
utils::get_authorize_page(payment_data_inner, return_url, dummy_connector_conf)
.as_bytes()
.to_vec(),
mime::TEXT_HTML,
)))
} else {
Ok(api::ApplicationResponse::FileData((
utils::get_expired_page(dummy_connector_conf)
.as_bytes()
.to_vec(),
mime::TEXT_HTML,
)))
}
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
pub async fn payment_complete(
state: SessionState,
req: types::DummyConnectorPaymentCompleteRequest,
) -> types::DummyConnectorResponse<()> {
utils::tokio_mock_sleep(
state.conf.dummy_connector.payment_duration,
state.conf.dummy_connector.payment_tolerance,
)
.await;
let payment_data = utils::get_payment_data_by_attempt_id(&state, req.attempt_id.clone()).await;
let payment_status = if req.confirm {
types::DummyConnectorStatus::Succeeded
} else {
types::DummyConnectorStatus::Failed
};
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::DummyConnectorErrors::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let _ = redis_conn.delete_key(&req.attempt_id.as_str().into()).await;
if let Ok(payment_data) = payment_data {
let updated_payment_data = types::DummyConnectorPaymentData {
status: payment_status,
next_action: None,
..payment_data
};
utils::store_data_in_redis(
&state,
updated_payment_data.payment_id.get_string_repr().to_owned(),
updated_payment_data.clone(),
state.conf.dummy_connector.payment_ttl,
)
.await?;
return Ok(api::ApplicationResponse::JsonForRedirection(
api_models::payments::RedirectionResponse {
return_url: String::new(),
params: vec![],
return_url_with_query_params: updated_payment_data
.return_url
.unwrap_or(state.conf.dummy_connector.default_return_url.clone()),
http_method: "GET".to_string(),
headers: vec![],
},
));
}
Ok(api::ApplicationResponse::JsonForRedirection(
api_models::payments::RedirectionResponse {
return_url: String::new(),
params: vec![],
return_url_with_query_params: state.conf.dummy_connector.default_return_url.clone(),
http_method: "GET".to_string(),
headers: vec![],
},
))
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
pub async fn refund_payment(
state: SessionState,
req: types::DummyConnectorRefundRequest,
) -> types::DummyConnectorResponse<types::DummyConnectorRefundResponse> {
utils::tokio_mock_sleep(
state.conf.dummy_connector.refund_duration,
state.conf.dummy_connector.refund_tolerance,
)
.await;
let payment_id = req
.payment_id
.get_required_value("payment_id")
.change_context(errors::DummyConnectorErrors::MissingRequiredField {
field_name: "payment_id",
})?;
let mut payment_data =
utils::get_payment_data_from_payment_id(&state, payment_id.get_string_repr().to_owned())
.await?;
payment_data.is_eligible_for_refund(req.amount)?;
let refund_id = generate_id_with_default_len(consts::REFUND_ID_PREFIX);
payment_data.eligible_amount -= req.amount;
utils::store_data_in_redis(
&state,
payment_id.get_string_repr().to_owned(),
payment_data.to_owned(),
state.conf.dummy_connector.payment_ttl,
)
.await?;
let refund_data = types::DummyConnectorRefundResponse::new(
types::DummyConnectorStatus::Succeeded,
refund_id.to_owned(),
payment_data.currency,
common_utils::date_time::now(),
payment_data.amount,
req.amount,
);
utils::store_data_in_redis(
&state,
refund_id,
refund_data.to_owned(),
state.conf.dummy_connector.refund_ttl,
)
.await?;
Ok(api::ApplicationResponse::Json(refund_data))
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
pub async fn refund_data(
state: SessionState,
req: types::DummyConnectorRefundRetrieveRequest,
) -> types::DummyConnectorResponse<types::DummyConnectorRefundResponse> {
let refund_id = req.refund_id;
utils::tokio_mock_sleep(
state.conf.dummy_connector.refund_retrieve_duration,
state.conf.dummy_connector.refund_retrieve_tolerance,
)
.await;
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::DummyConnectorErrors::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let refund_data = redis_conn
.get_and_deserialize_key::<types::DummyConnectorRefundResponse>(
&refund_id.as_str().into(),
"DummyConnectorRefundResponse",
)
.await
.change_context(errors::DummyConnectorErrors::RefundNotFound)?;
Ok(api::ApplicationResponse::Json(refund_data))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/dummy_connector/types.rs | crates/router/src/routes/dummy_connector/types.rs | use api_models::enums::Currency;
use common_utils::{errors::CustomResult, generate_id_with_default_len, pii};
use error_stack::report;
use masking::Secret;
use router_env::types::FlowMetric;
use strum::Display;
use time::PrimitiveDateTime;
use super::{consts, errors::DummyConnectorErrors};
use crate::services;
#[derive(Debug, Display, Clone, PartialEq, Eq)]
#[allow(clippy::enum_variant_names)]
pub enum Flow {
DummyPaymentCreate,
DummyPaymentRetrieve,
DummyPaymentAuthorize,
DummyPaymentComplete,
DummyRefundCreate,
DummyRefundRetrieve,
}
impl FlowMetric for Flow {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, strum::Display, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DummyConnectors {
#[serde(rename = "phonypay")]
#[strum(serialize = "phonypay")]
PhonyPay,
#[serde(rename = "fauxpay")]
#[strum(serialize = "fauxpay")]
FauxPay,
#[serde(rename = "pretendpay")]
#[strum(serialize = "pretendpay")]
PretendPay,
StripeTest,
AdyenTest,
CheckoutTest,
PaypalTest,
}
impl DummyConnectors {
pub fn get_connector_image_link(self, base_url: &str) -> String {
let image_name = match self {
Self::PhonyPay => "PHONYPAY.svg",
Self::FauxPay => "FAUXPAY.svg",
Self::PretendPay => "PRETENDPAY.svg",
Self::StripeTest => "STRIPE_TEST.svg",
Self::PaypalTest => "PAYPAL_TEST.svg",
_ => "PHONYPAY.svg",
};
format!("{base_url}{image_name}")
}
}
#[derive(
Default, serde::Serialize, serde::Deserialize, strum::Display, Clone, PartialEq, Debug, Eq,
)]
#[serde(rename_all = "lowercase")]
pub enum DummyConnectorStatus {
Succeeded,
#[default]
Processing,
Failed,
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct DummyConnectorPaymentAttempt {
pub timestamp: PrimitiveDateTime,
pub attempt_id: String,
pub payment_id: common_utils::id_type::PaymentId,
pub payment_request: DummyConnectorPaymentRequest,
}
impl From<DummyConnectorPaymentRequest> for DummyConnectorPaymentAttempt {
fn from(payment_request: DummyConnectorPaymentRequest) -> Self {
let timestamp = common_utils::date_time::now();
let payment_id = common_utils::id_type::PaymentId::default();
let attempt_id = generate_id_with_default_len(consts::ATTEMPT_ID_PREFIX);
Self {
timestamp,
attempt_id,
payment_id,
payment_request,
}
}
}
impl DummyConnectorPaymentAttempt {
pub fn build_payment_data(
self,
status: DummyConnectorStatus,
next_action: Option<DummyConnectorNextAction>,
return_url: Option<String>,
) -> DummyConnectorPaymentData {
DummyConnectorPaymentData {
attempt_id: self.attempt_id,
payment_id: self.payment_id,
status,
amount: self.payment_request.amount,
eligible_amount: self.payment_request.amount,
connector: self.payment_request.connector,
created: self.timestamp,
currency: self.payment_request.currency,
payment_method_type: self.payment_request.payment_method_data.into(),
next_action,
return_url,
}
}
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct DummyConnectorPaymentRequest {
pub amount: i64,
pub currency: Currency,
pub payment_method_data: DummyConnectorPaymentMethodData,
pub return_url: Option<String>,
pub connector: DummyConnectors,
}
pub trait GetPaymentMethodDetails {
fn get_name(&self) -> &'static str;
fn get_image_link(&self, base_url: &str) -> String;
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DummyConnectorPaymentMethodData {
Card(DummyConnectorCard),
Upi(DummyConnectorUpi),
Wallet(DummyConnectorWallet),
PayLater(DummyConnectorPayLater),
}
#[derive(
Default, serde::Serialize, serde::Deserialize, strum::Display, PartialEq, Debug, Clone,
)]
#[serde(rename_all = "lowercase")]
pub enum DummyConnectorPaymentMethodType {
#[default]
Card,
Upi(DummyConnectorUpiType),
Wallet(DummyConnectorWallet),
PayLater(DummyConnectorPayLater),
}
impl From<DummyConnectorPaymentMethodData> for DummyConnectorPaymentMethodType {
fn from(value: DummyConnectorPaymentMethodData) -> Self {
match value {
DummyConnectorPaymentMethodData::Card(_) => Self::Card,
DummyConnectorPaymentMethodData::Upi(upi_data) => match upi_data {
DummyConnectorUpi::UpiCollect(_) => Self::Upi(DummyConnectorUpiType::UpiCollect),
},
DummyConnectorPaymentMethodData::Wallet(wallet) => Self::Wallet(wallet),
DummyConnectorPaymentMethodData::PayLater(pay_later) => Self::PayLater(pay_later),
}
}
}
impl GetPaymentMethodDetails for DummyConnectorPaymentMethodType {
fn get_name(&self) -> &'static str {
match self {
Self::Card => "3D Secure",
Self::Upi(upi_type) => upi_type.get_name(),
Self::Wallet(wallet) => wallet.get_name(),
Self::PayLater(pay_later) => pay_later.get_name(),
}
}
fn get_image_link(&self, base_url: &str) -> String {
match self {
Self::Card => format!("{}{}", base_url, "CARD.svg"),
Self::Upi(upi_type) => upi_type.get_image_link(base_url),
Self::Wallet(wallet) => wallet.get_image_link(base_url),
Self::PayLater(pay_later) => pay_later.get_image_link(base_url),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorCard {
pub name: Secret<String>,
pub number: cards::CardNumber,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvc: Secret<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorUpiCollect {
pub vpa_id: Secret<String, pii::UpiVpaMaskingStrategy>,
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DummyConnectorUpi {
UpiCollect(DummyConnectorUpiCollect),
}
pub enum DummyConnectorCardFlow {
NoThreeDS(DummyConnectorStatus, Option<DummyConnectorErrors>),
ThreeDS(DummyConnectorStatus, Option<DummyConnectorErrors>),
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub enum DummyConnectorWallet {
GooglePay,
Paypal,
WeChatPay,
MbWay,
AliPay,
AliPayHK,
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub enum DummyConnectorUpiType {
UpiCollect,
}
impl GetPaymentMethodDetails for DummyConnectorUpiType {
fn get_name(&self) -> &'static str {
match self {
Self::UpiCollect => "UPI Collect",
}
}
fn get_image_link(&self, base_url: &str) -> String {
let image_name = match self {
Self::UpiCollect => "UPI_COLLECT.svg",
};
format!("{base_url}{image_name}")
}
}
impl GetPaymentMethodDetails for DummyConnectorWallet {
fn get_name(&self) -> &'static str {
match self {
Self::GooglePay => "Google Pay",
Self::Paypal => "PayPal",
Self::WeChatPay => "WeChat Pay",
Self::MbWay => "Mb Way",
Self::AliPay => "Alipay",
Self::AliPayHK => "Alipay HK",
}
}
fn get_image_link(&self, base_url: &str) -> String {
let image_name = match self {
Self::GooglePay => "GOOGLE_PAY.svg",
Self::Paypal => "PAYPAL.svg",
Self::WeChatPay => "WECHAT_PAY.svg",
Self::MbWay => "MBWAY.svg",
Self::AliPay => "ALIPAY.svg",
Self::AliPayHK => "ALIPAY.svg",
};
format!("{base_url}{image_name}")
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
pub enum DummyConnectorPayLater {
Klarna,
Affirm,
AfterPayClearPay,
}
impl GetPaymentMethodDetails for DummyConnectorPayLater {
fn get_name(&self) -> &'static str {
match self {
Self::Klarna => "Klarna",
Self::Affirm => "Affirm",
Self::AfterPayClearPay => "Afterpay Clearpay",
}
}
fn get_image_link(&self, base_url: &str) -> String {
let image_name = match self {
Self::Klarna => "KLARNA.svg",
Self::Affirm => "AFFIRM.svg",
Self::AfterPayClearPay => "AFTERPAY.svg",
};
format!("{base_url}{image_name}")
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
pub struct DummyConnectorPaymentData {
pub attempt_id: String,
pub payment_id: common_utils::id_type::PaymentId,
pub status: DummyConnectorStatus,
pub amount: i64,
pub eligible_amount: i64,
pub currency: Currency,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created: PrimitiveDateTime,
pub payment_method_type: DummyConnectorPaymentMethodType,
pub connector: DummyConnectors,
pub next_action: Option<DummyConnectorNextAction>,
pub return_url: Option<String>,
}
impl DummyConnectorPaymentData {
pub fn is_eligible_for_refund(&self, refund_amount: i64) -> DummyConnectorResult<()> {
if self.eligible_amount < refund_amount {
return Err(
report!(DummyConnectorErrors::RefundAmountExceedsPaymentAmount)
.attach_printable("Eligible amount is lesser than refund amount"),
);
}
if self.status != DummyConnectorStatus::Succeeded {
return Err(report!(DummyConnectorErrors::PaymentNotSuccessful)
.attach_printable("Payment is not successful to process the refund"));
}
Ok(())
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum DummyConnectorNextAction {
RedirectToUrl(String),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorPaymentResponse {
pub status: DummyConnectorStatus,
pub id: common_utils::id_type::PaymentId,
pub amount: i64,
pub currency: Currency,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created: PrimitiveDateTime,
pub payment_method_type: DummyConnectorPaymentMethodType,
pub next_action: Option<DummyConnectorNextAction>,
}
impl From<DummyConnectorPaymentData> for DummyConnectorPaymentResponse {
fn from(value: DummyConnectorPaymentData) -> Self {
Self {
status: value.status,
id: value.payment_id,
amount: value.amount,
currency: value.currency,
created: value.created,
payment_method_type: value.payment_method_type,
next_action: value.next_action,
}
}
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorPaymentRetrieveRequest {
pub payment_id: String,
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorPaymentConfirmRequest {
pub attempt_id: String,
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorPaymentCompleteRequest {
pub attempt_id: String,
pub confirm: bool,
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorPaymentCompleteBody {
pub confirm: bool,
}
#[derive(Default, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct DummyConnectorRefundRequest {
pub amount: i64,
pub payment_id: Option<common_utils::id_type::PaymentId>,
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct DummyConnectorRefundResponse {
pub status: DummyConnectorStatus,
pub id: String,
pub currency: Currency,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created: PrimitiveDateTime,
pub payment_amount: i64,
pub refund_amount: i64,
}
impl DummyConnectorRefundResponse {
pub fn new(
status: DummyConnectorStatus,
id: String,
currency: Currency,
created: PrimitiveDateTime,
payment_amount: i64,
refund_amount: i64,
) -> Self {
Self {
status,
id,
currency,
created,
payment_amount,
refund_amount,
}
}
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DummyConnectorRefundRetrieveRequest {
pub refund_id: String,
}
pub type DummyConnectorResponse<T> =
CustomResult<services::ApplicationResponse<T>, DummyConnectorErrors>;
pub type DummyConnectorResult<T> = CustomResult<T, DummyConnectorErrors>;
pub struct DummyConnectorUpiFlow {
pub status: DummyConnectorStatus,
pub error: Option<DummyConnectorErrors>,
pub is_next_action_required: bool,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes/dummy_connector/utils.rs | crates/router/src/routes/dummy_connector/utils.rs | use std::fmt::Debug;
use common_utils::ext_traits::AsyncExt;
use error_stack::{report, ResultExt};
use masking::PeekInterface;
use maud::html;
use rand::{distributions::Uniform, prelude::Distribution};
use tokio::time as tokio;
use super::{
consts, errors,
types::{self, GetPaymentMethodDetails},
};
use crate::{
configs::settings,
routes::{dummy_connector::types::DummyConnectors, SessionState},
};
pub async fn tokio_mock_sleep(delay: u64, tolerance: u64) {
let mut rng = rand::thread_rng();
// TODO: change this to `Uniform::try_from`
// this would require changing the fn signature
// to return a Result
let effective_delay = Uniform::from((delay - tolerance)..(delay + tolerance));
tokio::sleep(tokio::Duration::from_millis(
effective_delay.sample(&mut rng),
))
.await
}
pub async fn store_data_in_redis(
state: &SessionState,
key: String,
data: impl serde::Serialize + Debug,
ttl: i64,
) -> types::DummyConnectorResult<()> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::DummyConnectorErrors::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.serialize_and_set_key_with_expiry(&key.into(), data, ttl)
.await
.change_context(errors::DummyConnectorErrors::PaymentStoringError)
.attach_printable("Failed to add data in redis")?;
Ok(())
}
pub async fn get_payment_data_from_payment_id(
state: &SessionState,
payment_id: String,
) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::DummyConnectorErrors::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.get_and_deserialize_key::<types::DummyConnectorPaymentData>(
&payment_id.as_str().into(),
"types DummyConnectorPaymentData",
)
.await
.change_context(errors::DummyConnectorErrors::PaymentNotFound)
}
pub async fn get_payment_data_by_attempt_id(
state: &SessionState,
attempt_id: String,
) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::DummyConnectorErrors::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.get_and_deserialize_key::<String>(&attempt_id.as_str().into(), "String")
.await
.async_and_then(|payment_id| async move {
redis_conn
.get_and_deserialize_key::<types::DummyConnectorPaymentData>(
&payment_id.as_str().into(),
"DummyConnectorPaymentData",
)
.await
})
.await
.change_context(errors::DummyConnectorErrors::PaymentNotFound)
}
pub fn get_authorize_page(
payment_data: types::DummyConnectorPaymentData,
return_url: String,
dummy_connector_conf: &settings::DummyConnector,
) -> String {
let mode = payment_data.payment_method_type.get_name();
let image = payment_data
.payment_method_type
.get_image_link(dummy_connector_conf.assets_base_url.as_str());
let connector_image = payment_data
.connector
.get_connector_image_link(dummy_connector_conf.assets_base_url.as_str());
let currency = payment_data.currency.to_string();
html! {
head {
title { "Authorize Payment" }
style { (consts::THREE_DS_CSS) }
link rel="icon" href=(connector_image) {}
}
body {
div.heading {
img.logo src="https://app.hyperswitch.io/assets/Dark/hyperswitchLogoIconWithText.svg" alt="Hyperswitch Logo" {}
h1 { "Test Payment Page" }
}
div.container {
div.payment_details {
img src=(image) {}
div.border_horizontal {}
img src=(connector_image) {}
}
(maud::PreEscaped(
format!(r#"
<p class="disclaimer">
This is a test payment of <span id="amount"></span> {} using {}
<script>
document.getElementById("amount").innerHTML = ({} / 100).toFixed(2);
</script>
</p>
"#, currency, mode, payment_data.amount)
)
)
p { b { "Real money will not be debited for the payment." } " \
You can choose to simulate successful or failed payment while testing this payment." }
div.user_action {
button.authorize onclick=(format!("window.location.href='{}?confirm=true'", return_url))
{ "Complete Payment" }
button.reject onclick=(format!("window.location.href='{}?confirm=false'", return_url))
{ "Reject Payment" }
}
}
div.container {
p.disclaimer { "What is this page?" }
p { "This page is just a simulation for integration and testing purpose. \
In live mode, this page will not be displayed and the user will be taken to \
the Bank page (or) Google Pay cards popup (or) original payment method's page. \
Contact us for any queries."
}
div.contact {
div.contact_item.hover_cursor onclick=(dummy_connector_conf.slack_invite_url) {
img src="https://hyperswitch.io/logos/logo_slack.svg" alt="Slack Logo" {}
}
div.contact_item.hover_cursor onclick=(dummy_connector_conf.discord_invite_url) {
img src="https://hyperswitch.io/logos/logo_discord.svg" alt="Discord Logo" {}
}
div.border_vertical {}
div.contact_item.email {
p { "Or email us at" }
a href="mailto:hyperswitch@juspay.in" { "hyperswitch@juspay.in" }
}
}
}
}
}
.into_string()
}
pub fn get_expired_page(dummy_connector_conf: &settings::DummyConnector) -> String {
html! {
head {
title { "Authorize Payment" }
style { (consts::THREE_DS_CSS) }
link rel="icon" href="https://app.hyperswitch.io/HyperswitchFavicon.png" {}
}
body {
div.heading {
img.logo src="https://app.hyperswitch.io/assets/Dark/hyperswitchLogoIconWithText.svg" alt="Hyperswitch Logo" {}
h1 { "Test Payment Page" }
}
div.container {
p.disclaimer { "This link is not valid or it is expired" }
}
div.container {
p.disclaimer { "What is this page?" }
p { "This page is just a simulation for integration and testing purpose.\
In live mode, this is not visible. Contact us for any queries."
}
div.contact {
div.contact_item.hover_cursor onclick=(dummy_connector_conf.slack_invite_url) {
img src="https://hyperswitch.io/logos/logo_slack.svg" alt="Slack Logo" {}
}
div.contact_item.hover_cursor onclick=(dummy_connector_conf.discord_invite_url) {
img src="https://hyperswitch.io/logos/logo_discord.svg" alt="Discord Logo" {}
}
div.border_vertical {}
div.contact_item.email {
p { "Or email us at" }
a href="mailto:hyperswitch@juspay.in" { "hyperswitch@juspay.in" }
}
}
}
}
}
.into_string()
}
pub trait ProcessPaymentAttempt {
fn build_payment_data_from_payment_attempt(
self,
payment_attempt: types::DummyConnectorPaymentAttempt,
redirect_url: String,
) -> types::DummyConnectorResult<types::DummyConnectorPaymentData>;
}
impl ProcessPaymentAttempt for types::DummyConnectorCard {
fn build_payment_data_from_payment_attempt(
self,
payment_attempt: types::DummyConnectorPaymentAttempt,
redirect_url: String,
) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> {
match self.get_flow_from_card_number(payment_attempt.payment_request.connector.clone())? {
types::DummyConnectorCardFlow::NoThreeDS(status, error) => {
if let Some(error) = error {
Err(error)?;
}
Ok(payment_attempt.build_payment_data(status, None, None))
}
types::DummyConnectorCardFlow::ThreeDS(_, _) => {
Ok(payment_attempt.clone().build_payment_data(
types::DummyConnectorStatus::Processing,
Some(types::DummyConnectorNextAction::RedirectToUrl(redirect_url)),
payment_attempt.payment_request.return_url,
))
}
}
}
}
impl ProcessPaymentAttempt for types::DummyConnectorUpiCollect {
fn build_payment_data_from_payment_attempt(
self,
payment_attempt: types::DummyConnectorPaymentAttempt,
redirect_url: String,
) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> {
let upi_collect_response = self.get_flow_from_upi_collect()?;
if let Some(error) = upi_collect_response.error {
Err(error)?;
}
let next_action = upi_collect_response
.is_next_action_required
.then_some(types::DummyConnectorNextAction::RedirectToUrl(redirect_url));
let return_url = payment_attempt.payment_request.return_url.clone();
Ok(
payment_attempt.build_payment_data(
upi_collect_response.status,
next_action,
return_url,
),
)
}
}
impl types::DummyConnectorUpiCollect {
pub fn get_flow_from_upi_collect(
self,
) -> types::DummyConnectorResult<types::DummyConnectorUpiFlow> {
let vpa_id = self.vpa_id.peek();
match vpa_id.as_str() {
consts::DUMMY_CONNECTOR_UPI_FAILURE_VPA_ID => Ok(types::DummyConnectorUpiFlow {
status: types::DummyConnectorStatus::Failed,
error: errors::DummyConnectorErrors::PaymentNotSuccessful.into(),
is_next_action_required: false,
}),
consts::DUMMY_CONNECTOR_UPI_SUCCESS_VPA_ID => Ok(types::DummyConnectorUpiFlow {
status: types::DummyConnectorStatus::Processing,
error: None,
is_next_action_required: true,
}),
_ => Ok(types::DummyConnectorUpiFlow {
status: types::DummyConnectorStatus::Failed,
error: Some(errors::DummyConnectorErrors::PaymentDeclined {
message: "Invalid Upi id",
}),
is_next_action_required: false,
}),
}
}
}
impl types::DummyConnectorCard {
pub fn get_flow_from_card_number(
self,
connector: DummyConnectors,
) -> types::DummyConnectorResult<types::DummyConnectorCardFlow> {
let card_number = self.number.peek();
match card_number.as_str() {
"4111111111111111" | "4242424242424242" | "5555555555554444" | "38000000000006"
| "378282246310005" | "6011111111111117" => {
Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Succeeded,
None,
))
}
"5105105105105100" | "4000000000000002" => {
Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Failed,
Some(errors::DummyConnectorErrors::PaymentDeclined {
message: "Card declined",
}),
))
}
"4000000000009995" => {
if connector == DummyConnectors::StripeTest {
Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Succeeded,
None,
))
} else {
Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Failed,
Some(errors::DummyConnectorErrors::PaymentDeclined {
message: "Internal Server Error from Connector, Please try again later",
}),
))
}
}
"4000000000009987" => Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Failed,
Some(errors::DummyConnectorErrors::PaymentDeclined {
message: "Lost card",
}),
)),
"4000000000009979" => Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Failed,
Some(errors::DummyConnectorErrors::PaymentDeclined {
message: "Stolen card",
}),
)),
"4000003800000446" => Ok(types::DummyConnectorCardFlow::ThreeDS(
types::DummyConnectorStatus::Succeeded,
None,
)),
_ => Err(report!(errors::DummyConnectorErrors::CardNotSupported)
.attach_printable("The card is not supported")),
}
}
}
impl ProcessPaymentAttempt for types::DummyConnectorWallet {
fn build_payment_data_from_payment_attempt(
self,
payment_attempt: types::DummyConnectorPaymentAttempt,
redirect_url: String,
) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> {
Ok(payment_attempt.clone().build_payment_data(
types::DummyConnectorStatus::Processing,
Some(types::DummyConnectorNextAction::RedirectToUrl(redirect_url)),
payment_attempt.payment_request.return_url,
))
}
}
impl ProcessPaymentAttempt for types::DummyConnectorPayLater {
fn build_payment_data_from_payment_attempt(
self,
payment_attempt: types::DummyConnectorPaymentAttempt,
redirect_url: String,
) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> {
Ok(payment_attempt.clone().build_payment_data(
types::DummyConnectorStatus::Processing,
Some(types::DummyConnectorNextAction::RedirectToUrl(redirect_url)),
payment_attempt.payment_request.return_url,
))
}
}
impl ProcessPaymentAttempt for types::DummyConnectorPaymentMethodData {
fn build_payment_data_from_payment_attempt(
self,
payment_attempt: types::DummyConnectorPaymentAttempt,
redirect_url: String,
) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> {
match self {
Self::Card(card) => {
card.build_payment_data_from_payment_attempt(payment_attempt, redirect_url)
}
Self::Upi(upi_data) => match upi_data {
types::DummyConnectorUpi::UpiCollect(upi_collect) => upi_collect
.build_payment_data_from_payment_attempt(payment_attempt, redirect_url),
},
Self::Wallet(wallet) => {
wallet.build_payment_data_from_payment_attempt(payment_attempt, redirect_url)
}
Self::PayLater(pay_later) => {
pay_later.build_payment_data_from_payment_attempt(payment_attempt, redirect_url)
}
}
}
}
impl types::DummyConnectorPaymentData {
pub fn process_payment_attempt(
state: &SessionState,
payment_attempt: types::DummyConnectorPaymentAttempt,
) -> types::DummyConnectorResult<Self> {
let redirect_url = format!(
"{}/dummy-connector/authorize/{}",
state.base_url, payment_attempt.attempt_id
);
payment_attempt
.clone()
.payment_request
.payment_method_data
.build_payment_data_from_payment_attempt(payment_attempt, redirect_url)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/utils/user.rs | crates/router/src/utils/user.rs | use std::sync::Arc;
#[cfg(feature = "v1")]
use api_models::admin as admin_api;
use api_models::user as user_api;
#[cfg(feature = "v1")]
use common_enums::connector_enums;
use common_enums::UserAuthType;
#[cfg(feature = "v1")]
use common_utils::ext_traits::ValueExt;
use common_utils::{
encryption::Encryption,
errors::CustomResult,
id_type, type_name,
types::{keymanager::Identifier, user::LineageContext},
};
use diesel_models::organization::{self, OrganizationBridge};
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount as DomainMerchantConnectorAccount;
#[cfg(feature = "v1")]
use masking::PeekInterface;
use masking::{ExposeInterface, Secret};
use redis_interface::RedisConnectionPool;
use router_env::{env, logger};
#[cfg(feature = "v1")]
use crate::types::AdditionalMerchantData;
use crate::{
consts::user::{REDIS_SSO_PREFIX, REDIS_SSO_TTL},
core::errors::{StorageError, UserErrors, UserResult},
routes::SessionState,
services::{
authentication::{AuthToken, UserFromToken},
authorization::roles::RoleInfo,
},
types::{
domain::{self, MerchantAccount, UserFromStorage},
transformers::ForeignFrom,
},
};
pub mod dashboard_metadata;
pub mod password;
#[cfg(feature = "dummy_connector")]
pub mod sample_data;
pub mod theme;
pub mod two_factor_auth;
impl UserFromToken {
pub async fn get_merchant_account_from_db(
&self,
state: SessionState,
) -> UserResult<MerchantAccount> {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&self.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(UserErrors::MerchantIdNotFound)
} else {
e.change_context(UserErrors::InternalServerError)
}
})?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(&self.merchant_id, &key_store)
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(UserErrors::MerchantIdNotFound)
} else {
e.change_context(UserErrors::InternalServerError)
}
})?;
Ok(merchant_account)
}
pub async fn get_user_from_db(&self, state: &SessionState) -> UserResult<UserFromStorage> {
let user = state
.global_store
.find_user_by_id(&self.user_id)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(user.into())
}
pub async fn get_role_info_from_db(&self, state: &SessionState) -> UserResult<RoleInfo> {
RoleInfo::from_role_id_org_id_tenant_id(
state,
&self.role_id,
&self.org_id,
self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)
}
}
pub async fn generate_jwt_auth_token_with_attributes(
state: &SessionState,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
role_id: String,
profile_id: id_type::ProfileId,
tenant_id: Option<id_type::TenantId>,
) -> UserResult<Secret<String>> {
let token = AuthToken::new_token(
user_id,
merchant_id,
role_id,
&state.conf,
org_id,
profile_id,
tenant_id,
)
.await?;
Ok(Secret::new(token))
}
#[allow(unused_variables)]
pub fn get_verification_days_left(
state: &SessionState,
user: &UserFromStorage,
) -> UserResult<Option<i64>> {
#[cfg(feature = "email")]
return user.get_verification_days_left(state);
#[cfg(not(feature = "email"))]
return Ok(None);
}
pub async fn get_user_from_db_by_email(
state: &SessionState,
email: domain::UserEmail,
) -> CustomResult<UserFromStorage, StorageError> {
state
.global_store
.find_user_by_email(&email)
.await
.map(UserFromStorage::from)
}
pub fn get_redis_connection_for_global_tenant(
state: &SessionState,
) -> UserResult<Arc<RedisConnectionPool>> {
state
.global_store
.get_redis_conn()
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get redis connection")
}
impl ForeignFrom<&user_api::AuthConfig> for UserAuthType {
fn foreign_from(from: &user_api::AuthConfig) -> Self {
match *from {
user_api::AuthConfig::OpenIdConnect { .. } => Self::OpenIdConnect,
user_api::AuthConfig::Password => Self::Password,
user_api::AuthConfig::MagicLink => Self::MagicLink,
}
}
}
pub async fn construct_public_and_private_db_configs(
state: &SessionState,
auth_config: &user_api::AuthConfig,
encryption_key: &[u8],
id: String,
) -> UserResult<(Option<Encryption>, Option<serde_json::Value>)> {
match auth_config {
user_api::AuthConfig::OpenIdConnect {
private_config,
public_config,
} => {
let private_config_value = serde_json::to_value(private_config.clone())
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to convert auth config to json")?;
let encrypted_config =
domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
type_name!(diesel_models::user::User),
domain::types::CryptoOperation::Encrypt(private_config_value.into()),
Identifier::UserAuth(id),
encryption_key,
)
.await
.and_then(|val| val.try_into_operation())
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to encrypt auth config")?;
Ok((
Some(encrypted_config.into()),
Some(
serde_json::to_value(public_config.clone())
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to convert auth config to json")?,
),
))
}
user_api::AuthConfig::Password | user_api::AuthConfig::MagicLink => Ok((None, None)),
}
}
pub fn parse_value<T>(value: serde_json::Value, type_name: &str) -> UserResult<T>
where
T: serde::de::DeserializeOwned,
{
serde_json::from_value::<T>(value)
.change_context(UserErrors::InternalServerError)
.attach_printable(format!("Unable to parse {type_name}"))
}
pub async fn decrypt_oidc_private_config(
state: &SessionState,
encrypted_config: Option<Encryption>,
id: String,
) -> UserResult<user_api::OpenIdConnectPrivateConfig> {
let user_auth_key = hex::decode(
state
.conf
.user_auth_methods
.get_inner()
.encryption_key
.clone()
.expose(),
)
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to decode DEK")?;
let private_config = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
type_name!(diesel_models::user::User),
domain::types::CryptoOperation::DecryptOptional(encrypted_config),
Identifier::UserAuth(id),
&user_auth_key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to decrypt private config")?
.ok_or(UserErrors::InternalServerError)
.attach_printable("Private config not found")?
.into_inner()
.expose();
serde_json::from_value::<user_api::OpenIdConnectPrivateConfig>(private_config)
.change_context(UserErrors::InternalServerError)
.attach_printable("unable to parse OpenIdConnectPrivateConfig")
}
pub async fn set_sso_id_in_redis(
state: &SessionState,
oidc_state: Secret<String>,
sso_id: String,
) -> UserResult<()> {
let connection = get_redis_connection_for_global_tenant(state)?;
let key = get_oidc_key(&oidc_state.expose());
connection
.set_key_with_expiry(&key.into(), sso_id, REDIS_SSO_TTL)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to set sso id in redis")
}
pub async fn get_sso_id_from_redis(
state: &SessionState,
oidc_state: Secret<String>,
) -> UserResult<String> {
let connection = get_redis_connection_for_global_tenant(state)?;
let key = get_oidc_key(&oidc_state.expose());
connection
.get_key::<Option<String>>(&key.into())
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get sso id from redis")?
.ok_or(UserErrors::SSOFailed)
.attach_printable("Cannot find oidc state in redis. Oidc state invalid or expired")
}
fn get_oidc_key(oidc_state: &str) -> String {
format!("{REDIS_SSO_PREFIX}{oidc_state}")
}
pub fn get_oidc_sso_redirect_url(state: &SessionState, provider: &str) -> String {
format!("{}/redirect/oidc/{}", state.conf.user.base_url, provider)
}
pub fn is_sso_auth_type(auth_type: UserAuthType) -> bool {
match auth_type {
UserAuthType::OpenIdConnect => true,
UserAuthType::Password | UserAuthType::MagicLink => false,
}
}
#[cfg(feature = "v1")]
pub fn create_merchant_account_request_for_org(
req: user_api::UserOrgMerchantCreateRequest,
org: organization::Organization,
product_type: common_enums::MerchantProductType,
) -> UserResult<api_models::admin::MerchantAccountCreate> {
let merchant_id = generate_env_specific_merchant_id(req.merchant_name.clone().expose())?;
let company_name = domain::UserCompanyName::new(req.merchant_name.expose())?;
Ok(api_models::admin::MerchantAccountCreate {
merchant_id,
metadata: None,
locker_id: None,
return_url: None,
merchant_name: Some(Secret::new(company_name.get_secret())),
webhook_details: None,
publishable_key: None,
organization_id: Some(org.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: Some(product_type),
merchant_account_type: None,
})
}
pub async fn validate_email_domain_auth_type_using_db(
state: &SessionState,
email: &domain::UserEmail,
required_auth_type: UserAuthType,
) -> UserResult<()> {
let domain = email.extract_domain()?;
let user_auth_methods = state
.store
.list_user_authentication_methods_for_email_domain(domain)
.await
.change_context(UserErrors::InternalServerError)?;
(user_auth_methods.is_empty()
|| user_auth_methods
.iter()
.any(|auth_method| auth_method.auth_type == required_auth_type))
.then_some(())
.ok_or(UserErrors::InvalidUserAuthMethodOperation.into())
}
pub fn spawn_async_lineage_context_update_to_db(
state: &SessionState,
user_id: &str,
lineage_context: LineageContext,
) {
let state = state.clone();
let lineage_context = lineage_context.clone();
let user_id = user_id.to_owned();
tokio::spawn(async move {
match state
.global_store
.update_user_by_user_id(
&user_id,
diesel_models::user::UserUpdate::LineageContextUpdate { lineage_context },
)
.await
{
Ok(_) => {
logger::debug!("Successfully updated lineage context for user {}", user_id);
}
Err(e) => {
logger::error!(
"Failed to update lineage context for user {}: {:?}",
user_id,
e
);
}
}
});
}
pub fn generate_env_specific_merchant_id(value: String) -> UserResult<id_type::MerchantId> {
if matches!(env::which(), env::Env::Production) {
let raw_id = domain::MerchantId::new(value)?;
Ok(id_type::MerchantId::try_from(raw_id)?)
} else {
Ok(id_type::MerchantId::new_from_unix_timestamp())
}
}
pub fn get_base_url(state: &SessionState) -> &str {
if !state.conf.multitenancy.enabled {
&state.conf.user.base_url
} else {
&state.tenant.user.control_center_url
}
}
#[cfg(feature = "v1")]
pub async fn build_cloned_connector_create_request(
source_mca: DomainMerchantConnectorAccount,
destination_profile_id: Option<id_type::ProfileId>,
destination_connector_label: Option<String>,
) -> UserResult<admin_api::MerchantConnectorCreate> {
let source_mca_name = source_mca
.connector_name
.parse::<connector_enums::Connector>()
.change_context(UserErrors::InternalServerError)
.attach_printable("Invalid connector name received")?;
let payment_methods_enabled = source_mca
.payment_methods_enabled
.clone()
.map(|data| {
let val = data.into_iter().map(|secret| secret.expose()).collect();
serde_json::Value::Array(val)
.parse_value("PaymentMethods")
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to deserialize PaymentMethods")
})
.transpose()?;
let frm_configs = source_mca
.frm_configs
.as_ref()
.map(|configs_vec| {
configs_vec
.iter()
.map(|config_secret| {
config_secret
.peek()
.clone()
.parse_value("FrmConfigs")
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to deserialize FrmConfigs")
})
.collect::<Result<Vec<_>, _>>()
})
.transpose()?;
let connector_webhook_details = source_mca
.connector_webhook_details
.map(|webhook_details| {
serde_json::Value::parse_value(
webhook_details.expose(),
"MerchantConnectorWebhookDetails",
)
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to deserialize connector_webhook_details")
})
.transpose()?;
let connector_wallets_details = source_mca
.connector_wallets_details
.map(|secret_value| {
secret_value
.into_inner()
.expose()
.parse_value::<admin_api::ConnectorWalletDetails>("ConnectorWalletDetails")
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to parse ConnectorWalletDetails from Value")
})
.transpose()?;
let additional_merchant_data = source_mca
.additional_merchant_data
.map(|secret_value| {
secret_value
.into_inner()
.expose()
.parse_value::<AdditionalMerchantData>("AdditionalMerchantData")
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to parse AdditionalMerchantData from Value")
})
.transpose()?
.map(admin_api::AdditionalMerchantData::foreign_from);
Ok(admin_api::MerchantConnectorCreate {
connector_type: source_mca.connector_type,
connector_name: source_mca_name,
connector_label: destination_connector_label.or(source_mca.connector_label.clone()),
merchant_connector_id: None,
connector_account_details: Some(source_mca.connector_account_details.clone().into_inner()),
test_mode: source_mca.test_mode,
disabled: source_mca.disabled,
payment_methods_enabled,
metadata: source_mca.metadata,
business_country: source_mca.business_country,
business_label: source_mca.business_label.clone(),
business_sub_label: source_mca.business_sub_label.clone(),
frm_configs,
connector_webhook_details,
profile_id: destination_profile_id,
pm_auth_config: source_mca.pm_auth_config.clone(),
connector_wallets_details,
status: Some(source_mca.status),
additional_merchant_data,
})
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/utils/connector_onboarding.rs | crates/router/src/utils/connector_onboarding.rs | use diesel_models::{ConfigNew, ConfigUpdate};
use error_stack::ResultExt;
use super::errors::StorageErrorExt;
use crate::{
consts,
core::errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
routes::{app::settings, SessionState},
types::{self, api::enums},
};
pub mod paypal;
pub fn get_connector_auth(
connector: enums::Connector,
connector_data: &settings::ConnectorOnboarding,
) -> RouterResult<types::ConnectorAuthType> {
match connector {
enums::Connector::Paypal => Ok(types::ConnectorAuthType::BodyKey {
api_key: connector_data.paypal.client_secret.clone(),
key1: connector_data.paypal.client_id.clone(),
}),
_ => Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason(format!(
"Onboarding is not implemented for {connector}",
)),
}
.into()),
}
}
pub fn is_enabled(
connector: types::Connector,
conf: &settings::ConnectorOnboarding,
) -> Option<bool> {
match connector {
enums::Connector::Paypal => Some(conf.paypal.enabled),
_ => None,
}
}
pub async fn check_if_connector_exists(
state: &SessionState,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<()> {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?;
#[cfg(feature = "v1")]
let _connector = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
merchant_id,
connector_id,
&key_store,
)
.await
.to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_string(),
})?;
#[cfg(feature = "v2")]
{
let _ = connector_id;
let _ = key_store;
todo!()
};
Ok(())
}
pub async fn set_tracking_id_in_configs(
state: &SessionState,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
connector: enums::Connector,
) -> RouterResult<()> {
let timestamp = common_utils::date_time::now_unix_timestamp().to_string();
let find_config = state
.store
.find_config_by_key(&build_key(connector_id, connector))
.await;
if find_config.is_ok() {
state
.store
.update_config_by_key(
&build_key(connector_id, connector),
ConfigUpdate::Update {
config: Some(timestamp),
},
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Error updating data in configs table")?;
} else if find_config
.as_ref()
.map_err(|e| e.current_context().is_db_not_found())
.err()
.unwrap_or(false)
{
state
.store
.insert_config(ConfigNew {
key: build_key(connector_id, connector),
config: timestamp,
})
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting data in configs table")?;
} else {
find_config.change_context(ApiErrorResponse::InternalServerError)?;
}
Ok(())
}
pub async fn get_tracking_id_from_configs(
state: &SessionState,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
connector: enums::Connector,
) -> RouterResult<String> {
let timestamp = state
.store
.find_config_by_key_unwrap_or(
&build_key(connector_id, connector),
Some(common_utils::date_time::now_unix_timestamp().to_string()),
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Error getting data from configs table")?
.config;
Ok(format!("{}_{}", connector_id.get_string_repr(), timestamp))
}
fn build_key(
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
connector: enums::Connector,
) -> String {
format!(
"{}_{}_{}",
consts::CONNECTOR_ONBOARDING_CONFIG_PREFIX,
connector,
connector_id.get_string_repr(),
)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/utils/ext_traits.rs | crates/router/src/utils/ext_traits.rs | pub use hyperswitch_domain_models::ext_traits::OptionExt;
use crate::core::errors::{self, CustomResult};
pub trait ValidateCall<T, F> {
fn validate_opt(self, func: F) -> CustomResult<(), errors::ValidationError>;
}
impl<T, F> ValidateCall<T, F> for Option<&T>
where
F: Fn(&T) -> CustomResult<(), errors::ValidationError>,
{
fn validate_opt(self, func: F) -> CustomResult<(), errors::ValidationError> {
match self {
Some(val) => func(val),
None => 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/utils/storage_partitioning.rs | crates/router/src/utils/storage_partitioning.rs | pub use storage_impl::redis::kv_store::{KvStorePartition, PartitionKey};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/utils/user_role.rs | crates/router/src/utils/user_role.rs | use std::{
cmp,
collections::{HashMap, HashSet},
};
use api_models::user_role::role as role_api;
use common_enums::{EntityType, ParentGroup, PermissionGroup};
use common_utils::id_type;
use diesel_models::{
enums::UserRoleVersion,
role::ListRolesByEntityPayload,
user_role::{UserRole, UserRoleUpdate},
};
use error_stack::{report, Report, ResultExt};
use router_env::logger;
use storage_impl::errors::StorageError;
use strum::IntoEnumIterator;
use crate::{
consts,
core::errors::{UserErrors, UserResult},
db::{
errors::StorageErrorExt,
user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload},
},
routes::SessionState,
services::authorization::{
self as authz,
permission_groups::{ParentGroupExt, PermissionGroupExt},
permissions, roles,
},
types::domain,
};
pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> {
if groups.is_empty() {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("Role groups cannot be empty");
}
let unique_groups: HashSet<_> = groups.iter().copied().collect();
if unique_groups.contains(&PermissionGroup::InternalManage) {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("Invalid groups present in the custom role");
}
if unique_groups.len() != groups.len() {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("Duplicate permission group found");
}
Ok(())
}
pub async fn validate_role_name(
state: &SessionState,
role_name: &domain::RoleName,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
profile_id: &id_type::ProfileId,
entity_type: &EntityType,
) -> UserResult<()> {
let role_name_str = role_name.clone().get_role_name();
let is_present_in_predefined_roles = roles::predefined_roles::PREDEFINED_ROLES
.iter()
.any(|(_, role_info)| role_info.get_role_name() == role_name_str);
let entity_type_for_role = match entity_type {
EntityType::Tenant | EntityType::Organization => ListRolesByEntityPayload::Organization,
EntityType::Merchant => ListRolesByEntityPayload::Merchant(merchant_id.to_owned()),
EntityType::Profile => {
ListRolesByEntityPayload::Profile(merchant_id.to_owned(), profile_id.to_owned())
}
};
let is_present_in_custom_role = match state
.global_store
.generic_list_roles_by_entity_type(
entity_type_for_role,
false,
tenant_id.to_owned(),
org_id.to_owned(),
)
.await
{
Ok(roles_list) => roles_list
.iter()
.any(|role| role.role_name == role_name_str),
Err(e) => {
if e.current_context().is_db_not_found() {
false
} else {
return Err(UserErrors::InternalServerError.into());
}
}
};
if is_present_in_predefined_roles || is_present_in_custom_role {
return Err(UserErrors::RoleNameAlreadyExists.into());
}
Ok(())
}
pub async fn set_role_info_in_cache_by_user_role(
state: &SessionState,
user_role: &UserRole,
) -> bool {
let Some(ref org_id) = user_role.org_id else {
return false;
};
set_role_info_in_cache_if_required(
state,
user_role.role_id.as_str(),
org_id,
&user_role.tenant_id,
)
.await
.map_err(|e| logger::error!("Error setting permissions in cache {:?}", e))
.is_ok()
}
pub async fn set_role_info_in_cache_by_role_id_org_id(
state: &SessionState,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> bool {
set_role_info_in_cache_if_required(state, role_id, org_id, tenant_id)
.await
.map_err(|e| logger::error!("Error setting permissions in cache {:?}", e))
.is_ok()
}
pub async fn set_role_info_in_cache_if_required(
state: &SessionState,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> UserResult<()> {
if roles::predefined_roles::PREDEFINED_ROLES.contains_key(role_id) {
return Ok(());
}
let role_info =
roles::RoleInfo::from_role_id_org_id_tenant_id(state, role_id, org_id, tenant_id)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error getting role_info from role_id")?;
authz::set_role_info_in_cache(
state,
role_id,
&role_info,
i64::try_from(consts::JWT_TOKEN_TIME_IN_SECS)
.change_context(UserErrors::InternalServerError)?,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error setting permissions in redis")
}
pub async fn update_v1_and_v2_user_roles_in_db(
state: &SessionState,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
profile_id: Option<&id_type::ProfileId>,
update: UserRoleUpdate,
) -> (
Result<UserRole, Report<StorageError>>,
Result<UserRole, Report<StorageError>>,
) {
let updated_v1_role = state
.global_store
.update_user_role_by_user_id_and_lineage(
user_id,
tenant_id,
org_id,
merchant_id,
profile_id,
update.clone(),
UserRoleVersion::V1,
)
.await
.map_err(|e| {
logger::error!("Error updating user_role {e:?}");
e
});
let updated_v2_role = state
.global_store
.update_user_role_by_user_id_and_lineage(
user_id,
tenant_id,
org_id,
merchant_id,
profile_id,
update,
UserRoleVersion::V2,
)
.await
.map_err(|e| {
logger::error!("Error updating user_role {e:?}");
e
});
(updated_v1_role, updated_v2_role)
}
pub async fn get_single_org_id(
state: &SessionState,
user_role: &UserRole,
) -> UserResult<id_type::OrganizationId> {
let (_, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
match entity_type {
EntityType::Tenant => Ok(state
.store
.list_merchant_and_org_ids(1, None)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get merchants list for org")?
.pop()
.ok_or(UserErrors::InternalServerError)
.attach_printable("No merchants to get merchant or org id")?
.1),
EntityType::Organization | EntityType::Merchant | EntityType::Profile => user_role
.org_id
.clone()
.ok_or(UserErrors::InternalServerError)
.attach_printable("Org_id not found"),
}
}
pub async fn get_single_merchant_id(
state: &SessionState,
user_role: &UserRole,
org_id: &id_type::OrganizationId,
) -> UserResult<id_type::MerchantId> {
let (_, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
match entity_type {
EntityType::Tenant | EntityType::Organization => Ok(state
.store
.list_merchant_accounts_by_organization_id(org_id)
.await
.to_not_found_response(UserErrors::InvalidRoleOperationWithMessage(
"Invalid Org Id".to_string(),
))?
.first()
.ok_or(UserErrors::InternalServerError)
.attach_printable("No merchants found for org_id")?
.get_id()
.clone()),
EntityType::Merchant | EntityType::Profile => user_role
.merchant_id
.clone()
.ok_or(UserErrors::InternalServerError)
.attach_printable("merchant_id not found"),
}
}
pub async fn get_single_profile_id(
state: &SessionState,
user_role: &UserRole,
merchant_id: &id_type::MerchantId,
) -> UserResult<id_type::ProfileId> {
let (_, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
match entity_type {
EntityType::Tenant | EntityType::Organization | EntityType::Merchant => {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(state
.store
.list_profile_by_merchant_id(&key_store, merchant_id)
.await
.change_context(UserErrors::InternalServerError)?
.pop()
.ok_or(UserErrors::InternalServerError)?
.get_id()
.to_owned())
}
EntityType::Profile => user_role
.profile_id
.clone()
.ok_or(UserErrors::InternalServerError)
.attach_printable("profile_id not found"),
}
}
pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite(
state: &SessionState,
user_id: &str,
tenant_id: &id_type::TenantId,
entity_id: String,
entity_type: EntityType,
) -> UserResult<
Option<(
id_type::OrganizationId,
Option<id_type::MerchantId>,
Option<id_type::ProfileId>,
)>,
> {
match entity_type {
EntityType::Tenant => Err(UserErrors::InvalidRoleOperationWithMessage(
"Tenant roles are not allowed for this operation".to_string(),
)
.into()),
EntityType::Organization => {
let Ok(org_id) =
id_type::OrganizationId::try_from(std::borrow::Cow::from(entity_id.clone()))
else {
return Ok(None);
};
let user_roles = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id,
tenant_id,
org_id: Some(&org_id),
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: None,
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.collect::<HashSet<_>>();
if user_roles.len() > 1 {
return Ok(None);
}
if let Some(user_role) = user_roles.into_iter().next() {
let (_entity_id, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
if entity_type != EntityType::Organization {
return Ok(None);
}
return Ok(Some((
user_role.org_id.ok_or(UserErrors::InternalServerError)?,
None,
None,
)));
}
Ok(None)
}
EntityType::Merchant => {
let Ok(merchant_id) = id_type::MerchantId::wrap(entity_id) else {
return Ok(None);
};
let user_roles = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id,
tenant_id,
org_id: None,
merchant_id: Some(&merchant_id),
profile_id: None,
entity_id: None,
version: None,
status: None,
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.collect::<HashSet<_>>();
if user_roles.len() > 1 {
return Ok(None);
}
if let Some(user_role) = user_roles.into_iter().next() {
let (_entity_id, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
if entity_type != EntityType::Merchant {
return Ok(None);
}
return Ok(Some((
user_role.org_id.ok_or(UserErrors::InternalServerError)?,
Some(merchant_id),
None,
)));
}
Ok(None)
}
EntityType::Profile => {
let Ok(profile_id) = id_type::ProfileId::try_from(std::borrow::Cow::from(entity_id))
else {
return Ok(None);
};
let user_roles = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id,
tenant_id: &state.tenant.tenant_id,
org_id: None,
merchant_id: None,
profile_id: Some(&profile_id),
entity_id: None,
version: None,
status: None,
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.collect::<HashSet<_>>();
if user_roles.len() > 1 {
return Ok(None);
}
if let Some(user_role) = user_roles.into_iter().next() {
let (_entity_id, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
if entity_type != EntityType::Profile {
return Ok(None);
}
return Ok(Some((
user_role.org_id.ok_or(UserErrors::InternalServerError)?,
Some(
user_role
.merchant_id
.ok_or(UserErrors::InternalServerError)?,
),
Some(profile_id),
)));
}
Ok(None)
}
}
}
pub async fn get_single_merchant_id_and_profile_id(
state: &SessionState,
user_role: &UserRole,
) -> UserResult<(id_type::MerchantId, id_type::ProfileId)> {
let org_id = get_single_org_id(state, user_role).await?;
let merchant_id = get_single_merchant_id(state, user_role, &org_id).await?;
let profile_id = get_single_profile_id(state, user_role, &merchant_id).await?;
Ok((merchant_id, profile_id))
}
pub async fn fetch_user_roles_by_payload(
state: &SessionState,
payload: ListUserRolesByOrgIdPayload<'_>,
request_entity_type: Option<EntityType>,
) -> UserResult<HashSet<UserRole>> {
Ok(state
.global_store
.list_user_roles_by_org_id(payload)
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.filter_map(|user_role| {
let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?;
request_entity_type
.is_none_or(|req_entity_type| entity_type == req_entity_type)
.then_some(user_role)
})
.collect::<HashSet<_>>())
}
pub fn get_min_entity(
user_entity: EntityType,
filter_entity: Option<EntityType>,
) -> UserResult<EntityType> {
let Some(filter_entity) = filter_entity else {
return Ok(user_entity);
};
if user_entity < filter_entity {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"{user_entity} level user requesting data for {filter_entity:?} level",
));
}
Ok(cmp::min(user_entity, filter_entity))
}
pub fn parent_group_info_request_to_permission_groups(
parent_groups: &[role_api::ParentGroupInfoRequest],
) -> Result<Vec<PermissionGroup>, UserErrors> {
parent_groups
.iter()
.try_fold(Vec::new(), |mut permission_groups, parent_group| {
let scopes = &parent_group.scopes;
if scopes.is_empty() {
return Err(UserErrors::InvalidRoleOperation);
}
let available_scopes = parent_group.name.get_available_scopes();
if !scopes.iter().all(|scope| available_scopes.contains(scope)) {
return Err(UserErrors::InvalidRoleOperation);
}
let groups = PermissionGroup::iter()
.filter(|group| {
group.parent() == parent_group.name && scopes.contains(&group.scope())
})
.collect::<Vec<_>>();
permission_groups.extend(groups);
Ok(permission_groups)
})
}
pub fn permission_groups_to_parent_group_info(
permission_groups: &[PermissionGroup],
entity_type: EntityType,
) -> Vec<role_api::ParentGroupInfo> {
let parent_groups_map: HashMap<ParentGroup, Vec<common_enums::PermissionScope>> =
permission_groups
.iter()
.fold(HashMap::new(), |mut acc, group| {
let parent = group.parent();
let scope = group.scope();
acc.entry(parent).or_default().push(scope);
acc
});
parent_groups_map
.into_iter()
.filter_map(|(name, scopes)| {
let unique_scopes = scopes
.into_iter()
.collect::<HashSet<_>>()
.into_iter()
.collect();
let filtered_resources =
permissions::filter_resources_by_entity_type(name.resources(), entity_type)?;
Some(role_api::ParentGroupInfo {
name,
resources: filtered_resources,
scopes: unique_scopes,
})
})
.collect()
}
pub fn resources_to_description(
resources: Vec<common_enums::Resource>,
entity_type: EntityType,
) -> Option<String> {
if resources.is_empty() {
return None;
}
let filtered_resources = permissions::filter_resources_by_entity_type(resources, entity_type)?;
let description = filtered_resources
.iter()
.map(|res| permissions::get_resource_name(*res, entity_type))
.collect::<Option<Vec<_>>>()?
.join(", ");
Some(description)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/utils/verify_connector.rs | crates/router/src/utils/verify_connector.rs | use api_models::enums::Connector;
use error_stack::ResultExt;
use crate::{core::errors, types::domain};
pub fn generate_card_from_details(
card_number: String,
card_exp_year: String,
card_exp_month: String,
card_cvv: String,
) -> errors::RouterResult<domain::Card> {
Ok(domain::Card {
card_number: card_number
.parse::<cards::CardNumber>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing card number")?,
card_issuer: None,
card_cvc: masking::Secret::new(card_cvv),
card_network: None,
card_exp_year: masking::Secret::new(card_exp_year),
card_exp_month: masking::Secret::new(card_exp_month),
nick_name: None,
card_type: None,
card_issuing_country: None,
card_issuing_country_code: None,
bank_code: None,
card_holder_name: None,
co_badged_card_data: None,
})
}
pub fn get_test_card_details(
connector_name: Connector,
) -> errors::RouterResult<Option<domain::Card>> {
match connector_name {
Connector::Stripe => Some(generate_card_from_details(
"4242424242424242".to_string(),
"2025".to_string(),
"12".to_string(),
"100".to_string(),
))
.transpose(),
Connector::Paypal => Some(generate_card_from_details(
"4111111111111111".to_string(),
"2025".to_string(),
"02".to_string(),
"123".to_string(),
))
.transpose(),
_ => Ok(None),
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/utils/chat.rs | crates/router/src/utils/chat.rs | use api_models::chat as chat_api;
use common_utils::{
crypto::{EncodeMessage, GcmAes256},
encryption::Encryption,
};
use diesel_models::hyperswitch_ai_interaction::HyperswitchAiInteractionNew;
use error_stack::ResultExt;
use masking::ExposeInterface;
use crate::{
core::errors::{self, CustomResult},
routes::SessionState,
services::authentication as auth,
};
pub async fn construct_hyperswitch_ai_interaction(
state: &SessionState,
user_from_token: &auth::UserFromToken,
req: &chat_api::ChatRequest,
response: &chat_api::ChatResponse,
request_id: &str,
) -> CustomResult<HyperswitchAiInteractionNew, errors::ApiErrorResponse> {
let encryption_key = state.conf.chat.get_inner().encryption_key.clone().expose();
let key = match hex::decode(&encryption_key) {
Ok(key) => key,
Err(e) => {
router_env::logger::error!("Failed to decode encryption key: {}", e);
// Fallback to using the string as bytes, which was the previous behavior
encryption_key.as_bytes().to_vec()
}
};
let encrypted_user_query_bytes = GcmAes256
.encode_message(&key, &req.message.clone().expose().into_bytes())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt user query")?;
let encrypted_response_bytes = serde_json::to_vec(&response.response.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize response for encryption")
.and_then(|bytes| {
GcmAes256
.encode_message(&key, &bytes)
.change_context(errors::ApiErrorResponse::InternalServerError)
})
.attach_printable("Failed to encrypt response")?;
Ok(HyperswitchAiInteractionNew {
id: request_id.to_owned(),
session_id: Some(request_id.to_string()),
user_id: Some(user_from_token.user_id.clone()),
merchant_id: Some(user_from_token.merchant_id.get_string_repr().to_string()),
profile_id: Some(user_from_token.profile_id.get_string_repr().to_string()),
org_id: Some(user_from_token.org_id.get_string_repr().to_string()),
role_id: Some(user_from_token.role_id.clone()),
user_query: Some(Encryption::new(encrypted_user_query_bytes.into())),
response: Some(Encryption::new(encrypted_response_bytes.into())),
database_query: response.query_executed.clone().map(|q| q.expose()),
interaction_status: Some(response.status.clone()),
created_at: common_utils::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/utils/currency.rs | crates/router/src/utils/currency.rs | use std::{
collections::HashMap,
ops::Deref,
str::FromStr,
sync::{Arc, LazyLock},
};
use api_models::enums;
use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt};
use currency_conversion::types::{CurrencyFactors, ExchangeRates};
use error_stack::ResultExt;
use masking::PeekInterface;
use redis_interface::DelReply;
use router_env::{instrument, tracing};
use rust_decimal::Decimal;
use strum::IntoEnumIterator;
use tokio::sync::RwLock;
use tracing_futures::Instrument;
use crate::{
logger,
routes::app::settings::{Conversion, DefaultExchangeRates},
services, SessionState,
};
const REDIX_FOREX_CACHE_KEY: &str = "{forex_cache}_lock";
const REDIX_FOREX_CACHE_DATA: &str = "{forex_cache}_data";
const FOREX_API_TIMEOUT: u64 = 5;
const FOREX_BASE_URL: &str = "https://openexchangerates.org/api/latest.json?app_id=";
const FOREX_BASE_CURRENCY: &str = "&base=USD";
const FALLBACK_FOREX_BASE_URL: &str = "http://apilayer.net/api/live?access_key=";
const FALLBACK_FOREX_API_CURRENCY_PREFIX: &str = "USD";
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FxExchangeRatesCacheEntry {
pub data: Arc<ExchangeRates>,
timestamp: i64,
}
static FX_EXCHANGE_RATES_CACHE: LazyLock<RwLock<Option<FxExchangeRatesCacheEntry>>> =
LazyLock::new(|| RwLock::new(None));
impl ApiEventMetric for FxExchangeRatesCacheEntry {}
#[derive(Debug, Clone, thiserror::Error)]
pub enum ForexError {
#[error("API error")]
ApiError,
#[error("API timeout")]
ApiTimeout,
#[error("API unresponsive")]
ApiUnresponsive,
#[error("Conversion error")]
ConversionError,
#[error("Could not acquire the lock for cache entry")]
CouldNotAcquireLock,
#[error("Provided currency not acceptable")]
CurrencyNotAcceptable,
#[error("Forex configuration error: {0}")]
ConfigurationError(String),
#[error("Incorrect entries in default Currency response")]
DefaultCurrencyParsingError,
#[error("Entry not found in cache")]
EntryNotFound,
#[error("Forex data unavailable")]
ForexDataUnavailable,
#[error("Expiration time invalid")]
InvalidLogExpiry,
#[error("Error reading local")]
LocalReadError,
#[error("Error writing to local cache")]
LocalWriteError,
#[error("Json Parsing error")]
ParsingError,
#[error("Aws Kms decryption error")]
AwsKmsDecryptionFailed,
#[error("Error connecting to redis")]
RedisConnectionError,
#[error("Not able to release write lock")]
RedisLockReleaseFailed,
#[error("Error writing to redis")]
RedisWriteError,
#[error("Not able to acquire write lock")]
WriteLockNotAcquired,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct ForexResponse {
pub rates: HashMap<String, FloatDecimal>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct FallbackForexResponse {
pub quotes: HashMap<String, FloatDecimal>,
}
#[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
struct FloatDecimal(#[serde(with = "rust_decimal::serde::float")] Decimal);
impl Deref for FloatDecimal {
type Target = Decimal;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl FxExchangeRatesCacheEntry {
fn new(exchange_rate: ExchangeRates) -> Self {
Self {
data: Arc::new(exchange_rate),
timestamp: date_time::now_unix_timestamp(),
}
}
fn is_expired(&self, data_expiration_delay: u32) -> bool {
self.timestamp + i64::from(data_expiration_delay) < date_time::now_unix_timestamp()
}
}
async fn retrieve_forex_from_local_cache() -> Option<FxExchangeRatesCacheEntry> {
FX_EXCHANGE_RATES_CACHE.read().await.clone()
}
async fn save_forex_data_to_local_cache(
exchange_rates_cache_entry: FxExchangeRatesCacheEntry,
) -> CustomResult<(), ForexError> {
let mut local = FX_EXCHANGE_RATES_CACHE.write().await;
*local = Some(exchange_rates_cache_entry);
logger::debug!("forex_log: forex saved in cache");
Ok(())
}
impl TryFrom<DefaultExchangeRates> for ExchangeRates {
type Error = error_stack::Report<ForexError>;
fn try_from(value: DefaultExchangeRates) -> Result<Self, Self::Error> {
let mut conversion_usable: HashMap<enums::Currency, CurrencyFactors> = HashMap::new();
for (curr, conversion) in value.conversion {
let enum_curr = enums::Currency::from_str(curr.as_str())
.change_context(ForexError::ConversionError)
.attach_printable("Unable to Convert currency received")?;
conversion_usable.insert(enum_curr, CurrencyFactors::from(conversion));
}
let base_curr = enums::Currency::from_str(value.base_currency.as_str())
.change_context(ForexError::ConversionError)
.attach_printable("Unable to convert base currency")?;
Ok(Self {
base_currency: base_curr,
conversion: conversion_usable,
})
}
}
impl From<Conversion> for CurrencyFactors {
fn from(value: Conversion) -> Self {
Self {
to_factor: value.to_factor,
from_factor: value.from_factor,
}
}
}
#[instrument(skip_all)]
pub async fn get_forex_rates(
state: &SessionState,
data_expiration_delay: u32,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
if let Some(local_rates) = retrieve_forex_from_local_cache().await {
if local_rates.is_expired(data_expiration_delay) {
// expired local data
logger::debug!("forex_log: Forex stored in cache is expired");
call_forex_api_and_save_data_to_cache_and_redis(state, Some(local_rates)).await
} else {
// Valid data present in local
logger::debug!("forex_log: forex found in cache");
Ok(local_rates)
}
} else {
// No data in local
call_api_if_redis_forex_data_expired(state, data_expiration_delay).await
}
}
async fn call_api_if_redis_forex_data_expired(
state: &SessionState,
data_expiration_delay: u32,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
match retrieve_forex_data_from_redis(state).await {
Ok(Some(data)) => {
call_forex_api_if_redis_data_expired(state, data, data_expiration_delay).await
}
Ok(None) => {
// No data in local as well as redis
call_forex_api_and_save_data_to_cache_and_redis(state, None).await?;
Err(ForexError::ForexDataUnavailable.into())
}
Err(error) => {
// Error in deriving forex rates from redis
logger::error!("forex_error: {:?}", error);
call_forex_api_and_save_data_to_cache_and_redis(state, None).await?;
Err(ForexError::ForexDataUnavailable.into())
}
}
}
async fn call_forex_api_and_save_data_to_cache_and_redis(
state: &SessionState,
stale_redis_data: Option<FxExchangeRatesCacheEntry>,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
// spawn a new thread and do the api fetch and write operations on redis.
let forex_api_key = state.conf.forex_api.get_inner().api_key.peek();
if forex_api_key.is_empty() {
Err(ForexError::ConfigurationError("api_keys not provided".into()).into())
} else {
let state = state.clone();
tokio::spawn(
async move {
acquire_redis_lock_and_call_forex_api(&state)
.await
.map_err(|err| {
logger::error!(forex_error=?err);
})
.ok();
}
.in_current_span(),
);
stale_redis_data.ok_or(ForexError::EntryNotFound.into())
}
}
async fn acquire_redis_lock_and_call_forex_api(
state: &SessionState,
) -> CustomResult<(), ForexError> {
let lock_acquired = acquire_redis_lock(state).await?;
if !lock_acquired {
Err(ForexError::CouldNotAcquireLock.into())
} else {
logger::debug!("forex_log: redis lock acquired");
let api_rates = fetch_forex_rates_from_primary_api(state).await;
match api_rates {
Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await,
Err(error) => {
logger::error!(forex_error=?error,"primary_forex_error");
// API not able to fetch data call secondary service
let secondary_api_rates = fetch_forex_rates_from_fallback_api(state).await;
match secondary_api_rates {
Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await,
Err(error) => {
release_redis_lock(state).await?;
Err(error)
}
}
}
}
}
}
async fn save_forex_data_to_cache_and_redis(
state: &SessionState,
forex: FxExchangeRatesCacheEntry,
) -> CustomResult<(), ForexError> {
save_forex_data_to_redis(state, &forex)
.await
.async_and_then(|_rates| release_redis_lock(state))
.await
.async_and_then(|_val| save_forex_data_to_local_cache(forex.clone()))
.await
}
async fn call_forex_api_if_redis_data_expired(
state: &SessionState,
redis_data: FxExchangeRatesCacheEntry,
data_expiration_delay: u32,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
match is_redis_expired(Some(redis_data.clone()).as_ref(), data_expiration_delay).await {
Some(redis_forex) => {
// Valid data present in redis
let exchange_rates = FxExchangeRatesCacheEntry::new(redis_forex.as_ref().clone());
logger::debug!("forex_log: forex response found in redis");
save_forex_data_to_local_cache(exchange_rates.clone()).await?;
Ok(exchange_rates)
}
None => {
// redis expired
call_forex_api_and_save_data_to_cache_and_redis(state, Some(redis_data)).await
}
}
}
async fn fetch_forex_rates_from_primary_api(
state: &SessionState,
) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexError>> {
let forex_api_key = state.conf.forex_api.get_inner().api_key.peek();
logger::debug!("forex_log: Primary api call for forex fetch");
let forex_url: String = format!("{FOREX_BASE_URL}{forex_api_key}{FOREX_BASE_CURRENCY}");
let forex_request = services::RequestBuilder::new()
.method(services::Method::Get)
.url(&forex_url)
.build();
logger::info!(primary_forex_request=?forex_request,"forex_log: Primary api call for forex fetch");
let response = state
.api_client
.send_request(
&state.clone(),
forex_request,
Some(FOREX_API_TIMEOUT),
false,
)
.await
.change_context(ForexError::ApiUnresponsive)
.attach_printable("Primary forex fetch api unresponsive")?;
let forex_response = response
.json::<ForexResponse>()
.await
.change_context(ForexError::ParsingError)
.attach_printable(
"Unable to parse response received from primary api into ForexResponse",
)?;
logger::info!(primary_forex_response=?forex_response,"forex_log");
let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new();
for enum_curr in enums::Currency::iter() {
match forex_response.rates.get(&enum_curr.to_string()) {
Some(rate) => {
let from_factor = match Decimal::new(1, 0).checked_div(**rate) {
Some(rate) => rate,
None => {
logger::error!(
"forex_error: Rates for {} not received from API",
&enum_curr
);
continue;
}
};
let currency_factors = CurrencyFactors::new(**rate, from_factor);
conversions.insert(enum_curr, currency_factors);
}
None => {
logger::error!(
"forex_error: Rates for {} not received from API",
&enum_curr
);
}
};
}
Ok(FxExchangeRatesCacheEntry::new(ExchangeRates::new(
enums::Currency::USD,
conversions,
)))
}
pub async fn fetch_forex_rates_from_fallback_api(
state: &SessionState,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
let fallback_forex_api_key = state.conf.forex_api.get_inner().fallback_api_key.peek();
let fallback_forex_url: String = format!("{FALLBACK_FOREX_BASE_URL}{fallback_forex_api_key}");
let fallback_forex_request = services::RequestBuilder::new()
.method(services::Method::Get)
.url(&fallback_forex_url)
.build();
logger::info!(fallback_forex_request=?fallback_forex_request,"forex_log: Fallback api call for forex fetch");
let response = state
.api_client
.send_request(
&state.clone(),
fallback_forex_request,
Some(FOREX_API_TIMEOUT),
false,
)
.await
.change_context(ForexError::ApiUnresponsive)
.attach_printable("Fallback forex fetch api unresponsive")?;
let fallback_forex_response = response
.json::<FallbackForexResponse>()
.await
.change_context(ForexError::ParsingError)
.attach_printable(
"Unable to parse response received from fallback api into ForexResponse",
)?;
logger::info!(fallback_forex_response=?fallback_forex_response,"forex_log");
let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new();
for enum_curr in enums::Currency::iter() {
match fallback_forex_response.quotes.get(
format!(
"{}{}",
FALLBACK_FOREX_API_CURRENCY_PREFIX,
&enum_curr.to_string()
)
.as_str(),
) {
Some(rate) => {
let from_factor = match Decimal::new(1, 0).checked_div(**rate) {
Some(rate) => rate,
None => {
logger::error!(
"forex_error: Rates for {} not received from API",
&enum_curr
);
continue;
}
};
let currency_factors = CurrencyFactors::new(**rate, from_factor);
conversions.insert(enum_curr, currency_factors);
}
None => {
if enum_curr == enums::Currency::USD {
let currency_factors =
CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0));
conversions.insert(enum_curr, currency_factors);
} else {
logger::error!(
"forex_error: Rates for {} not received from API",
&enum_curr
);
}
}
};
}
let rates =
FxExchangeRatesCacheEntry::new(ExchangeRates::new(enums::Currency::USD, conversions));
match acquire_redis_lock(state).await {
Ok(_) => {
save_forex_data_to_cache_and_redis(state, rates.clone()).await?;
Ok(rates)
}
Err(e) => Err(e),
}
}
async fn release_redis_lock(
state: &SessionState,
) -> Result<DelReply, error_stack::Report<ForexError>> {
logger::debug!("forex_log: Releasing redis lock");
state
.store
.get_redis_conn()
.change_context(ForexError::RedisConnectionError)?
.delete_key(&REDIX_FOREX_CACHE_KEY.into())
.await
.change_context(ForexError::RedisLockReleaseFailed)
.attach_printable("Unable to release redis lock")
}
async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexError> {
let forex_api = state.conf.forex_api.get_inner();
logger::debug!("forex_log: Acquiring redis lock");
state
.store
.get_redis_conn()
.change_context(ForexError::RedisConnectionError)?
.set_key_if_not_exists_with_expiry(
&REDIX_FOREX_CACHE_KEY.into(),
"",
Some(i64::from(forex_api.redis_lock_timeout_in_seconds)),
)
.await
.map(|val| matches!(val, redis_interface::SetnxReply::KeySet))
.change_context(ForexError::CouldNotAcquireLock)
.attach_printable("Unable to acquire redis lock")
}
async fn save_forex_data_to_redis(
app_state: &SessionState,
forex_exchange_cache_entry: &FxExchangeRatesCacheEntry,
) -> CustomResult<(), ForexError> {
let forex_api = app_state.conf.forex_api.get_inner();
logger::debug!("forex_log: Saving forex to redis");
app_state
.store
.get_redis_conn()
.change_context(ForexError::RedisConnectionError)?
.serialize_and_set_key_with_expiry(
&REDIX_FOREX_CACHE_DATA.into(),
forex_exchange_cache_entry,
i64::from(forex_api.redis_ttl_in_seconds),
)
.await
.change_context(ForexError::RedisWriteError)
.attach_printable("Unable to save forex data to redis")
}
async fn retrieve_forex_data_from_redis(
app_state: &SessionState,
) -> CustomResult<Option<FxExchangeRatesCacheEntry>, ForexError> {
logger::debug!("forex_log: Retrieving forex from redis");
app_state
.store
.get_redis_conn()
.change_context(ForexError::RedisConnectionError)?
.get_and_deserialize_key(&REDIX_FOREX_CACHE_DATA.into(), "FxExchangeRatesCache")
.await
.change_context(ForexError::EntryNotFound)
.attach_printable("Forex entry not found in redis")
}
async fn is_redis_expired(
redis_cache: Option<&FxExchangeRatesCacheEntry>,
data_expiration_delay: u32,
) -> Option<Arc<ExchangeRates>> {
redis_cache.and_then(|cache| {
if cache.timestamp + i64::from(data_expiration_delay) > date_time::now_unix_timestamp() {
Some(cache.data.clone())
} else {
logger::debug!("forex_log: Forex stored in redis is expired");
None
}
})
}
#[instrument(skip_all)]
pub async fn convert_currency(
state: SessionState,
amount: i64,
to_currency: String,
from_currency: String,
) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexError> {
let forex_api = state.conf.forex_api.get_inner();
let rates = get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds)
.await
.change_context(ForexError::ApiError)?;
let to_currency = enums::Currency::from_str(to_currency.as_str())
.change_context(ForexError::CurrencyNotAcceptable)
.attach_printable("The provided currency is not acceptable")?;
let from_currency = enums::Currency::from_str(from_currency.as_str())
.change_context(ForexError::CurrencyNotAcceptable)
.attach_printable("The provided currency is not acceptable")?;
let converted_amount =
currency_conversion::conversion::convert(&rates.data, from_currency, to_currency, amount)
.change_context(ForexError::ConversionError)
.attach_printable("Unable to perform currency conversion")?;
Ok(api_models::currency::CurrencyConversionResponse {
converted_amount: converted_amount.to_string(),
currency: to_currency.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/utils/db_utils.rs | crates/router/src/utils/db_utils.rs | use crate::{
core::errors::{self, utils::RedisErrorExt},
routes::metrics,
};
/// Generates hscan field pattern. Suppose the field is pa_1234_ref_1211 it will generate
/// pa_1234_ref_*
pub fn generate_hscan_pattern_for_refund(sk: &str) -> String {
sk.split('_')
.take(3)
.chain(["*"])
.collect::<Vec<&str>>()
.join("_")
}
// The first argument should be a future while the second argument should be a closure that returns a future for a database call
pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>(
redis_fut: RFut,
database_call_closure: F,
) -> error_stack::Result<T, errors::StorageError>
where
F: FnOnce() -> DFut,
RFut: futures::Future<Output = error_stack::Result<T, redis_interface::errors::RedisError>>,
DFut: futures::Future<Output = error_stack::Result<T, errors::StorageError>>,
{
let redis_output = redis_fut.await;
match redis_output {
Ok(output) => Ok(output),
Err(redis_error) => match redis_error.current_context() {
redis_interface::errors::RedisError::NotFound => {
metrics::KV_MISS.add(1, &[]);
database_call_closure().await
}
// Keeping the key empty here since the error would never go here.
_ => Err(redis_error.to_redis_failed_response("")),
},
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/utils/user/password.rs | crates/router/src/utils/user/password.rs | use argon2::{
password_hash::{
rand_core::OsRng, Error as argon2Err, PasswordHash, PasswordHasher, PasswordVerifier,
SaltString,
},
Argon2,
};
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret};
use rand::{seq::SliceRandom, Rng};
use crate::core::errors::UserErrors;
pub fn generate_password_hash(
password: Secret<String>,
) -> CustomResult<Secret<String>, UserErrors> {
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
let password_hash = argon2
.hash_password(password.expose().as_bytes(), &salt)
.change_context(UserErrors::InternalServerError)?;
Ok(Secret::new(password_hash.to_string()))
}
pub fn is_correct_password(
candidate: &Secret<String>,
password: &Secret<String>,
) -> CustomResult<bool, UserErrors> {
let password = password.peek();
let parsed_hash =
PasswordHash::new(password).change_context(UserErrors::InternalServerError)?;
let result = Argon2::default().verify_password(candidate.peek().as_bytes(), &parsed_hash);
match result {
Ok(_) => Ok(true),
Err(argon2Err::Password) => Ok(false),
Err(e) => Err(e),
}
.change_context(UserErrors::InternalServerError)
}
pub fn get_index_for_correct_recovery_code(
candidate: &Secret<String>,
recovery_codes: &[Secret<String>],
) -> CustomResult<Option<usize>, UserErrors> {
for (index, recovery_code) in recovery_codes.iter().enumerate() {
let is_match = is_correct_password(candidate, recovery_code)?;
if is_match {
return Ok(Some(index));
}
}
Ok(None)
}
pub fn get_temp_password() -> Secret<String> {
let uuid_pass = uuid::Uuid::new_v4().to_string();
let mut rng = rand::thread_rng();
let special_chars: Vec<char> = "!@#$%^&*()-_=+[]{}|;:,.<>?".chars().collect();
let special_char = special_chars.choose(&mut rng).unwrap_or(&'@');
Secret::new(format!(
"{}{}{}{}{}",
uuid_pass,
rng.gen_range('A'..='Z'),
special_char,
rng.gen_range('a'..='z'),
rng.gen_range('0'..='9'),
))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/utils/user/theme.rs | crates/router/src/utils/user/theme.rs | use std::path::PathBuf;
use common_enums::EntityType;
use common_utils::{ext_traits::AsyncExt, id_type, types::user::ThemeLineage};
use diesel_models::user::theme::Theme;
use error_stack::ResultExt;
use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
use crate::{
core::errors::{StorageErrorExt, UserErrors, UserResult},
routes::SessionState,
services::authentication::UserFromToken,
};
fn get_theme_dir_key(theme_id: &str) -> PathBuf {
["themes", theme_id].iter().collect()
}
pub fn get_specific_file_key(theme_id: &str, file_name: &str) -> PathBuf {
let mut path = get_theme_dir_key(theme_id);
path.push(file_name);
path
}
pub fn get_theme_file_key(theme_id: &str) -> PathBuf {
get_specific_file_key(theme_id, "theme.json")
}
fn path_buf_to_str(path: &PathBuf) -> UserResult<&str> {
path.to_str()
.ok_or(UserErrors::InternalServerError)
.attach_printable(format!("Failed to convert path {path:#?} to string"))
}
pub async fn retrieve_file_from_theme_bucket(
state: &SessionState,
path: &PathBuf,
) -> UserResult<Vec<u8>> {
state
.theme_storage_client
.retrieve_file(path_buf_to_str(path)?)
.await
.change_context(UserErrors::ErrorRetrievingFile)
}
pub async fn upload_file_to_theme_bucket(
state: &SessionState,
path: &PathBuf,
data: Vec<u8>,
) -> UserResult<()> {
state
.theme_storage_client
.upload_file(path_buf_to_str(path)?, data)
.await
.change_context(UserErrors::ErrorUploadingFile)
}
pub async fn validate_lineage(state: &SessionState, lineage: &ThemeLineage) -> UserResult<()> {
match lineage {
ThemeLineage::Tenant { tenant_id } => {
validate_tenant(state, tenant_id)?;
Ok(())
}
ThemeLineage::Organization { tenant_id, org_id } => {
validate_tenant(state, tenant_id)?;
validate_org(state, org_id).await?;
Ok(())
}
ThemeLineage::Merchant {
tenant_id,
org_id,
merchant_id,
} => {
validate_tenant(state, tenant_id)?;
validate_org(state, org_id).await?;
validate_merchant(state, org_id, merchant_id).await?;
Ok(())
}
ThemeLineage::Profile {
tenant_id,
org_id,
merchant_id,
profile_id,
} => {
validate_tenant(state, tenant_id)?;
validate_org(state, org_id).await?;
let key_store = validate_merchant_and_get_key_store(state, org_id, merchant_id).await?;
validate_profile(state, profile_id, merchant_id, &key_store).await?;
Ok(())
}
}
}
fn validate_tenant(state: &SessionState, tenant_id: &id_type::TenantId) -> UserResult<()> {
if &state.tenant.tenant_id != tenant_id {
return Err(UserErrors::InvalidThemeLineage("tenant_id".to_string()).into());
}
Ok(())
}
async fn validate_org(state: &SessionState, org_id: &id_type::OrganizationId) -> UserResult<()> {
state
.accounts_store
.find_organization_by_org_id(org_id)
.await
.to_not_found_response(UserErrors::InvalidThemeLineage("org_id".to_string()))
.map(|_| ())
}
async fn validate_merchant_and_get_key_store(
state: &SessionState,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
) -> UserResult<MerchantKeyStore> {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(UserErrors::InvalidThemeLineage("merchant_id".to_string()))?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(merchant_id, &key_store)
.await
.to_not_found_response(UserErrors::InvalidThemeLineage("merchant_id".to_string()))?;
if &merchant_account.organization_id != org_id {
return Err(UserErrors::InvalidThemeLineage("merchant_id".to_string()).into());
}
Ok(key_store)
}
async fn validate_merchant(
state: &SessionState,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
) -> UserResult<()> {
validate_merchant_and_get_key_store(state, org_id, merchant_id)
.await
.map(|_| ())
}
async fn validate_profile(
state: &SessionState,
profile_id: &id_type::ProfileId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
) -> UserResult<()> {
state
.store
.find_business_profile_by_merchant_id_profile_id(key_store, merchant_id, profile_id)
.await
.to_not_found_response(UserErrors::InvalidThemeLineage("profile_id".to_string()))
.map(|_| ())
}
pub async fn get_most_specific_theme_using_token_and_min_entity(
state: &SessionState,
user_from_token: &UserFromToken,
min_entity: EntityType,
) -> UserResult<Option<Theme>> {
get_most_specific_theme_using_lineage(
state,
ThemeLineage::new(
min_entity,
user_from_token
.tenant_id
.clone()
.unwrap_or(state.tenant.tenant_id.clone()),
user_from_token.org_id.clone(),
user_from_token.merchant_id.clone(),
user_from_token.profile_id.clone(),
),
)
.await
}
pub async fn get_most_specific_theme_using_lineage(
state: &SessionState,
lineage: ThemeLineage,
) -> UserResult<Option<Theme>> {
match state
.store
.find_most_specific_theme_in_lineage(lineage)
.await
{
Ok(theme) => Ok(Some(theme)),
Err(e) => {
if e.current_context().is_db_not_found() {
Ok(None)
} else {
Err(e.change_context(UserErrors::InternalServerError))
}
}
}
}
pub async fn get_theme_using_optional_theme_id(
state: &SessionState,
theme_id: Option<String>,
) -> UserResult<Option<Theme>> {
match theme_id
.async_map(|theme_id| state.store.find_theme_by_theme_id(theme_id))
.await
.transpose()
{
Ok(theme) => Ok(theme),
Err(e) => {
if e.current_context().is_db_not_found() {
Ok(None)
} else {
Err(e.change_context(UserErrors::InternalServerError))
}
}
}
}
pub async fn get_theme_lineage_from_user_token(
user_from_token: &UserFromToken,
state: &SessionState,
request_entity_type: &EntityType,
) -> UserResult<ThemeLineage> {
let tenant_id = user_from_token
.tenant_id
.clone()
.unwrap_or(state.tenant.tenant_id.clone());
let org_id = user_from_token.org_id.clone();
let merchant_id = user_from_token.merchant_id.clone();
let profile_id = user_from_token.profile_id.clone();
Ok(ThemeLineage::new(
*request_entity_type,
tenant_id,
org_id,
merchant_id,
profile_id,
))
}
pub async fn can_user_access_theme(
user: &UserFromToken,
user_entity_type: &EntityType,
theme: &Theme,
) -> UserResult<()> {
if user_entity_type < &theme.entity_type {
return Err(UserErrors::ThemeNotFound.into());
}
match theme.entity_type {
EntityType::Tenant => {
if user.tenant_id.as_ref() == Some(&theme.tenant_id)
&& theme.org_id.is_none()
&& theme.merchant_id.is_none()
&& theme.profile_id.is_none()
{
Ok(())
} else {
Err(UserErrors::ThemeNotFound.into())
}
}
EntityType::Organization => {
if user.tenant_id.as_ref() == Some(&theme.tenant_id)
&& theme.org_id.as_ref() == Some(&user.org_id)
&& theme.merchant_id.is_none()
&& theme.profile_id.is_none()
{
Ok(())
} else {
Err(UserErrors::ThemeNotFound.into())
}
}
EntityType::Merchant => {
if user.tenant_id.as_ref() == Some(&theme.tenant_id)
&& theme.org_id.as_ref() == Some(&user.org_id)
&& theme.merchant_id.as_ref() == Some(&user.merchant_id)
&& theme.profile_id.is_none()
{
Ok(())
} else {
Err(UserErrors::ThemeNotFound.into())
}
}
EntityType::Profile => {
if user.tenant_id.as_ref() == Some(&theme.tenant_id)
&& theme.org_id.as_ref() == Some(&user.org_id)
&& theme.merchant_id.as_ref() == Some(&user.merchant_id)
&& theme.profile_id.as_ref() == Some(&user.profile_id)
{
Ok(())
} else {
Err(UserErrors::ThemeNotFound.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/utils/user/two_factor_auth.rs | crates/router/src/utils/user/two_factor_auth.rs | use common_utils::pii;
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface};
use totp_rs::{Algorithm, TOTP};
use crate::{
consts,
core::errors::{UserErrors, UserResult},
routes::SessionState,
};
pub fn generate_default_totp(
email: pii::Email,
secret: Option<masking::Secret<String>>,
issuer: String,
) -> UserResult<TOTP> {
let secret = secret
.map(|sec| totp_rs::Secret::Encoded(sec.expose()))
.unwrap_or_else(totp_rs::Secret::generate_secret)
.to_bytes()
.change_context(UserErrors::InternalServerError)?;
TOTP::new(
Algorithm::SHA1,
consts::user::TOTP_DIGITS,
consts::user::TOTP_TOLERANCE,
consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS,
secret,
Some(issuer),
email.expose().expose(),
)
.change_context(UserErrors::InternalServerError)
}
pub async fn check_totp_in_redis(state: &SessionState, user_id: &str) -> UserResult<bool> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id);
redis_conn
.exists::<()>(&key.into())
.await
.change_context(UserErrors::InternalServerError)
}
pub async fn check_recovery_code_in_redis(state: &SessionState, user_id: &str) -> UserResult<bool> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id);
redis_conn
.exists::<()>(&key.into())
.await
.change_context(UserErrors::InternalServerError)
}
pub async fn insert_totp_in_redis(state: &SessionState, user_id: &str) -> UserResult<()> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id);
redis_conn
.set_key_with_expiry(
&key.as_str().into(),
common_utils::date_time::now_unix_timestamp(),
state.conf.user.two_factor_auth_expiry_in_secs,
)
.await
.change_context(UserErrors::InternalServerError)
}
pub async fn insert_totp_secret_in_redis(
state: &SessionState,
user_id: &str,
secret: &masking::Secret<String>,
) -> UserResult<()> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
redis_conn
.set_key_with_expiry(
&get_totp_secret_key(user_id).into(),
secret.peek(),
consts::user::REDIS_TOTP_SECRET_TTL_IN_SECS,
)
.await
.change_context(UserErrors::InternalServerError)
}
pub async fn get_totp_secret_from_redis(
state: &SessionState,
user_id: &str,
) -> UserResult<Option<masking::Secret<String>>> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
redis_conn
.get_key::<Option<String>>(&get_totp_secret_key(user_id).into())
.await
.change_context(UserErrors::InternalServerError)
.map(|secret| secret.map(Into::into))
}
pub async fn delete_totp_secret_from_redis(state: &SessionState, user_id: &str) -> UserResult<()> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
redis_conn
.delete_key(&get_totp_secret_key(user_id).into())
.await
.change_context(UserErrors::InternalServerError)
.map(|_| ())
}
fn get_totp_secret_key(user_id: &str) -> String {
format!("{}{}", consts::user::REDIS_TOTP_SECRET_PREFIX, user_id)
}
pub async fn insert_recovery_code_in_redis(state: &SessionState, user_id: &str) -> UserResult<()> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id);
redis_conn
.set_key_with_expiry(
&key.as_str().into(),
common_utils::date_time::now_unix_timestamp(),
state.conf.user.two_factor_auth_expiry_in_secs,
)
.await
.change_context(UserErrors::InternalServerError)
}
pub async fn delete_totp_from_redis(state: &SessionState, user_id: &str) -> UserResult<()> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id);
redis_conn
.delete_key(&key.into())
.await
.change_context(UserErrors::InternalServerError)
.map(|_| ())
}
pub async fn delete_recovery_code_from_redis(
state: &SessionState,
user_id: &str,
) -> UserResult<()> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id);
redis_conn
.delete_key(&key.into())
.await
.change_context(UserErrors::InternalServerError)
.map(|_| ())
}
fn get_totp_attempts_key(user_id: &str) -> String {
format!("{}{}", consts::user::REDIS_TOTP_ATTEMPTS_PREFIX, user_id)
}
fn get_recovery_code_attempts_key(user_id: &str) -> String {
format!(
"{}{}",
consts::user::REDIS_RECOVERY_CODE_ATTEMPTS_PREFIX,
user_id
)
}
pub async fn insert_totp_attempts_in_redis(
state: &SessionState,
user_id: &str,
user_totp_attempts: u8,
) -> UserResult<()> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
redis_conn
.set_key_with_expiry(
&get_totp_attempts_key(user_id).into(),
user_totp_attempts,
consts::user::REDIS_TOTP_ATTEMPTS_TTL_IN_SECS,
)
.await
.change_context(UserErrors::InternalServerError)
}
pub async fn get_totp_attempts_from_redis(state: &SessionState, user_id: &str) -> UserResult<u8> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
redis_conn
.get_key::<Option<u8>>(&get_totp_attempts_key(user_id).into())
.await
.change_context(UserErrors::InternalServerError)
.map(|v| v.unwrap_or(0))
}
pub async fn insert_recovery_code_attempts_in_redis(
state: &SessionState,
user_id: &str,
user_recovery_code_attempts: u8,
) -> UserResult<()> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
redis_conn
.set_key_with_expiry(
&get_recovery_code_attempts_key(user_id).into(),
user_recovery_code_attempts,
consts::user::REDIS_RECOVERY_CODE_ATTEMPTS_TTL_IN_SECS,
)
.await
.change_context(UserErrors::InternalServerError)
}
pub async fn get_recovery_code_attempts_from_redis(
state: &SessionState,
user_id: &str,
) -> UserResult<u8> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
redis_conn
.get_key::<Option<u8>>(&get_recovery_code_attempts_key(user_id).into())
.await
.change_context(UserErrors::InternalServerError)
.map(|v| v.unwrap_or(0))
}
pub async fn delete_totp_attempts_from_redis(
state: &SessionState,
user_id: &str,
) -> UserResult<()> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
redis_conn
.delete_key(&get_totp_attempts_key(user_id).into())
.await
.change_context(UserErrors::InternalServerError)
.map(|_| ())
}
pub async fn delete_recovery_code_attempts_from_redis(
state: &SessionState,
user_id: &str,
) -> UserResult<()> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
redis_conn
.delete_key(&get_recovery_code_attempts_key(user_id).into())
.await
.change_context(UserErrors::InternalServerError)
.map(|_| ())
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/utils/user/sample_data.rs | crates/router/src/utils/user/sample_data.rs | use api_models::{
enums::Connector::{DummyConnector4, DummyConnector7},
user::sample_data::SampleDataRequest,
};
use common_utils::{
id_type,
types::{AmountConvertor, ConnectorTransactionId, MinorUnit, StringMinorUnitForConnector},
};
#[cfg(feature = "v1")]
use diesel_models::user::sample_data::PaymentAttemptBatchNew;
use diesel_models::{enums as storage_enums, DisputeNew, RefundNew};
use error_stack::ResultExt;
use hyperswitch_domain_models::payments::PaymentIntent;
use rand::{prelude::SliceRandom, thread_rng, Rng};
use time::OffsetDateTime;
use crate::{
consts,
core::errors::sample_data::{SampleDataError, SampleDataResult},
types::domain,
SessionState,
};
#[cfg(feature = "v1")]
#[allow(clippy::type_complexity)]
pub async fn generate_sample_data(
state: &SessionState,
req: SampleDataRequest,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> SampleDataResult<
Vec<(
PaymentIntent,
PaymentAttemptBatchNew,
Option<RefundNew>,
Option<DisputeNew>,
)>,
> {
let sample_data_size: usize = req.record.unwrap_or(100);
if !(10..=100).contains(&sample_data_size) {
return Err(SampleDataError::InvalidRange.into());
}
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(SampleDataError::InternalServerError)?;
let merchant_from_db = state
.store
.find_merchant_account_by_merchant_id(merchant_id, &key_store)
.await
.change_context::<SampleDataError>(SampleDataError::DataDoesNotExist)?;
let platform = domain::Platform::new(
merchant_from_db.clone(),
key_store.clone(),
merchant_from_db.clone(),
key_store,
None,
);
#[cfg(feature = "v1")]
let (profile_id_result, business_country_default, business_label_default) = {
let merchant_parsed_details: Vec<api_models::admin::PrimaryBusinessDetails> =
serde_json::from_value(merchant_from_db.primary_business_details.clone())
.change_context(SampleDataError::InternalServerError)
.attach_printable("Error while parsing primary business details")?;
let business_country_default = merchant_parsed_details.first().map(|x| x.country);
let business_label_default = merchant_parsed_details.first().map(|x| x.business.clone());
let profile_id = crate::core::utils::get_profile_id_from_business_details(
business_country_default,
business_label_default.as_ref(),
platform.get_processor(),
req.profile_id.as_ref(),
&*state.store,
false,
)
.await;
(profile_id, business_country_default, business_label_default)
};
#[cfg(feature = "v2")]
let (profile_id_result, business_country_default, business_label_default) = {
let profile_id = req
.profile_id.clone()
.ok_or(hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse::MissingRequiredField {
field_name: "profile_id",
});
(profile_id, None, None)
};
let profile_id = match profile_id_result {
Ok(id) => id.clone(),
Err(error) => {
router_env::logger::error!(
"Profile ID not found in business details. Attempting to fetch from the database {error:?}"
);
state
.store
.list_profile_by_merchant_id(platform.get_processor().get_key_store(), merchant_id)
.await
.change_context(SampleDataError::InternalServerError)
.attach_printable("Failed to get business profile")?
.first()
.ok_or(SampleDataError::InternalServerError)?
.get_id()
.to_owned()
}
};
// 10 percent payments should be failed
#[allow(clippy::as_conversions)]
let failure_attempts = usize::try_from((sample_data_size as f32 / 10.0).round() as i64)
.change_context(SampleDataError::InvalidParameters)?;
let failure_after_attempts = sample_data_size / failure_attempts;
// 20 percent refunds for payments
#[allow(clippy::as_conversions)]
let number_of_refunds = usize::try_from((sample_data_size as f32 / 5.0).round() as i64)
.change_context(SampleDataError::InvalidParameters)?;
let mut refunds_count = 0;
// 2 disputes if generated data size is between 50 and 100, 1 dispute if it is less than 50.
let number_of_disputes: usize = if sample_data_size >= 50 { 2 } else { 1 };
let mut disputes_count = 0;
let mut random_array: Vec<usize> = (1..=sample_data_size).collect();
// Shuffle the array
let mut rng = thread_rng();
random_array.shuffle(&mut rng);
let mut res: Vec<(
PaymentIntent,
PaymentAttemptBatchNew,
Option<RefundNew>,
Option<DisputeNew>,
)> = Vec::new();
let start_time = req
.start_time
.unwrap_or(common_utils::date_time::now() - time::Duration::days(7))
.assume_utc()
.unix_timestamp();
let end_time = req
.end_time
.unwrap_or_else(common_utils::date_time::now)
.assume_utc()
.unix_timestamp();
let current_time = common_utils::date_time::now().assume_utc().unix_timestamp();
let min_amount = req.min_amount.unwrap_or(100);
let max_amount = req.max_amount.unwrap_or(min_amount + 100);
if min_amount > max_amount
|| start_time > end_time
|| start_time > current_time
|| end_time > current_time
{
return Err(SampleDataError::InvalidParameters.into());
};
let currency_vec = req.currency.unwrap_or(vec![common_enums::Currency::USD]);
let currency_vec_len = currency_vec.len();
let connector_vec = req
.connector
.unwrap_or(vec![DummyConnector4, DummyConnector7]);
let connector_vec_len = connector_vec.len();
let auth_type = req.auth_type.unwrap_or(vec![
common_enums::AuthenticationType::ThreeDs,
common_enums::AuthenticationType::NoThreeDs,
]);
let auth_type_len = auth_type.len();
if currency_vec_len == 0 || connector_vec_len == 0 || auth_type_len == 0 {
return Err(SampleDataError::InvalidParameters.into());
}
// This has to be an internal server error because, this function failing means that the intended functionality is not working as expected
let dashboard_customer_id =
id_type::CustomerId::try_from(std::borrow::Cow::from("hs-dashboard-user"))
.change_context(SampleDataError::InternalServerError)?;
for num in 1..=sample_data_size {
let payment_id = id_type::PaymentId::generate_test_payment_id_for_sample_data();
let attempt_id = payment_id.get_attempt_id(1);
let client_secret = payment_id.generate_client_secret();
let amount = thread_rng().gen_range(min_amount..=max_amount);
let created_at @ modified_at @ last_synced =
OffsetDateTime::from_unix_timestamp(thread_rng().gen_range(start_time..=end_time))
.map(common_utils::date_time::convert_to_pdt)
.unwrap_or(
req.start_time.unwrap_or_else(|| {
common_utils::date_time::now() - time::Duration::days(7)
}),
);
let session_expiry =
created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
// After some set of payments sample data will have a failed attempt
let is_failed_payment =
(random_array.get(num - 1).unwrap_or(&0) % failure_after_attempts) == 0;
let payment_intent = PaymentIntent {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
status: match is_failed_payment {
true => common_enums::IntentStatus::Failed,
_ => common_enums::IntentStatus::Succeeded,
},
amount: MinorUnit::new(amount * 100),
currency: Some(
*currency_vec
.get((num - 1) % currency_vec_len)
.unwrap_or(&common_enums::Currency::USD),
),
description: Some("This is a sample payment".to_string()),
created_at,
modified_at,
last_synced: Some(last_synced),
client_secret: Some(client_secret),
business_country: business_country_default,
business_label: business_label_default.clone(),
active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
attempt_id.clone(),
),
attempt_count: 1,
customer_id: Some(dashboard_customer_id.clone()),
amount_captured: Some(MinorUnit::new(amount * 100)),
profile_id: Some(profile_id.clone()),
return_url: Default::default(),
metadata: Default::default(),
connector_id: Default::default(),
shipping_address_id: Default::default(),
billing_address_id: Default::default(),
statement_descriptor_name: Default::default(),
statement_descriptor_suffix: Default::default(),
setup_future_usage: Default::default(),
off_session: Default::default(),
order_details: Default::default(),
allowed_payment_method_types: Default::default(),
connector_metadata: Default::default(),
feature_metadata: Default::default(),
merchant_decision: Default::default(),
payment_link_id: Default::default(),
payment_confirm_source: Default::default(),
updated_by: merchant_from_db.storage_scheme.to_string(),
surcharge_applicable: Default::default(),
request_incremental_authorization: Default::default(),
incremental_authorization_allowed: Default::default(),
authorization_count: Default::default(),
fingerprint_id: None,
session_expiry: Some(session_expiry),
request_external_three_ds_authentication: None,
split_payments: None,
frm_metadata: Default::default(),
customer_details: None,
billing_details: None,
merchant_order_reference_id: Default::default(),
shipping_details: None,
is_payment_processor_token_flow: None,
organization_id: org_id.clone(),
shipping_cost: None,
tax_details: None,
skip_external_tax_calculation: None,
request_extended_authorization: None,
psd2_sca_exemption_type: None,
processor_merchant_id: merchant_id.clone(),
created_by: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
is_iframe_redirection_enabled: None,
is_payment_id_from_merchant: None,
payment_channel: None,
order_date: None,
discount_amount: None,
duty_amount: None,
tax_status: None,
shipping_amount_tax: None,
enable_partial_authorization: None,
enable_overcapture: None,
mit_category: None,
billing_descriptor: None,
tokenization: None,
partner_merchant_identifier_details: None,
};
let (connector_transaction_id, processor_transaction_data) =
ConnectorTransactionId::form_id_and_data(attempt_id.clone());
let payment_attempt = PaymentAttemptBatchNew {
attempt_id: attempt_id.clone(),
payment_id: payment_id.clone(),
connector_transaction_id: Some(connector_transaction_id),
merchant_id: merchant_id.clone(),
status: match is_failed_payment {
true => common_enums::AttemptStatus::Failure,
_ => common_enums::AttemptStatus::Charged,
},
amount: MinorUnit::new(amount * 100),
currency: payment_intent.currency,
connector: Some(
(*connector_vec
.get((num - 1) % connector_vec_len)
.unwrap_or(&DummyConnector4))
.to_string(),
),
payment_method: Some(common_enums::PaymentMethod::Card),
payment_method_type: Some(get_payment_method_type(thread_rng().gen_range(1..=2))),
authentication_type: Some(
*auth_type
.get((num - 1) % auth_type_len)
.unwrap_or(&common_enums::AuthenticationType::NoThreeDs),
),
error_message: match is_failed_payment {
true => Some("This is a test payment which has a failed status".to_string()),
_ => None,
},
error_code: match is_failed_payment {
true => Some("HS001".to_string()),
_ => None,
},
confirm: true,
created_at,
modified_at,
last_synced: Some(last_synced),
amount_to_capture: Some(MinorUnit::new(amount * 100)),
connector_response_reference_id: Some(attempt_id.clone()),
updated_by: merchant_from_db.storage_scheme.to_string(),
save_to_locker: None,
offer_amount: None,
surcharge_amount: None,
tax_amount: None,
payment_method_id: None,
capture_method: None,
capture_on: None,
cancellation_reason: None,
mandate_id: None,
browser_info: None,
payment_token: None,
connector_metadata: None,
payment_experience: None,
payment_method_data: None,
business_sub_label: None,
straight_through_algorithm: None,
preprocessing_step_id: None,
mandate_details: None,
error_reason: None,
multiple_capture_count: None,
amount_capturable: MinorUnit::new(i64::default()),
merchant_connector_id: None,
authentication_data: None,
encoded_data: None,
unified_code: None,
unified_message: None,
net_amount: None,
external_three_ds_authentication_attempted: None,
authentication_connector: None,
authentication_id: None,
mandate_data: None,
payment_method_billing_address_id: None,
fingerprint_id: None,
charge_id: None,
client_source: None,
client_version: None,
customer_acceptance: None,
profile_id: profile_id.clone(),
organization_id: org_id.clone(),
shipping_cost: None,
order_tax_amount: None,
processor_transaction_data,
connector_mandate_detail: None,
request_extended_authorization: None,
extended_authorization_applied: None,
extended_authorization_last_applied_at: None,
capture_before: None,
card_discovery: None,
processor_merchant_id: Some(merchant_id.clone()),
created_by: None,
setup_future_usage_applied: None,
routing_approach: None,
connector_request_reference_id: None,
network_transaction_id: None,
network_details: None,
is_stored_credential: None,
authorized_amount: None,
tokenization: None,
encrypted_payment_method_data: None,
};
let refund = if refunds_count < number_of_refunds && !is_failed_payment {
refunds_count += 1;
let (connector_transaction_id, processor_transaction_data) =
ConnectorTransactionId::form_id_and_data(attempt_id.clone());
Some(RefundNew {
refund_id: common_utils::generate_id_with_default_len("test"),
internal_reference_id: common_utils::generate_id_with_default_len("test"),
external_reference_id: None,
payment_id: payment_id.clone(),
attempt_id: attempt_id.clone(),
merchant_id: merchant_id.clone(),
connector_transaction_id,
connector_refund_id: None,
description: Some("This is a sample refund".to_string()),
created_at,
modified_at,
refund_reason: Some("Sample Refund".to_string()),
connector: payment_attempt
.connector
.clone()
.unwrap_or(DummyConnector4.to_string()),
currency: *currency_vec
.get((num - 1) % currency_vec_len)
.unwrap_or(&common_enums::Currency::USD),
total_amount: MinorUnit::new(amount * 100),
refund_amount: MinorUnit::new(amount * 100),
refund_status: common_enums::RefundStatus::Success,
sent_to_gateway: true,
refund_type: diesel_models::enums::RefundType::InstantRefund,
metadata: None,
refund_arn: None,
profile_id: payment_intent.profile_id.clone(),
updated_by: merchant_from_db.storage_scheme.to_string(),
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
charges: None,
split_refunds: None,
organization_id: org_id.clone(),
processor_refund_data: None,
processor_transaction_data,
})
} else {
None
};
let dispute =
if disputes_count < number_of_disputes && !is_failed_payment && refund.is_none() {
disputes_count += 1;
let currency = payment_intent
.currency
.unwrap_or(common_enums::Currency::USD);
Some(DisputeNew {
dispute_id: common_utils::generate_id_with_default_len("test"),
amount: StringMinorUnitForConnector::convert(
&StringMinorUnitForConnector,
MinorUnit::new(amount * 100),
currency,
)
.change_context(SampleDataError::InternalServerError)?,
currency: currency.to_string(),
dispute_stage: storage_enums::DisputeStage::Dispute,
dispute_status: storage_enums::DisputeStatus::DisputeOpened,
payment_id: payment_id.clone(),
attempt_id: attempt_id.clone(),
merchant_id: merchant_id.clone(),
connector_status: "Sample connector status".into(),
connector_dispute_id: common_utils::generate_id_with_default_len("test"),
connector_reason: Some("Sample Dispute".into()),
connector_reason_code: Some("123".into()),
challenge_required_by: None,
connector_created_at: None,
connector_updated_at: None,
connector: payment_attempt
.connector
.clone()
.unwrap_or(DummyConnector4.to_string()),
evidence: None,
profile_id: payment_intent.profile_id.clone(),
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
dispute_amount: MinorUnit::new(amount * 100),
organization_id: org_id.clone(),
dispute_currency: Some(payment_intent.currency.unwrap_or_default()),
})
} else {
None
};
res.push((payment_intent, payment_attempt, refund, dispute));
}
Ok(res)
}
fn get_payment_method_type(num: u8) -> common_enums::PaymentMethodType {
let rem: u8 = (num) % 2;
match rem {
0 => common_enums::PaymentMethodType::Debit,
_ => common_enums::PaymentMethodType::Credit,
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/utils/user/dashboard_metadata.rs | crates/router/src/utils/user/dashboard_metadata.rs | use std::{net::IpAddr, ops::Not, str::FromStr};
use actix_web::http::header::HeaderMap;
use api_models::user::dashboard_metadata::{
GetMetaDataRequest, GetMultipleMetaDataPayload, ProdIntent, SetMetaDataRequest,
};
use common_utils::id_type;
use diesel_models::{
enums::DashboardMetadata as DBEnum,
user::dashboard_metadata::{DashboardMetadata, DashboardMetadataNew, DashboardMetadataUpdate},
};
use error_stack::{report, ResultExt};
use masking::{ExposeInterface, PeekInterface, Secret};
use router_env::logger;
use crate::{
core::errors::{UserErrors, UserResult},
headers, SessionState,
};
pub async fn insert_merchant_scoped_metadata_to_db(
state: &SessionState,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_key: DBEnum,
metadata_value: impl serde::Serialize,
) -> UserResult<DashboardMetadata> {
let now = common_utils::date_time::now();
let data_value = serde_json::to_value(metadata_value)
.change_context(UserErrors::InternalServerError)
.attach_printable("Error Converting Struct To Serde Value")?;
state
.store
.insert_metadata(DashboardMetadataNew {
user_id: None,
merchant_id,
org_id,
data_key: metadata_key,
data_value: Secret::from(data_value),
created_by: user_id.clone(),
created_at: now,
last_modified_by: user_id,
last_modified_at: now,
})
.await
.map_err(|e| {
if e.current_context().is_db_unique_violation() {
return e.change_context(UserErrors::MetadataAlreadySet);
}
e.change_context(UserErrors::InternalServerError)
})
}
pub async fn insert_user_scoped_metadata_to_db(
state: &SessionState,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_key: DBEnum,
metadata_value: impl serde::Serialize,
) -> UserResult<DashboardMetadata> {
let now = common_utils::date_time::now();
let data_value = serde_json::to_value(metadata_value)
.change_context(UserErrors::InternalServerError)
.attach_printable("Error Converting Struct To Serde Value")?;
state
.store
.insert_metadata(DashboardMetadataNew {
user_id: Some(user_id.clone()),
merchant_id,
org_id,
data_key: metadata_key,
data_value: Secret::from(data_value),
created_by: user_id.clone(),
created_at: now,
last_modified_by: user_id,
last_modified_at: now,
})
.await
.map_err(|e| {
if e.current_context().is_db_unique_violation() {
return e.change_context(UserErrors::MetadataAlreadySet);
}
e.change_context(UserErrors::InternalServerError)
})
}
pub async fn get_merchant_scoped_metadata_from_db(
state: &SessionState,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_keys: Vec<DBEnum>,
) -> UserResult<Vec<DashboardMetadata>> {
state
.store
.find_merchant_scoped_dashboard_metadata(&merchant_id, &org_id, metadata_keys)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("DB Error Fetching DashboardMetaData")
}
pub async fn get_user_scoped_metadata_from_db(
state: &SessionState,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_keys: Vec<DBEnum>,
) -> UserResult<Vec<DashboardMetadata>> {
match state
.store
.find_user_scoped_dashboard_metadata(&user_id, &merchant_id, &org_id, metadata_keys)
.await
{
Ok(data) => Ok(data),
Err(e) => {
if e.current_context().is_db_not_found() {
return Ok(Vec::with_capacity(0));
}
Err(e
.change_context(UserErrors::InternalServerError)
.attach_printable("DB Error Fetching DashboardMetaData"))
}
}
}
pub async fn update_merchant_scoped_metadata(
state: &SessionState,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_key: DBEnum,
metadata_value: impl serde::Serialize,
) -> UserResult<DashboardMetadata> {
let data_value = serde_json::to_value(metadata_value)
.change_context(UserErrors::InternalServerError)
.attach_printable("Error Converting Struct To Serde Value")?;
state
.store
.update_metadata(
None,
merchant_id,
org_id,
metadata_key,
DashboardMetadataUpdate::UpdateData {
data_key: metadata_key,
data_value: Secret::from(data_value),
last_modified_by: user_id,
},
)
.await
.change_context(UserErrors::InternalServerError)
}
pub async fn update_user_scoped_metadata(
state: &SessionState,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_key: DBEnum,
metadata_value: impl serde::Serialize,
) -> UserResult<DashboardMetadata> {
let data_value = serde_json::to_value(metadata_value)
.change_context(UserErrors::InternalServerError)
.attach_printable("Error Converting Struct To Serde Value")?;
state
.store
.update_metadata(
Some(user_id.clone()),
merchant_id,
org_id,
metadata_key,
DashboardMetadataUpdate::UpdateData {
data_key: metadata_key,
data_value: Secret::from(data_value),
last_modified_by: user_id,
},
)
.await
.change_context(UserErrors::InternalServerError)
}
pub fn deserialize_to_response<T>(data: Option<&DashboardMetadata>) -> UserResult<Option<T>>
where
T: serde::de::DeserializeOwned,
{
data.map(|metadata| serde_json::from_value(metadata.data_value.clone().expose()))
.transpose()
.change_context(UserErrors::InternalServerError)
.attach_printable("Error Serializing Metadata from DB")
}
pub fn separate_metadata_type_based_on_scope(
metadata_keys: Vec<DBEnum>,
) -> (Vec<DBEnum>, Vec<DBEnum>) {
let (mut merchant_scoped, mut user_scoped) = (
Vec::with_capacity(metadata_keys.len()),
Vec::with_capacity(metadata_keys.len()),
);
for key in metadata_keys {
match key {
DBEnum::ProductionAgreement
| DBEnum::SetupProcessor
| DBEnum::ConfigureEndpoint
| DBEnum::SetupComplete
| DBEnum::FirstProcessorConnected
| DBEnum::SecondProcessorConnected
| DBEnum::ConfiguredRouting
| DBEnum::TestPayment
| DBEnum::IntegrationMethod
| DBEnum::ConfigurationType
| DBEnum::IntegrationCompleted
| DBEnum::StripeConnected
| DBEnum::PaypalConnected
| DBEnum::SpRoutingConfigured
| DBEnum::SpTestPayment
| DBEnum::DownloadWoocom
| DBEnum::ConfigureWoocom
| DBEnum::SetupWoocomWebhook
| DBEnum::OnboardingSurvey
| DBEnum::IsMultipleConfiguration
| DBEnum::ReconStatus
| DBEnum::ProdIntent => merchant_scoped.push(key),
DBEnum::Feedback | DBEnum::IsChangePasswordRequired => user_scoped.push(key),
}
}
(merchant_scoped, user_scoped)
}
pub fn is_update_required(metadata: &UserResult<DashboardMetadata>) -> bool {
match metadata {
Ok(_) => false,
Err(e) => matches!(e.current_context(), UserErrors::MetadataAlreadySet),
}
}
pub fn is_backfill_required(metadata_key: DBEnum) -> bool {
matches!(
metadata_key,
DBEnum::StripeConnected | DBEnum::PaypalConnected
)
}
pub fn set_ip_address_if_required(
request: &mut SetMetaDataRequest,
headers: &HeaderMap,
) -> UserResult<()> {
if let SetMetaDataRequest::ProductionAgreement(req) = request {
let ip_address_from_request: Secret<String, common_utils::pii::IpAddress> = headers
.get(headers::X_FORWARDED_FOR)
.ok_or(report!(UserErrors::IpAddressParsingFailed))
.attach_printable("X-Forwarded-For header not found")?
.to_str()
.change_context(UserErrors::IpAddressParsingFailed)
.attach_printable("Error converting Header Value to Str")?
.split(',')
.next()
.and_then(|ip| {
let ip_addr: Result<IpAddr, _> = ip.parse();
ip_addr.ok()
})
.ok_or(report!(UserErrors::IpAddressParsingFailed))
.attach_printable("Error Parsing header value to ip")?
.to_string()
.into();
req.ip_address = Some(ip_address_from_request)
}
Ok(())
}
pub fn parse_string_to_enums(query: String) -> UserResult<GetMultipleMetaDataPayload> {
Ok(GetMultipleMetaDataPayload {
results: query
.split(',')
.map(GetMetaDataRequest::from_str)
.collect::<Result<Vec<GetMetaDataRequest>, _>>()
.change_context(UserErrors::InvalidMetadataRequest)
.attach_printable("Error Parsing to DashboardMetadata enums")?,
})
}
fn not_contains_string(value: Option<&str>, value_to_be_checked: &str) -> bool {
value.is_some_and(|mail| !mail.contains(value_to_be_checked))
}
pub fn is_prod_email_required(data: &ProdIntent, user_email: String) -> bool {
let poc_email_check = not_contains_string(
data.poc_email.as_ref().map(|email| email.peek().as_str()),
"juspay",
);
let business_website_check =
not_contains_string(data.business_website.as_ref().map(|s| s.as_str()), "juspay")
&& not_contains_string(
data.business_website.as_ref().map(|s| s.as_str()),
"hyperswitch",
);
let user_email_check = not_contains_string(Some(&user_email), "juspay");
if (poc_email_check && business_website_check && user_email_check).not() {
logger::info!(prod_intent_email = poc_email_check);
logger::info!(prod_intent_email = business_website_check);
logger::info!(prod_intent_email = user_email_check);
}
poc_email_check && business_website_check && user_email_check
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/utils/connector_onboarding/paypal.rs | crates/router/src/utils/connector_onboarding/paypal.rs | use common_utils::request::{Method, Request, RequestBuilder, RequestContent};
use error_stack::ResultExt;
use http::header;
use crate::{
connector,
core::errors::{ApiErrorResponse, RouterResult},
routes::SessionState,
types,
types::api::{
enums,
verify_connector::{self as verify_connector_types, VerifyConnector},
},
utils::verify_connector as verify_connector_utils,
};
pub async fn generate_access_token(state: SessionState) -> RouterResult<types::AccessToken> {
let connector = enums::Connector::Paypal;
let boxed_connector =
types::api::ConnectorData::convert_connector(connector.to_string().as_str())?;
let connector_auth =
super::get_connector_auth(connector, state.conf.connector_onboarding.get_inner())?;
connector::Paypal::get_access_token(
&state,
verify_connector_types::VerifyConnectorData {
connector: boxed_connector,
connector_auth,
card_details: verify_connector_utils::get_test_card_details(connector)?.ok_or(
ApiErrorResponse::FlowNotSupported {
flow: "Connector onboarding".to_string(),
connector: connector.to_string(),
},
)?,
},
)
.await?
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Error occurred while retrieving access token")
}
pub fn build_paypal_post_request<T>(
url: String,
body: T,
access_token: String,
) -> RouterResult<Request>
where
T: serde::Serialize + Send + 'static,
{
Ok(RequestBuilder::new()
.method(Method::Post)
.url(&url)
.attach_default_headers()
.header(
header::AUTHORIZATION.to_string().as_str(),
format!("Bearer {access_token}").as_str(),
)
.header(
header::CONTENT_TYPE.to_string().as_str(),
"application/json",
)
.set_body(RequestContent::Json(Box::new(body)))
.build())
}
pub fn build_paypal_get_request(url: String, access_token: String) -> RouterResult<Request> {
Ok(RequestBuilder::new()
.method(Method::Get)
.url(&url)
.attach_default_headers()
.header(
header::AUTHORIZATION.to_string().as_str(),
format!("Bearer {access_token}").as_str(),
)
.build())
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/bin/router.rs | crates/router/src/bin/router.rs | use error_stack::ResultExt;
use router::{
configs::settings::{CmdLineConf, Settings},
core::errors::{ApplicationError, ApplicationResult},
logger,
routes::metrics,
};
#[tokio::main]
async fn main() -> ApplicationResult<()> {
// get commandline config before initializing config
let cmd_line = <CmdLineConf as clap::Parser>::parse();
#[allow(clippy::expect_used)]
let conf = Settings::with_config_path(cmd_line.config_path)
.expect("Unable to construct application configuration");
#[allow(clippy::expect_used)]
conf.validate()
.expect("Failed to validate router configuration");
#[allow(clippy::print_stdout)] // The logger has not yet been initialized
#[cfg(feature = "vergen")]
{
println!("Starting router (Version: {})", router_env::git_tag!());
}
let _guard = router_env::setup(
&conf.log,
router_env::service_name!(),
[router_env::service_name!(), "actix_server"],
)
.change_context(ApplicationError::ConfigurationError)?;
logger::info!("Application started [{:?}] [{:?}]", conf.server, conf.log);
// Spawn a thread for collecting metrics at fixed intervals
metrics::bg_metrics_collector::spawn_metrics_collector(
conf.log.telemetry.bg_metrics_collection_interval_in_secs,
);
#[allow(clippy::expect_used)]
let server = Box::pin(router::start_server(conf))
.await
.expect("Failed to create the server");
let _ = server.await;
Err(error_stack::Report::from(ApplicationError::from(
std::io::Error::other("Server shut down"),
)))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/bin/scheduler.rs | crates/router/src/bin/scheduler.rs | use std::{collections::HashMap, str::FromStr, sync::Arc};
use actix_web::{dev::Server, web, Scope};
use api_models::health_check::SchedulerHealthCheckResponse;
use common_utils::ext_traits::{OptionExt, StringExt};
use diesel_models::process_tracker::{self as storage, business_status};
use error_stack::ResultExt;
use router::{
configs::settings::{CmdLineConf, Settings},
core::{
errors::{self, CustomResult},
health_check::HealthCheckInterface,
},
logger, routes,
services::{self, api},
workflows,
};
use router_env::{
instrument,
tracing::{self, Instrument},
};
use scheduler::{
consumer::workflows::ProcessTrackerWorkflow, errors::ProcessTrackerError,
workflows::ProcessTrackerWorkflows, SchedulerSessionState,
};
use storage_impl::errors::ApplicationError;
use tokio::sync::{mpsc, oneshot};
const SCHEDULER_FLOW: &str = "SCHEDULER_FLOW";
#[tokio::main]
async fn main() -> CustomResult<(), ProcessTrackerError> {
let cmd_line = <CmdLineConf as clap::Parser>::parse();
#[allow(clippy::expect_used)]
let conf = Settings::with_config_path(cmd_line.config_path)
.expect("Unable to construct application configuration");
let api_client = Box::new(
services::ProxyClient::new(&conf.proxy)
.change_context(ProcessTrackerError::ConfigurationError)?,
);
// channel for listening to redis disconnect events
let (redis_shutdown_signal_tx, redis_shutdown_signal_rx) = oneshot::channel();
let state = Box::pin(routes::AppState::new(
conf,
redis_shutdown_signal_tx,
api_client,
))
.await;
// channel to shutdown scheduler gracefully
let (tx, rx) = mpsc::channel(1);
let _task_handle = tokio::spawn(
router::receiver_for_error(redis_shutdown_signal_rx, tx.clone()).in_current_span(),
);
#[allow(clippy::expect_used)]
let scheduler_flow_str =
std::env::var(SCHEDULER_FLOW).expect("SCHEDULER_FLOW environment variable not set");
#[allow(clippy::expect_used)]
let scheduler_flow = scheduler::SchedulerFlow::from_str(&scheduler_flow_str)
.expect("Unable to parse SchedulerFlow from environment variable");
#[allow(clippy::print_stdout)] // The logger has not yet been initialized
#[cfg(feature = "vergen")]
{
println!(
"Starting {scheduler_flow} (Version: {})",
router_env::git_tag!()
);
}
let _guard = router_env::setup(
&state.conf.log,
&scheduler_flow_str,
[router_env::service_name!()],
);
#[allow(clippy::expect_used)]
let web_server = Box::pin(start_web_server(
state.clone(),
scheduler_flow_str.to_string(),
))
.await
.expect("Failed to create the server");
let _task_handle = tokio::spawn(
async move {
let _ = web_server.await;
logger::error!("The health check probe stopped working!");
}
.in_current_span(),
);
logger::debug!(startup_config=?state.conf);
start_scheduler(&state, scheduler_flow, (tx, rx)).await?;
logger::error!("Scheduler shut down");
Ok(())
}
pub async fn start_web_server(
state: routes::AppState,
service: String,
) -> errors::ApplicationResult<Server> {
let server = state
.conf
.scheduler
.as_ref()
.ok_or(ApplicationError::InvalidConfigurationValueError(
"Scheduler server is invalidly configured".into(),
))?
.server
.clone();
let web_server = actix_web::HttpServer::new(move || {
actix_web::App::new().service(Health::server(state.clone(), service.clone()))
})
.bind((server.host.as_str(), server.port))
.change_context(ApplicationError::ConfigurationError)?
.workers(server.workers)
.run();
let _ = web_server.handle();
Ok(web_server)
}
pub struct Health;
impl Health {
pub fn server(state: routes::AppState, service: String) -> Scope {
web::scope("health")
.app_data(web::Data::new(state))
.app_data(web::Data::new(service))
.service(web::resource("").route(web::get().to(health)))
.service(web::resource("/ready").route(web::get().to(deep_health_check)))
}
}
#[instrument(skip_all)]
pub async fn health() -> impl actix_web::Responder {
logger::info!("Scheduler health was called");
actix_web::HttpResponse::Ok().body("Scheduler health is good")
}
#[instrument(skip_all)]
pub async fn deep_health_check(
state: web::Data<routes::AppState>,
service: web::Data<String>,
) -> impl actix_web::Responder {
let mut checks = HashMap::new();
let stores = state.stores.clone();
let app_state = Arc::clone(&state.into_inner());
let service_name = service.into_inner();
for (tenant, _) in stores {
let session_state_res = app_state.clone().get_session_state(&tenant, None, || {
errors::ApiErrorResponse::MissingRequiredField {
field_name: "tenant_id",
}
.into()
});
let session_state = match session_state_res {
Ok(state) => state,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let report = deep_health_check_func(session_state, &service_name).await;
match report {
Ok(response) => {
checks.insert(
tenant,
serde_json::to_string(&response)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
);
}
Err(err) => {
return api::log_and_return_error_response(err);
}
}
}
services::http_response_json(
serde_json::to_string(&checks)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
)
}
#[instrument(skip_all)]
pub async fn deep_health_check_func(
state: routes::SessionState,
service: &str,
) -> errors::RouterResult<SchedulerHealthCheckResponse> {
logger::info!("{} deep health check was called", service);
logger::debug!("Database health check begin");
let db_status = state
.health_check_db()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Database",
message,
})
})?;
logger::debug!("Database health check end");
logger::debug!("Redis health check begin");
let redis_status = state
.health_check_redis()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Redis",
message,
})
})?;
let outgoing_req_check =
state
.health_check_outgoing()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Outgoing Request",
message,
})
})?;
logger::debug!("Redis health check end");
let response = SchedulerHealthCheckResponse {
database: db_status,
redis: redis_status,
outgoing_request: outgoing_req_check,
};
Ok(response)
}
#[derive(Debug, Copy, Clone)]
pub struct WorkflowRunner;
#[async_trait::async_trait]
impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
async fn trigger_workflow<'a>(
&'a self,
state: &'a routes::SessionState,
process: storage::ProcessTracker,
) -> CustomResult<(), ProcessTrackerError> {
let runner = process
.runner
.clone()
.get_required_value("runner")
.change_context(ProcessTrackerError::MissingRequiredField)
.attach_printable("Missing runner field in process information")?;
let runner: storage::ProcessTrackerRunner = runner
.parse_enum("ProcessTrackerRunner")
.change_context(ProcessTrackerError::UnexpectedFlow)
.attach_printable("Failed to parse workflow runner name")?;
let get_operation = |runner: storage::ProcessTrackerRunner| -> CustomResult<
Box<dyn ProcessTrackerWorkflow<routes::SessionState>>,
ProcessTrackerError,
> {
match runner {
storage::ProcessTrackerRunner::PaymentsSyncWorkflow => {
Ok(Box::new(workflows::payment_sync::PaymentsSyncWorkflow))
}
storage::ProcessTrackerRunner::RefundWorkflowRouter => {
Ok(Box::new(workflows::refund_router::RefundWorkflowRouter))
}
storage::ProcessTrackerRunner::ProcessDisputeWorkflow => {
Ok(Box::new(workflows::process_dispute::ProcessDisputeWorkflow))
}
storage::ProcessTrackerRunner::DisputeListWorkflow => {
Ok(Box::new(workflows::dispute_list::DisputeListWorkflow))
}
storage::ProcessTrackerRunner::InvoiceSyncflow => {
Ok(Box::new(workflows::invoice_sync::InvoiceSyncWorkflow))
}
storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow => Ok(Box::new(
workflows::tokenized_data::DeleteTokenizeDataWorkflow,
)),
storage::ProcessTrackerRunner::ApiKeyExpiryWorkflow => {
#[cfg(feature = "email")]
{
Ok(Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow))
}
#[cfg(not(feature = "email"))]
{
Err(error_stack::report!(ProcessTrackerError::UnexpectedFlow))
.attach_printable(
"Cannot run API key expiry workflow when email feature is disabled",
)
}
}
storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow => Ok(Box::new(
workflows::outgoing_webhook_retry::OutgoingWebhookRetryWorkflow,
)),
storage::ProcessTrackerRunner::AttachPayoutAccountWorkflow => {
#[cfg(feature = "payouts")]
{
Ok(Box::new(
workflows::attach_payout_account_workflow::AttachPayoutAccountWorkflow,
))
}
#[cfg(not(feature = "payouts"))]
{
Err(
error_stack::report!(ProcessTrackerError::UnexpectedFlow),
)
.attach_printable(
"Cannot run Stripe external account workflow when payouts feature is disabled",
)
}
}
storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow => Ok(Box::new(
workflows::payment_method_status_update::PaymentMethodStatusUpdateWorkflow,
)),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow => {
Ok(Box::new(workflows::revenue_recovery::ExecutePcrWorkflow))
}
}
};
let operation = get_operation(runner)?;
let app_state = &state.clone();
let output = operation.execute_workflow(state, process.clone()).await;
match output {
Ok(_) => operation.success_handler(app_state, process).await,
Err(error) => match operation
.error_handler(app_state, process.clone(), error)
.await
{
Ok(_) => (),
Err(error) => {
logger::error!(?error, "Failed while handling error");
let status = state
.get_db()
.as_scheduler()
.finish_process_with_business_status(
process,
business_status::GLOBAL_FAILURE,
)
.await;
if let Err(error) = status {
logger::error!(
?error,
"Failed while performing database operation: {}",
business_status::GLOBAL_FAILURE
);
}
}
},
};
Ok(())
}
}
async fn start_scheduler(
state: &routes::AppState,
scheduler_flow: scheduler::SchedulerFlow,
channel: (mpsc::Sender<()>, mpsc::Receiver<()>),
) -> CustomResult<(), ProcessTrackerError> {
let scheduler_settings = state
.conf
.scheduler
.clone()
.ok_or(ProcessTrackerError::ConfigurationError)?;
scheduler::start_process_tracker(
state,
scheduler_flow,
Arc::new(scheduler_settings),
channel,
WorkflowRunner {},
|state, tenant| {
Arc::new(state.clone())
.get_session_state(tenant, None, || ProcessTrackerError::TenantNotFound.into())
},
)
.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/fraud_check.rs | crates/router/src/types/fraud_check.rs | pub use hyperswitch_domain_models::{
router_request_types::fraud_check::{
FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
FraudCheckSaleData, FraudCheckTransactionData, RefundMethod,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
use crate::{
services,
types::{api, ErrorResponse, RouterData},
};
pub type FrmSaleRouterData = RouterData<api::Sale, FraudCheckSaleData, FraudCheckResponseData>;
pub type FrmSaleType =
dyn services::ConnectorIntegration<api::Sale, FraudCheckSaleData, FraudCheckResponseData>;
#[derive(Debug, Clone)]
pub struct FrmRouterData {
pub merchant_id: common_utils::id_type::MerchantId,
pub connector: String,
// TODO: change this to PaymentId type
pub payment_id: String,
pub attempt_id: String,
pub request: FrmRequest,
pub response: FrmResponse,
}
#[derive(Debug, Clone)]
pub enum FrmRequest {
Sale(FraudCheckSaleData),
Checkout(Box<FraudCheckCheckoutData>),
Transaction(FraudCheckTransactionData),
Fulfillment(FraudCheckFulfillmentData),
RecordReturn(FraudCheckRecordReturnData),
}
#[derive(Debug, Clone)]
pub enum FrmResponse {
Sale(Result<FraudCheckResponseData, ErrorResponse>),
Checkout(Result<FraudCheckResponseData, ErrorResponse>),
Transaction(Result<FraudCheckResponseData, ErrorResponse>),
Fulfillment(Result<FraudCheckResponseData, ErrorResponse>),
RecordReturn(Result<FraudCheckResponseData, ErrorResponse>),
}
pub type FrmCheckoutRouterData =
RouterData<api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>;
pub type FrmCheckoutType = dyn services::ConnectorIntegration<
api::Checkout,
FraudCheckCheckoutData,
FraudCheckResponseData,
>;
pub type FrmTransactionRouterData =
RouterData<api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>;
pub type FrmTransactionType = dyn services::ConnectorIntegration<
api::Transaction,
FraudCheckTransactionData,
FraudCheckResponseData,
>;
pub type FrmFulfillmentRouterData =
RouterData<api::Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>;
pub type FrmFulfillmentType = dyn services::ConnectorIntegration<
api::Fulfillment,
FraudCheckFulfillmentData,
FraudCheckResponseData,
>;
pub type FrmRecordReturnRouterData =
RouterData<api::RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>;
pub type FrmRecordReturnType = dyn services::ConnectorIntegration<
api::RecordReturn,
FraudCheckRecordReturnData,
FraudCheckResponseData,
>;
| 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/pm_auth.rs | crates/router/src/types/pm_auth.rs | use std::str::FromStr;
use error_stack::ResultExt;
use pm_auth::{
connector::plaid,
types::{
self as pm_auth_types,
api::{BoxedPaymentAuthConnector, PaymentAuthConnectorData},
},
};
use crate::core::{
errors::{self, ApiErrorResponse},
pm_auth::helpers::PaymentAuthConnectorDataExt,
};
impl PaymentAuthConnectorDataExt for PaymentAuthConnectorData {
fn get_connector_by_name(name: &str) -> errors::CustomResult<Self, ApiErrorResponse> {
let connector_name = pm_auth_types::PaymentMethodAuthConnectors::from_str(name)
.change_context(ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| {
format!("unable to parse connector: {:?}", name.to_string())
})?;
let connector = Self::convert_connector(connector_name.clone())?;
Ok(Self {
connector,
connector_name,
})
}
fn convert_connector(
connector_name: pm_auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<BoxedPaymentAuthConnector, ApiErrorResponse> {
match connector_name {
pm_auth_types::PaymentMethodAuthConnectors::Plaid => Ok(Box::new(&plaid::Plaid)),
}
}
}
| 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.rs | crates/router/src/types/storage.rs | pub mod address;
pub mod api_keys;
pub mod authentication;
pub mod authorization;
pub mod blocklist;
pub mod blocklist_fingerprint;
pub mod blocklist_lookup;
pub mod business_profile;
pub mod callback_mapper;
pub mod capture;
pub mod cards_info;
pub mod configs;
pub mod customers;
pub mod dashboard_metadata;
pub mod dispute;
pub mod dynamic_routing_stats;
pub mod enums;
pub mod ephemeral_key;
pub mod events;
pub mod file;
pub mod fraud_check;
pub mod generic_link;
pub mod gsm;
pub mod hyperswitch_ai_interaction;
#[cfg(feature = "kv_store")]
pub mod kv;
pub mod locker_mock_up;
pub mod mandate;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_key_store;
pub mod payment_attempt;
pub mod payment_link;
pub mod payment_method;
pub mod payout_attempt;
pub mod payouts;
pub mod refund;
#[cfg(feature = "v2")]
pub mod revenue_recovery;
#[cfg(feature = "v2")]
pub mod revenue_recovery_redis_operation;
pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
pub mod unified_translations;
pub mod user;
pub mod user_authentication_method;
pub mod user_role;
pub use diesel_models::{
process_tracker::business_status, ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner,
ProcessTrackerUpdate,
};
#[cfg(feature = "payouts")]
pub use hyperswitch_domain_models::payouts::{
payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate},
payouts::{Payouts, PayoutsNew, PayoutsUpdate},
};
pub use hyperswitch_domain_models::{
payments::{
payment_attempt::{PaymentAttempt, PaymentAttemptUpdate},
payment_intent::{PaymentIntentUpdate, PaymentIntentUpdateFields},
PaymentIntent,
},
routing::{
PaymentRoutingInfo, PaymentRoutingInfoInner, PreRoutingConnectorChoice, RoutingData,
},
};
pub use scheduler::db::process_tracker;
pub use self::{
address::*, api_keys::*, authentication::*, authorization::*, blocklist::*,
blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, callback_mapper::*,
capture::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*, dispute::*,
dynamic_routing_stats::*, ephemeral_key::*, events::*, file::*, fraud_check::*,
generic_link::*, gsm::*, hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*,
merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*,
payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*,
routing_algorithm::*, unified_translations::*, user::*, user_authentication_method::*,
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/api.rs | crates/router/src/types/api.rs | pub mod admin;
pub mod api_keys;
pub mod authentication;
pub mod configs;
#[cfg(feature = "olap")]
pub mod connector_onboarding;
pub mod customers;
pub mod disputes;
pub mod enums;
pub mod ephemeral_key;
pub mod files;
#[cfg(feature = "frm")]
pub mod fraud_check;
pub mod mandates;
pub mod payment_link;
pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod poll;
pub mod refunds;
pub mod routing;
#[cfg(feature = "olap")]
pub mod verify_connector;
#[cfg(feature = "olap")]
pub mod webhook_events;
pub mod webhooks;
pub mod authentication_v2;
pub mod connector_mapping;
pub mod disputes_v2;
pub mod feature_matrix;
pub mod files_v2;
#[cfg(feature = "frm")]
pub mod fraud_check_v2;
pub mod payments_v2;
#[cfg(feature = "payouts")]
pub mod payouts_v2;
pub mod refunds_v2;
use std::{fmt::Debug, str::FromStr};
use api_models::routing::{self as api_routing, RoutableConnectorChoice};
use error_stack::ResultExt;
use euclid::enums::RoutableConnectors;
pub use hyperswitch_domain_models::router_flow_types::{
access_token_auth::{AccessTokenAuth, AccessTokenAuthentication},
mandate_revoke::MandateRevoke,
unified_authentication_service::*,
webhooks::VerifyWebhookSource,
};
pub use hyperswitch_interfaces::{
api::{
authentication::{
ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication,
ConnectorPreAuthenticationVersionCall, ExternalAuthentication,
},
authentication_v2::{
ConnectorAuthenticationV2, ConnectorPostAuthenticationV2, ConnectorPreAuthenticationV2,
ConnectorPreAuthenticationVersionCallV2, ExternalAuthenticationV2,
},
fraud_check::FraudCheck,
revenue_recovery::{
BillingConnectorInvoiceSyncIntegration, BillingConnectorPaymentsSyncIntegration,
RevenueRecovery, RevenueRecoveryRecordBack,
},
revenue_recovery_v2::RevenueRecoveryV2,
BoxedConnector, Connector, ConnectorAccessToken, ConnectorAccessTokenV2,
ConnectorAuthenticationToken, ConnectorAuthenticationTokenV2, ConnectorCommon,
ConnectorCommonExt, ConnectorMandateRevoke, ConnectorMandateRevokeV2,
ConnectorTransactionId, ConnectorVerifyWebhookSource, ConnectorVerifyWebhookSourceV2,
CurrencyUnit,
},
connector_integration_v2::{BoxedConnectorV2, ConnectorV2},
};
use rustc_hash::FxHashMap;
#[cfg(feature = "frm")]
pub use self::fraud_check::*;
#[cfg(feature = "payouts")]
pub use self::payouts::*;
pub use self::{
admin::*, api_keys::*, authentication::*, configs::*, connector_mapping::*, customers::*,
disputes::*, files::*, payment_link::*, payment_methods::*, payments::*, poll::*, refunds::*,
refunds_v2::*, webhooks::*,
};
use super::transformers::ForeignTryFrom;
use crate::{
connector, consts,
core::{
errors::{self, CustomResult},
payments::types as payments_types,
},
services::connector_integration_interface::ConnectorEnum,
types::{self, api::enums as api_enums},
};
#[derive(Clone)]
pub enum ConnectorCallType {
PreDetermined(ConnectorRoutingData),
Retryable(Vec<ConnectorRoutingData>),
SessionMultiple(SessionConnectorDatas),
#[cfg(feature = "v2")]
Skip,
}
impl From<ConnectorData> for ConnectorRoutingData {
fn from(connector_data: ConnectorData) -> Self {
Self {
connector_data,
network: None,
action_type: None,
}
}
}
#[derive(Clone, Debug)]
pub struct SessionConnectorData {
pub payment_method_sub_type: api_enums::PaymentMethodType,
pub payment_method_type: api_enums::PaymentMethod,
pub connector: ConnectorData,
pub business_sub_label: Option<String>,
}
impl SessionConnectorData {
pub fn new(
payment_method_sub_type: api_enums::PaymentMethodType,
connector: ConnectorData,
business_sub_label: Option<String>,
payment_method_type: api_enums::PaymentMethod,
) -> Self {
Self {
payment_method_sub_type,
connector,
business_sub_label,
payment_method_type,
}
}
}
common_utils::create_list_wrapper!(
SessionConnectorDatas,
SessionConnectorData,
impl_functions: {
pub fn apply_filter_for_session_routing(&self) -> Self {
let routing_enabled_pmts = &consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES;
let routing_enabled_pms = &consts::ROUTING_ENABLED_PAYMENT_METHODS;
self
.iter()
.filter(|connector_data| {
routing_enabled_pmts.contains(&connector_data.payment_method_sub_type)
|| routing_enabled_pms.contains(&connector_data.payment_method_type)
})
.cloned()
.collect()
}
pub fn filter_and_validate_for_session_flow(self, routing_results: &FxHashMap<api_enums::PaymentMethodType, Vec<routing::SessionRoutingChoice>>) -> Result<Self, errors::ApiErrorResponse> {
let mut final_list = Self::new(Vec::new());
let routing_enabled_pmts = &consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES;
for connector_data in self {
if !routing_enabled_pmts.contains(&connector_data.payment_method_sub_type) {
final_list.push(connector_data);
} else if let Some(choice) = routing_results.get(&connector_data.payment_method_sub_type) {
let routing_choice = choice
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
if connector_data.connector.connector_name == routing_choice.connector.connector_name
&& connector_data.connector.merchant_connector_id
== routing_choice.connector.merchant_connector_id
{
final_list.push(connector_data);
}
}
}
Ok(final_list)
}
}
);
pub fn convert_connector_data_to_routable_connectors(
connectors: &[ConnectorRoutingData],
) -> CustomResult<Vec<RoutableConnectorChoice>, common_utils::errors::ValidationError> {
connectors
.iter()
.map(|connectors_routing_data| {
RoutableConnectorChoice::foreign_try_from(
connectors_routing_data.connector_data.clone(),
)
})
.collect()
}
impl ForeignTryFrom<ConnectorData> for RoutableConnectorChoice {
type Error = error_stack::Report<common_utils::errors::ValidationError>;
fn foreign_try_from(from: ConnectorData) -> Result<Self, Self::Error> {
match RoutableConnectors::foreign_try_from(from.connector_name) {
Ok(connector) => Ok(Self {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector,
merchant_connector_id: from.merchant_connector_id,
}),
Err(e) => Err(common_utils::errors::ValidationError::InvalidValue {
message: format!("This is not a routable connector: {e:?}"),
})?,
}
}
}
/// Session Surcharge type
pub enum SessionSurchargeDetails {
/// Surcharge is calculated by hyperswitch
Calculated(payments_types::SurchargeMetadata),
/// Surcharge is sent by merchant
PreDetermined(payments_types::SurchargeDetails),
}
impl SessionSurchargeDetails {
pub fn fetch_surcharge_details(
&self,
payment_method: enums::PaymentMethod,
payment_method_type: enums::PaymentMethodType,
card_network: Option<&enums::CardNetwork>,
) -> Option<payments_types::SurchargeDetails> {
match self {
Self::Calculated(surcharge_metadata) => surcharge_metadata
.get_surcharge_details(payments_types::SurchargeKey::PaymentMethodData(
payment_method,
payment_method_type,
card_network.cloned(),
))
.cloned(),
Self::PreDetermined(surcharge_details) => Some(surcharge_details.clone()),
}
}
}
pub enum ConnectorChoice {
SessionMultiple(SessionConnectorDatas),
StraightThrough(serde_json::Value),
Decide,
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_convert_connector_parsing_success() {
let result = enums::Connector::from_str("aci");
assert!(result.is_ok());
assert_eq!(result.unwrap(), enums::Connector::Aci);
let result = enums::Connector::from_str("shift4");
assert!(result.is_ok());
assert_eq!(result.unwrap(), enums::Connector::Shift4);
let result = enums::Connector::from_str("authorizedotnet");
assert!(result.is_ok());
assert_eq!(result.unwrap(), enums::Connector::Authorizedotnet);
}
#[test]
fn test_convert_connector_parsing_fail_for_unknown_type() {
let result = enums::Connector::from_str("unknowntype");
assert!(result.is_err());
let result = enums::Connector::from_str("randomstring");
assert!(result.is_err());
}
#[test]
fn test_convert_connector_parsing_fail_for_camel_case() {
let result = enums::Connector::from_str("Paypal");
assert!(result.is_err());
let result = enums::Connector::from_str("Authorizedotnet");
assert!(result.is_err());
let result = enums::Connector::from_str("Opennode");
assert!(result.is_err());
}
}
#[derive(Clone)]
pub struct TaxCalculateConnectorData {
pub connector: ConnectorEnum,
pub connector_name: enums::TaxConnectors,
}
impl TaxCalculateConnectorData {
pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector_name = enums::TaxConnectors::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::TaxConnectors,
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match connector_name {
enums::TaxConnectors::Taxjar => {
Ok(ConnectorEnum::Old(Box::new(connector::Taxjar::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/connector_transformers.rs | crates/router/src/types/connector_transformers.rs | use api_models::enums as api_enums;
use super::ForeignTryFrom;
impl ForeignTryFrom<api_enums::Connector> for euclid::enums::RoutableConnectors {
type Error = error_stack::Report<common_utils::errors::ValidationError>;
fn foreign_try_from(from: api_enums::Connector) -> Result<Self, Self::Error> {
Ok(match from {
api_enums::Connector::Aci => Self::Aci,
api_enums::Connector::Adyen => Self::Adyen,
api_enums::Connector::Affirm => Self::Affirm,
api_enums::Connector::Adyenplatform => Self::Adyenplatform,
api_enums::Connector::Airwallex => Self::Airwallex,
api_enums::Connector::Amazonpay => Self::Amazonpay,
api_enums::Connector::Archipel => Self::Archipel,
api_enums::Connector::Authipay => Self::Authipay,
api_enums::Connector::Authorizedotnet => Self::Authorizedotnet,
api_enums::Connector::Bambora => Self::Bambora,
api_enums::Connector::Bamboraapac => Self::Bamboraapac,
api_enums::Connector::Bankofamerica => Self::Bankofamerica,
api_enums::Connector::Barclaycard => Self::Barclaycard,
api_enums::Connector::Billwerk => Self::Billwerk,
api_enums::Connector::Bitpay => Self::Bitpay,
api_enums::Connector::Bluesnap => Self::Bluesnap,
api_enums::Connector::Blackhawknetwork => Self::Blackhawknetwork,
api_enums::Connector::Calida => Self::Calida,
api_enums::Connector::Boku => Self::Boku,
api_enums::Connector::Braintree => Self::Braintree,
api_enums::Connector::Breadpay => Self::Breadpay,
api_enums::Connector::Cardinal => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "cardinal is not a routable connector".to_string(),
})?
}
api_enums::Connector::Cashtocode => Self::Cashtocode,
api_enums::Connector::Celero => Self::Celero,
api_enums::Connector::Chargebee => Self::Chargebee,
api_enums::Connector::Checkbook => Self::Checkbook,
api_enums::Connector::Checkout => Self::Checkout,
api_enums::Connector::Coinbase => Self::Coinbase,
api_enums::Connector::Coingate => Self::Coingate,
api_enums::Connector::Cryptopay => Self::Cryptopay,
api_enums::Connector::Custombilling => Self::Custombilling,
api_enums::Connector::CtpVisa => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "ctp visa is not a routable connector".to_string(),
})?
}
api_enums::Connector::CtpMastercard => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "ctp mastercard is not a routable connector".to_string(),
})?
}
api_enums::Connector::Cybersource => Self::Cybersource,
api_enums::Connector::Datatrans => Self::Datatrans,
api_enums::Connector::Deutschebank => Self::Deutschebank,
api_enums::Connector::Digitalvirgo => Self::Digitalvirgo,
api_enums::Connector::Dlocal => Self::Dlocal,
api_enums::Connector::Dwolla => Self::Dwolla,
api_enums::Connector::Ebanx => Self::Ebanx,
api_enums::Connector::Elavon => Self::Elavon,
api_enums::Connector::Facilitapay => Self::Facilitapay,
api_enums::Connector::Finix => Self::Finix,
api_enums::Connector::Fiserv => Self::Fiserv,
api_enums::Connector::Fiservemea => Self::Fiservemea,
api_enums::Connector::Fiuu => Self::Fiuu,
api_enums::Connector::Flexiti => Self::Flexiti,
api_enums::Connector::Forte => Self::Forte,
api_enums::Connector::Getnet => Self::Getnet,
api_enums::Connector::Gigadat => Self::Gigadat,
api_enums::Connector::Globalpay => Self::Globalpay,
api_enums::Connector::Globepay => Self::Globepay,
api_enums::Connector::Gocardless => Self::Gocardless,
api_enums::Connector::Gpayments => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "gpayments is not a routable connector".to_string(),
})?
}
api_enums::Connector::Hipay => Self::Hipay,
api_enums::Connector::Helcim => Self::Helcim,
api_enums::Connector::HyperswitchVault => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "Hyperswitch Vault is not a routable connector".to_string(),
})?
}
api_enums::Connector::Iatapay => Self::Iatapay,
api_enums::Connector::Inespay => Self::Inespay,
api_enums::Connector::Itaubank => Self::Itaubank,
api_enums::Connector::Jpmorgan => Self::Jpmorgan,
api_enums::Connector::Juspaythreedsserver => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "juspaythreedsserver is not a routable connector".to_string(),
})?
}
api_enums::Connector::Klarna => Self::Klarna,
api_enums::Connector::Loonio => Self::Loonio,
api_enums::Connector::Mifinity => Self::Mifinity,
api_enums::Connector::Mollie => Self::Mollie,
api_enums::Connector::Moneris => Self::Moneris,
api_enums::Connector::Multisafepay => Self::Multisafepay,
api_enums::Connector::Netcetera => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "netcetera is not a routable connector".to_string(),
})?
}
api_enums::Connector::Nexinets => Self::Nexinets,
api_enums::Connector::Nexixpay => Self::Nexixpay,
api_enums::Connector::Nmi => Self::Nmi,
api_enums::Connector::Nomupay => Self::Nomupay,
api_enums::Connector::Noon => Self::Noon,
api_enums::Connector::Nordea => Self::Nordea,
api_enums::Connector::Novalnet => Self::Novalnet,
api_enums::Connector::Nuvei => Self::Nuvei,
api_enums::Connector::Opennode => Self::Opennode,
api_enums::Connector::Paybox => Self::Paybox,
api_enums::Connector::Payjustnow => Self::Payjustnow,
api_enums::Connector::Payjustnowinstore => Self::Payjustnowinstore,
api_enums::Connector::Payload => Self::Payload,
api_enums::Connector::Payme => Self::Payme,
api_enums::Connector::Payone => Self::Payone,
api_enums::Connector::Paypal => Self::Paypal,
api_enums::Connector::Paysafe => Self::Paysafe,
api_enums::Connector::Paystack => Self::Paystack,
api_enums::Connector::Payu => Self::Payu,
api_enums::Connector::Peachpayments => Self::Peachpayments,
api_models::enums::Connector::Placetopay => Self::Placetopay,
api_enums::Connector::Plaid => Self::Plaid,
api_enums::Connector::Powertranz => Self::Powertranz,
api_enums::Connector::Prophetpay => Self::Prophetpay,
api_enums::Connector::Rapyd => Self::Rapyd,
api_enums::Connector::Razorpay => Self::Razorpay,
api_enums::Connector::Recurly => Self::Recurly,
api_enums::Connector::Redsys => Self::Redsys,
api_enums::Connector::Santander => Self::Santander,
api_enums::Connector::Shift4 => Self::Shift4,
api_enums::Connector::Zift => Self::Zift,
api_enums::Connector::Silverflow => Self::Silverflow,
api_enums::Connector::Signifyd => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "signifyd is not a routable connector".to_string(),
})?
}
api_enums::Connector::Riskified => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "riskified is not a routable connector".to_string(),
})?
}
api_enums::Connector::Square => Self::Square,
api_enums::Connector::Stax => Self::Stax,
api_enums::Connector::Stripe => Self::Stripe,
api_enums::Connector::Stripebilling => Self::Stripebilling,
// api_enums::Connector::Thunes => Self::Thunes,
api_enums::Connector::Tesouro => Self::Tesouro,
api_enums::Connector::Tokenex => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "Tokenex is not a routable connector".to_string(),
})?
}
api_enums::Connector::Tokenio => Self::Tokenio,
api_enums::Connector::Trustpay => Self::Trustpay,
api_enums::Connector::Trustpayments => Self::Trustpayments,
api_enums::Connector::Tsys => Self::Tsys,
// api_enums::Connector::UnifiedAuthenticationService => {
// Self::UnifiedAuthenticationService
// }
api_enums::Connector::Vgs => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "Vgs is not a routable connector".to_string(),
})?
}
api_enums::Connector::Volt => Self::Volt,
api_enums::Connector::Wellsfargo => Self::Wellsfargo,
// api_enums::Connector::Wellsfargopayout => Self::Wellsfargopayout,
api_enums::Connector::Wise => Self::Wise,
api_enums::Connector::Worldline => Self::Worldline,
api_enums::Connector::Worldpay => Self::Worldpay,
api_enums::Connector::Worldpayvantiv => Self::Worldpayvantiv,
api_enums::Connector::Worldpayxml => Self::Worldpayxml,
api_enums::Connector::Xendit => Self::Xendit,
api_enums::Connector::Zen => Self::Zen,
api_enums::Connector::Zsl => Self::Zsl,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyBillingConnector => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "stripe_billing_test is not a routable connector".to_string(),
})?
}
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector1 => Self::DummyConnector1,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector2 => Self::DummyConnector2,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector3 => Self::DummyConnector3,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector4 => Self::DummyConnector4,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector5 => Self::DummyConnector5,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector6 => Self::DummyConnector6,
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyConnector7 => Self::DummyConnector7,
api_enums::Connector::Threedsecureio => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "threedsecureio is not a routable connector".to_string(),
})?
}
api_enums::Connector::Taxjar => {
Err(common_utils::errors::ValidationError::InvalidValue {
message: "Taxjar is not a routable connector".to_string(),
})?
}
api_enums::Connector::Phonepe => Self::Phonepe,
api_enums::Connector::Paytm => Self::Paytm,
})
}
}
| 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/payment_methods.rs | crates/router/src/types/payment_methods.rs | use std::fmt::Debug;
use api_models::enums as api_enums;
use cards::{CardNumber, NetworkToken};
#[cfg(feature = "v2")]
use common_types::primitive_wrappers;
#[cfg(feature = "v2")]
use common_utils::generate_id;
use common_utils::id_type;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payment_method_data::NetworkTokenDetails;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::types::api;
#[cfg(feature = "v2")]
use crate::{
consts,
types::{domain, storage},
};
#[cfg(feature = "v2")]
pub trait VaultingInterface {
fn get_vaulting_request_url() -> &'static str;
fn get_vaulting_flow_name() -> &'static str;
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultFingerprintRequest {
pub data: String,
pub key: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultFingerprintResponse {
pub fingerprint_id: String,
}
#[cfg(any(feature = "v2", feature = "tokenization_v2"))]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVaultRequest<D> {
pub entity_id: id_type::GlobalCustomerId,
pub vault_id: domain::VaultId,
pub data: D,
pub ttl: i64,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVaultResponse {
#[cfg(feature = "v2")]
pub entity_id: Option<id_type::GlobalCustomerId>,
#[cfg(feature = "v1")]
pub entity_id: Option<id_type::CustomerId>,
#[cfg(feature = "v2")]
pub vault_id: domain::VaultId,
#[cfg(feature = "v1")]
pub vault_id: hyperswitch_domain_models::router_response_types::VaultIdType,
pub fingerprint_id: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVault;
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetVaultFingerprint;
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultRetrieve;
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultDelete;
#[cfg(feature = "v2")]
impl VaultingInterface for AddVault {
fn get_vaulting_request_url() -> &'static str {
consts::ADD_VAULT_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_ADD_FLOW_TYPE
}
}
#[cfg(feature = "v2")]
impl VaultingInterface for GetVaultFingerprint {
fn get_vaulting_request_url() -> &'static str {
consts::VAULT_FINGERPRINT_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_GET_FINGERPRINT_FLOW_TYPE
}
}
#[cfg(feature = "v2")]
impl VaultingInterface for VaultRetrieve {
fn get_vaulting_request_url() -> &'static str {
consts::VAULT_RETRIEVE_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_RETRIEVE_FLOW_TYPE
}
}
#[cfg(feature = "v2")]
impl VaultingInterface for VaultDelete {
fn get_vaulting_request_url() -> &'static str {
consts::VAULT_DELETE_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_DELETE_FLOW_TYPE
}
}
#[cfg(feature = "v2")]
pub struct SavedPMLPaymentsInfo {
pub payment_intent: storage::PaymentIntent,
pub profile: domain::Profile,
pub collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
pub off_session_payment_flag: bool,
pub is_connector_agnostic_mit_enabled: bool,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultRetrieveRequest {
pub entity_id: id_type::GlobalCustomerId,
pub vault_id: domain::VaultId,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultRetrieveResponse {
pub data: domain::PaymentMethodVaultingData,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultDeleteRequest {
pub entity_id: id_type::GlobalCustomerId,
pub vault_id: domain::VaultId,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultDeleteResponse {
pub entity_id: id_type::GlobalCustomerId,
pub vault_id: domain::VaultId,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardData {
pub card_number: CardNumber,
pub exp_month: Secret<String>,
pub exp_year: Secret<String>,
pub card_security_code: Option<Secret<String>>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardData {
pub card_number: CardNumber,
pub exp_month: Secret<String>,
pub exp_year: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_security_code: Option<Secret<String>>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderData {
pub consent_id: String,
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderData {
pub consent_id: String,
pub customer_id: id_type::GlobalCustomerId,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiPayload {
pub service: String,
pub card_data: Secret<String>, //encrypted card data
pub order_data: OrderData,
pub should_send_token: bool,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct CardNetworkTokenResponse {
pub payload: Secret<String>, //encrypted payload
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardNetworkTokenResponsePayload {
pub card_brand: api_enums::CardNetwork,
pub card_fingerprint: Option<Secret<String>>,
pub card_reference: String,
pub correlation_id: String,
pub customer_id: String,
pub par: String,
pub token: CardNumber,
pub token_expiry_month: Secret<String>,
pub token_expiry_year: Secret<String>,
pub token_isin: String,
pub token_last_four: String,
pub token_status: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GenerateNetworkTokenResponsePayload {
pub card_brand: api_enums::CardNetwork,
pub card_fingerprint: Option<Secret<String>>,
pub card_reference: String,
pub correlation_id: String,
pub customer_id: String,
pub par: String,
pub token: NetworkToken,
pub token_expiry_month: Secret<String>,
pub token_expiry_year: Secret<String>,
pub token_isin: String,
pub token_last_four: String,
pub token_status: String,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize)]
pub struct GetCardToken {
pub card_reference: String,
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize)]
pub struct GetCardToken {
pub card_reference: String,
pub customer_id: id_type::GlobalCustomerId,
}
#[cfg(feature = "v1")]
#[derive(Debug, Deserialize)]
pub struct AuthenticationDetails {
pub cryptogram: Secret<String>,
pub token: NetworkToken,
}
#[cfg(feature = "v2")]
#[derive(Debug, Deserialize)]
pub struct AuthenticationDetails {
pub cryptogram: Secret<String>,
pub token: NetworkToken,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TokenDetails {
pub exp_month: Secret<String>,
pub exp_year: Secret<String>,
}
#[derive(Debug, Deserialize)]
pub struct TokenResponse {
pub authentication_details: AuthenticationDetails,
pub network: api_enums::CardNetwork,
pub token_details: TokenDetails,
pub eci: Option<String>,
pub card_type: Option<String>,
pub issuer: Option<String>,
pub nickname: Option<Secret<String>>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub struct DeleteCardToken {
pub card_reference: String, //network token requestor ref id
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
pub struct DeleteCardToken {
pub card_reference: String, //network token requestor ref id
pub customer_id: id_type::GlobalCustomerId,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DeleteNetworkTokenStatus {
Success,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct NetworkTokenErrorInfo {
pub code: String,
pub developer_message: String,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct NetworkTokenErrorResponse {
pub error_message: Option<String>,
pub error_info: NetworkTokenErrorInfo,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct DeleteNetworkTokenResponse {
pub status: DeleteNetworkTokenStatus,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckTokenStatus {
pub card_reference: String,
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckTokenStatus {
pub card_reference: String,
pub customer_id: id_type::GlobalCustomerId,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum TokenStatus {
Active,
Inactive,
Suspended,
Expired,
Deleted,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckTokenStatusResponsePayload {
pub token_status: TokenStatus,
pub token_expiry_month: Option<Secret<String>>,
pub token_expiry_year: Option<Secret<String>>,
pub card_last_four: Option<String>,
pub card_expiry_month: Option<Secret<String>>,
pub card_expiry_year: Option<Secret<String>>,
pub token_last_four: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct CheckTokenStatusResponse {
pub payload: CheckTokenStatusResponsePayload,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NetworkTokenRequestorData {
pub card_reference: String,
pub customer_id: String,
pub expiry_year: Secret<String>,
pub expiry_month: Secret<String>,
}
impl NetworkTokenRequestorData {
pub fn is_update_required(
&self,
data_stored_in_vault: api::payment_methods::CardDetailFromLocker,
) -> bool {
//if the expiry year and month in the vault are not the same as the ones in the requestor data,
//then we need to update the vault data with the updated expiry year and month.
!((data_stored_in_vault.expiry_year.unwrap_or_default() == self.expiry_year)
&& (data_stored_in_vault.expiry_month.unwrap_or_default() == self.expiry_month))
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NetworkTokenMetaDataUpdateBody {
pub token: NetworkTokenRequestorData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PanMetadataUpdateBody {
pub card: NetworkTokenRequestorData,
}
| 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/transformers.rs | crates/router/src/types/transformers.rs | use actix_web::http::header::HeaderMap;
use api_models::{
cards_info as card_info_types, enums as api_enums, gsm as gsm_api_types, payment_methods,
payments, routing::ConnectorSelection,
};
use common_utils::{
consts::X_HS_LATENCY,
crypto::Encryptable,
ext_traits::{Encode, StringExt, ValueExt},
fp_utils::when,
pii,
types::ConnectorTransactionIdTrait,
};
use diesel_models::enums as storage_enums;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::payments::payment_intent::CustomerData;
use masking::{ExposeInterface, PeekInterface, Secret};
use super::domain;
#[cfg(feature = "v2")]
use crate::db::storage::revenue_recovery_redis_operation;
use crate::{
core::errors,
headers::{
ACCEPT_LANGUAGE, BROWSER_NAME, X_APP_ID, X_CLIENT_PLATFORM, X_CLIENT_SOURCE,
X_CLIENT_VERSION, X_MERCHANT_DOMAIN, X_PAYMENT_CONFIRM_SOURCE, X_REDIRECT_URI,
X_REFERENCE_ID,
},
services::authentication::get_header_value_by_key,
types::{
self as router_types,
api::{self as api_types, routing as routing_types},
storage,
},
};
pub trait ForeignInto<T> {
fn foreign_into(self) -> T;
}
pub trait ForeignTryInto<T> {
type Error;
fn foreign_try_into(self) -> Result<T, Self::Error>;
}
pub trait ForeignFrom<F> {
fn foreign_from(from: F) -> Self;
}
pub trait ForeignTryFrom<F>: Sized {
type Error;
fn foreign_try_from(from: F) -> Result<Self, Self::Error>;
}
impl<F, T> ForeignInto<T> for F
where
T: ForeignFrom<F>,
{
fn foreign_into(self) -> T {
T::foreign_from(self)
}
}
impl<F, T> ForeignTryInto<T> for F
where
T: ForeignTryFrom<F>,
{
type Error = <T as ForeignTryFrom<F>>::Error;
fn foreign_try_into(self) -> Result<T, Self::Error> {
T::foreign_try_from(self)
}
}
impl ForeignFrom<api_models::refunds::RefundType> for storage_enums::RefundType {
fn foreign_from(item: api_models::refunds::RefundType) -> Self {
match item {
api_models::refunds::RefundType::Instant => Self::InstantRefund,
api_models::refunds::RefundType::Scheduled => Self::RegularRefund,
}
}
}
#[cfg(feature = "v1")]
impl
ForeignFrom<(
Option<payment_methods::CardDetailFromLocker>,
domain::PaymentMethod,
)> for payment_methods::PaymentMethodResponse
{
fn foreign_from(
(card_details, item): (
Option<payment_methods::CardDetailFromLocker>,
domain::PaymentMethod,
),
) -> Self {
Self {
merchant_id: item.merchant_id.to_owned(),
customer_id: Some(item.customer_id.to_owned()),
payment_method_id: item.get_id().clone(),
payment_method: item.get_payment_method_type(),
payment_method_type: item.get_payment_method_subtype(),
card: card_details,
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: None,
metadata: item.metadata,
created: Some(item.created_at),
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: None,
client_secret: item.client_secret,
}
}
}
#[cfg(feature = "v2")]
impl
ForeignFrom<(
Option<payment_methods::CardDetailFromLocker>,
domain::PaymentMethod,
)> for payment_methods::PaymentMethodResponse
{
fn foreign_from(
(card_details, item): (
Option<payment_methods::CardDetailFromLocker>,
domain::PaymentMethod,
),
) -> Self {
todo!()
}
}
// TODO: remove this usage in v1 code
impl ForeignFrom<storage_enums::AttemptStatus> for storage_enums::IntentStatus {
fn foreign_from(s: storage_enums::AttemptStatus) -> Self {
Self::from(s)
}
}
impl ForeignTryFrom<storage_enums::AttemptStatus> for storage_enums::CaptureStatus {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
attempt_status: storage_enums::AttemptStatus,
) -> errors::RouterResult<Self> {
match attempt_status {
storage_enums::AttemptStatus::Charged
| storage_enums::AttemptStatus::PartialCharged | storage_enums::AttemptStatus::IntegrityFailure => Ok(Self::Charged),
storage_enums::AttemptStatus::Pending
| storage_enums::AttemptStatus::CaptureInitiated => Ok(Self::Pending),
storage_enums::AttemptStatus::Failure
| storage_enums::AttemptStatus::CaptureFailed => Ok(Self::Failed),
storage_enums::AttemptStatus::Started
| storage_enums::AttemptStatus::AuthenticationFailed
| storage_enums::AttemptStatus::RouterDeclined
| storage_enums::AttemptStatus::AuthenticationPending
| storage_enums::AttemptStatus::AuthenticationSuccessful
| storage_enums::AttemptStatus::Authorized
| storage_enums::AttemptStatus::AuthorizationFailed
| storage_enums::AttemptStatus::Authorizing
| storage_enums::AttemptStatus::CodInitiated
| storage_enums::AttemptStatus::Voided
| storage_enums::AttemptStatus::VoidedPostCharge
| storage_enums::AttemptStatus::VoidInitiated
| storage_enums::AttemptStatus::VoidFailed
| storage_enums::AttemptStatus::AutoRefunded
| storage_enums::AttemptStatus::Unresolved
| storage_enums::AttemptStatus::PaymentMethodAwaited
| storage_enums::AttemptStatus::ConfirmationAwaited
| storage_enums::AttemptStatus::DeviceDataCollectionPending
| storage_enums::AttemptStatus::PartiallyAuthorized
| storage_enums::AttemptStatus::PartialChargedAndChargeable | storage_enums::AttemptStatus::Expired => {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "AttemptStatus must be one of these for multiple partial captures [Charged, PartialCharged, Pending, CaptureInitiated, Failure, CaptureFailed]".into(),
}.into())
}
}
}
}
impl ForeignFrom<payments::MandateType> for storage_enums::MandateDataType {
fn foreign_from(from: payments::MandateType) -> Self {
match from {
payments::MandateType::SingleUse(inner) => Self::SingleUse(inner.foreign_into()),
payments::MandateType::MultiUse(inner) => {
Self::MultiUse(inner.map(ForeignInto::foreign_into))
}
}
}
}
impl ForeignFrom<storage_enums::MandateDataType> for payments::MandateType {
fn foreign_from(from: storage_enums::MandateDataType) -> Self {
match from {
storage_enums::MandateDataType::SingleUse(inner) => {
Self::SingleUse(inner.foreign_into())
}
storage_enums::MandateDataType::MultiUse(inner) => {
Self::MultiUse(inner.map(ForeignInto::foreign_into))
}
}
}
}
impl ForeignFrom<storage_enums::MandateAmountData> for payments::MandateAmountData {
fn foreign_from(from: storage_enums::MandateAmountData) -> Self {
Self {
amount: from.amount,
currency: from.currency,
start_date: from.start_date,
end_date: from.end_date,
metadata: from.metadata,
}
}
}
// TODO: remove foreign from since this conversion won't be needed in the router crate once data models is treated as a single & primary source of truth for structure information
impl ForeignFrom<payments::MandateData> for hyperswitch_domain_models::mandates::MandateData {
fn foreign_from(d: payments::MandateData) -> Self {
Self {
customer_acceptance: d.customer_acceptance,
mandate_type: d.mandate_type.map(|d| match d {
payments::MandateType::MultiUse(Some(i)) => {
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(
hyperswitch_domain_models::mandates::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
end_date: i.end_date,
metadata: i.metadata,
},
))
}
payments::MandateType::SingleUse(i) => {
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(
hyperswitch_domain_models::mandates::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
end_date: i.end_date,
metadata: i.metadata,
},
)
}
payments::MandateType::MultiUse(None) => {
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None)
}
}),
update_mandate_id: d.update_mandate_id,
}
}
}
impl ForeignFrom<payments::MandateAmountData> for storage_enums::MandateAmountData {
fn foreign_from(from: payments::MandateAmountData) -> Self {
Self {
amount: from.amount,
currency: from.currency,
start_date: from.start_date,
end_date: from.end_date,
metadata: from.metadata,
}
}
}
impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod {
fn foreign_from(payment_method_type: api_enums::PaymentMethodType) -> Self {
match payment_method_type {
api_enums::PaymentMethodType::AmazonPay
| api_enums::PaymentMethodType::Paysera
| api_enums::PaymentMethodType::Skrill
| api_enums::PaymentMethodType::ApplePay
| api_enums::PaymentMethodType::GooglePay
| api_enums::PaymentMethodType::Paypal
| api_enums::PaymentMethodType::AliPay
| api_enums::PaymentMethodType::AliPayHk
| api_enums::PaymentMethodType::Dana
| api_enums::PaymentMethodType::MbWay
| api_enums::PaymentMethodType::MobilePay
| api_enums::PaymentMethodType::Paze
| api_enums::PaymentMethodType::SamsungPay
| api_enums::PaymentMethodType::Twint
| api_enums::PaymentMethodType::Vipps
| api_enums::PaymentMethodType::TouchNGo
| api_enums::PaymentMethodType::Swish
| api_enums::PaymentMethodType::WeChatPay
| api_enums::PaymentMethodType::GoPay
| api_enums::PaymentMethodType::Gcash
| api_enums::PaymentMethodType::Momo
| api_enums::PaymentMethodType::Cashapp
| api_enums::PaymentMethodType::KakaoPay
| api_enums::PaymentMethodType::Venmo
| api_enums::PaymentMethodType::Mifinity
| api_enums::PaymentMethodType::RevolutPay
| api_enums::PaymentMethodType::Bluecode => Self::Wallet,
api_enums::PaymentMethodType::Affirm
| api_enums::PaymentMethodType::Alma
| api_enums::PaymentMethodType::AfterpayClearpay
| api_enums::PaymentMethodType::Klarna
| api_enums::PaymentMethodType::Flexiti
| api_enums::PaymentMethodType::PayBright
| api_enums::PaymentMethodType::Atome
| api_enums::PaymentMethodType::Walley
| api_enums::PaymentMethodType::Breadpay
| api_enums::PaymentMethodType::Payjustnow => Self::PayLater,
api_enums::PaymentMethodType::Giropay
| api_enums::PaymentMethodType::Ideal
| api_enums::PaymentMethodType::Sofort
| api_enums::PaymentMethodType::Eft
| api_enums::PaymentMethodType::Eps
| api_enums::PaymentMethodType::BancontactCard
| api_enums::PaymentMethodType::Blik
| api_enums::PaymentMethodType::LocalBankRedirect
| api_enums::PaymentMethodType::OnlineBankingThailand
| api_enums::PaymentMethodType::OnlineBankingCzechRepublic
| api_enums::PaymentMethodType::OnlineBankingFinland
| api_enums::PaymentMethodType::OnlineBankingFpx
| api_enums::PaymentMethodType::OnlineBankingPoland
| api_enums::PaymentMethodType::OnlineBankingSlovakia
| api_enums::PaymentMethodType::OpenBankingUk
| api_enums::PaymentMethodType::OpenBankingPIS
| api_enums::PaymentMethodType::Przelewy24
| api_enums::PaymentMethodType::Trustly
| api_enums::PaymentMethodType::Bizum
| api_enums::PaymentMethodType::Interac
| api_enums::PaymentMethodType::OpenBanking => Self::BankRedirect,
api_enums::PaymentMethodType::UpiCollect
| api_enums::PaymentMethodType::UpiIntent
| api_enums::PaymentMethodType::UpiQr => Self::Upi,
api_enums::PaymentMethodType::CryptoCurrency => Self::Crypto,
api_enums::PaymentMethodType::Ach
| api_enums::PaymentMethodType::Sepa
| api_enums::PaymentMethodType::SepaGuarenteedDebit
| api_enums::PaymentMethodType::Bacs
| api_enums::PaymentMethodType::Becs => Self::BankDebit,
api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
Self::Card
}
#[cfg(feature = "v2")]
api_enums::PaymentMethodType::Card => Self::Card,
api_enums::PaymentMethodType::Evoucher
| api_enums::PaymentMethodType::ClassicReward => Self::Reward,
api_enums::PaymentMethodType::Boleto
| api_enums::PaymentMethodType::Efecty
| api_enums::PaymentMethodType::PagoEfectivo
| api_enums::PaymentMethodType::RedCompra
| api_enums::PaymentMethodType::Alfamart
| api_enums::PaymentMethodType::Indomaret
| api_enums::PaymentMethodType::Oxxo
| api_enums::PaymentMethodType::SevenEleven
| api_enums::PaymentMethodType::Lawson
| api_enums::PaymentMethodType::MiniStop
| api_enums::PaymentMethodType::FamilyMart
| api_enums::PaymentMethodType::Seicomart
| api_enums::PaymentMethodType::PayEasy
| api_enums::PaymentMethodType::RedPagos => Self::Voucher,
api_enums::PaymentMethodType::Pse
| api_enums::PaymentMethodType::Multibanco
| api_enums::PaymentMethodType::PermataBankTransfer
| api_enums::PaymentMethodType::BcaBankTransfer
| api_enums::PaymentMethodType::BniVa
| api_enums::PaymentMethodType::BriVa
| api_enums::PaymentMethodType::CimbVa
| api_enums::PaymentMethodType::DanamonVa
| api_enums::PaymentMethodType::MandiriVa
| api_enums::PaymentMethodType::LocalBankTransfer
| api_enums::PaymentMethodType::InstantBankTransfer
| api_enums::PaymentMethodType::InstantBankTransferFinland
| api_enums::PaymentMethodType::InstantBankTransferPoland
| api_enums::PaymentMethodType::SepaBankTransfer
| api_enums::PaymentMethodType::IndonesianBankTransfer
| api_enums::PaymentMethodType::Pix => Self::BankTransfer,
api_enums::PaymentMethodType::Givex
| api_enums::PaymentMethodType::PaySafeCard
| api_enums::PaymentMethodType::BhnCardNetwork => Self::GiftCard,
api_enums::PaymentMethodType::Benefit
| api_enums::PaymentMethodType::Knet
| api_enums::PaymentMethodType::MomoAtm
| api_enums::PaymentMethodType::CardRedirect => Self::CardRedirect,
api_enums::PaymentMethodType::Fps
| api_enums::PaymentMethodType::DuitNow
| api_enums::PaymentMethodType::PromptPay
| api_enums::PaymentMethodType::VietQr => Self::RealTimePayment,
api_enums::PaymentMethodType::DirectCarrierBilling => Self::MobilePayment,
api_enums::PaymentMethodType::NetworkToken => Self::NetworkToken,
}
}
}
impl ForeignTryFrom<payments::PaymentMethodData> for api_enums::PaymentMethod {
type Error = errors::ApiErrorResponse;
fn foreign_try_from(
payment_method_data: payments::PaymentMethodData,
) -> Result<Self, Self::Error> {
match payment_method_data {
payments::PaymentMethodData::Card(..) | payments::PaymentMethodData::CardToken(..) => {
Ok(Self::Card)
}
payments::PaymentMethodData::Wallet(..) => Ok(Self::Wallet),
payments::PaymentMethodData::PayLater(..) => Ok(Self::PayLater),
payments::PaymentMethodData::BankRedirect(..) => Ok(Self::BankRedirect),
payments::PaymentMethodData::BankDebit(..) => Ok(Self::BankDebit),
payments::PaymentMethodData::BankTransfer(..) => Ok(Self::BankTransfer),
payments::PaymentMethodData::Crypto(..) => Ok(Self::Crypto),
payments::PaymentMethodData::Reward => Ok(Self::Reward),
payments::PaymentMethodData::RealTimePayment(..) => Ok(Self::RealTimePayment),
payments::PaymentMethodData::Upi(..) => Ok(Self::Upi),
payments::PaymentMethodData::Voucher(..) => Ok(Self::Voucher),
payments::PaymentMethodData::GiftCard(..) => Ok(Self::GiftCard),
payments::PaymentMethodData::CardRedirect(..) => Ok(Self::CardRedirect),
payments::PaymentMethodData::OpenBanking(..) => Ok(Self::OpenBanking),
payments::PaymentMethodData::MobilePayment(..) => Ok(Self::MobilePayment),
payments::PaymentMethodData::MandatePayment => {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: ("Mandate payments cannot have payment_method_data field".to_string()),
})
}
payments::PaymentMethodData::NetworkToken(..) => Ok(Self::NetworkToken),
}
}
}
impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::RefundStatus {
type Error = errors::ValidationError;
fn foreign_try_from(
value: api_models::webhooks::IncomingWebhookEvent,
) -> Result<Self, Self::Error> {
match value {
api_models::webhooks::IncomingWebhookEvent::RefundSuccess => Ok(Self::Success),
api_models::webhooks::IncomingWebhookEvent::RefundFailure => Ok(Self::Failure),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "incoming_webhook_event_type",
}),
}
}
}
impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for api_enums::RelayStatus {
type Error = errors::ValidationError;
fn foreign_try_from(
value: api_models::webhooks::IncomingWebhookEvent,
) -> Result<Self, Self::Error> {
match value {
api_models::webhooks::IncomingWebhookEvent::RefundSuccess => Ok(Self::Success),
api_models::webhooks::IncomingWebhookEvent::RefundFailure => Ok(Self::Failure),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "incoming_webhook_event_type",
}),
}
}
}
#[cfg(feature = "payouts")]
impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::PayoutStatus {
type Error = errors::ValidationError;
fn foreign_try_from(
value: api_models::webhooks::IncomingWebhookEvent,
) -> Result<Self, Self::Error> {
match value {
api_models::webhooks::IncomingWebhookEvent::PayoutSuccess => Ok(Self::Success),
api_models::webhooks::IncomingWebhookEvent::PayoutFailure => Ok(Self::Failed),
api_models::webhooks::IncomingWebhookEvent::PayoutCancelled => Ok(Self::Cancelled),
api_models::webhooks::IncomingWebhookEvent::PayoutProcessing => Ok(Self::Pending),
api_models::webhooks::IncomingWebhookEvent::PayoutCreated => Ok(Self::Initiated),
api_models::webhooks::IncomingWebhookEvent::PayoutExpired => Ok(Self::Expired),
api_models::webhooks::IncomingWebhookEvent::PayoutReversed => Ok(Self::Reversed),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "incoming_webhook_event_type",
}),
}
}
}
impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::MandateStatus {
type Error = errors::ValidationError;
fn foreign_try_from(
value: api_models::webhooks::IncomingWebhookEvent,
) -> Result<Self, Self::Error> {
match value {
api_models::webhooks::IncomingWebhookEvent::MandateActive => Ok(Self::Active),
api_models::webhooks::IncomingWebhookEvent::MandateRevoked => Ok(Self::Revoked),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "incoming_webhook_event_type",
}),
}
}
}
impl ForeignFrom<storage::Config> for api_types::Config {
fn foreign_from(config: storage::Config) -> Self {
Self {
key: config.key,
value: config.config,
}
}
}
impl ForeignFrom<&api_types::ConfigUpdate> for storage::ConfigUpdate {
fn foreign_from(config: &api_types::ConfigUpdate) -> Self {
Self::Update {
config: Some(config.value.clone()),
}
}
}
impl From<&domain::Address> for hyperswitch_domain_models::address::Address {
fn from(address: &domain::Address) -> Self {
// If all the fields of address are none, then pass the address as None
let address_details = if address.city.is_none()
&& address.line1.is_none()
&& address.line2.is_none()
&& address.line3.is_none()
&& address.state.is_none()
&& address.country.is_none()
&& address.zip.is_none()
&& address.first_name.is_none()
&& address.last_name.is_none()
{
None
} else {
Some(hyperswitch_domain_models::address::AddressDetails {
city: address.city.clone(),
country: address.country,
line1: address.line1.clone().map(Encryptable::into_inner),
line2: address.line2.clone().map(Encryptable::into_inner),
line3: address.line3.clone().map(Encryptable::into_inner),
state: address.state.clone().map(Encryptable::into_inner),
zip: address.zip.clone().map(Encryptable::into_inner),
first_name: address.first_name.clone().map(Encryptable::into_inner),
last_name: address.last_name.clone().map(Encryptable::into_inner),
origin_zip: address.origin_zip.clone().map(Encryptable::into_inner),
})
};
// If all the fields of phone are none, then pass the phone as None
let phone_details = if address.phone_number.is_none() && address.country_code.is_none() {
None
} else {
Some(hyperswitch_domain_models::address::PhoneDetails {
number: address.phone_number.clone().map(Encryptable::into_inner),
country_code: address.country_code.clone(),
})
};
Self {
address: address_details,
phone: phone_details,
email: address.email.clone().map(pii::Email::from),
}
}
}
impl ForeignFrom<domain::Address> for api_types::Address {
fn foreign_from(address: domain::Address) -> Self {
// If all the fields of address are none, then pass the address as None
let address_details = if address.city.is_none()
&& address.line1.is_none()
&& address.line2.is_none()
&& address.line3.is_none()
&& address.state.is_none()
&& address.country.is_none()
&& address.zip.is_none()
&& address.first_name.is_none()
&& address.last_name.is_none()
{
None
} else {
Some(api_types::AddressDetails {
city: address.city.clone(),
country: address.country,
line1: address.line1.clone().map(Encryptable::into_inner),
line2: address.line2.clone().map(Encryptable::into_inner),
line3: address.line3.clone().map(Encryptable::into_inner),
state: address.state.clone().map(Encryptable::into_inner),
zip: address.zip.clone().map(Encryptable::into_inner),
first_name: address.first_name.clone().map(Encryptable::into_inner),
last_name: address.last_name.clone().map(Encryptable::into_inner),
origin_zip: address.origin_zip.clone().map(Encryptable::into_inner),
})
};
// If all the fields of phone are none, then pass the phone as None
let phone_details = if address.phone_number.is_none() && address.country_code.is_none() {
None
} else {
Some(api_types::PhoneDetails {
number: address.phone_number.clone().map(Encryptable::into_inner),
country_code: address.country_code.clone(),
})
};
Self {
address: address_details,
phone: phone_details,
email: address.email.clone().map(pii::Email::from),
}
}
}
impl
ForeignFrom<(
diesel_models::api_keys::ApiKey,
crate::core::api_keys::PlaintextApiKey,
)> for api_models::api_keys::CreateApiKeyResponse
{
fn foreign_from(
item: (
diesel_models::api_keys::ApiKey,
crate::core::api_keys::PlaintextApiKey,
),
) -> Self {
use masking::StrongSecret;
let (api_key, plaintext_api_key) = item;
Self {
key_id: api_key.key_id,
merchant_id: api_key.merchant_id,
name: api_key.name,
description: api_key.description,
api_key: StrongSecret::from(plaintext_api_key.peek().to_owned()),
created: api_key.created_at,
expiration: api_key.expires_at.into(),
}
}
}
impl ForeignFrom<diesel_models::api_keys::ApiKey> for api_models::api_keys::RetrieveApiKeyResponse {
fn foreign_from(api_key: diesel_models::api_keys::ApiKey) -> Self {
Self {
key_id: api_key.key_id,
merchant_id: api_key.merchant_id,
name: api_key.name,
description: api_key.description,
prefix: api_key.prefix.into(),
created: api_key.created_at,
expiration: api_key.expires_at.into(),
}
}
}
impl ForeignFrom<api_models::api_keys::UpdateApiKeyRequest>
for diesel_models::api_keys::ApiKeyUpdate
{
fn foreign_from(api_key: api_models::api_keys::UpdateApiKeyRequest) -> Self {
Self::Update {
name: api_key.name,
description: api_key.description,
expires_at: api_key.expiration.map(Into::into),
last_used: None,
}
}
}
impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::DisputeStatus {
type Error = errors::ValidationError;
fn foreign_try_from(
value: api_models::webhooks::IncomingWebhookEvent,
) -> Result<Self, Self::Error> {
match value {
api_models::webhooks::IncomingWebhookEvent::DisputeOpened => Ok(Self::DisputeOpened),
api_models::webhooks::IncomingWebhookEvent::DisputeExpired => Ok(Self::DisputeExpired),
api_models::webhooks::IncomingWebhookEvent::DisputeAccepted => {
Ok(Self::DisputeAccepted)
}
api_models::webhooks::IncomingWebhookEvent::DisputeCancelled => {
Ok(Self::DisputeCancelled)
}
api_models::webhooks::IncomingWebhookEvent::DisputeChallenged => {
Ok(Self::DisputeChallenged)
}
api_models::webhooks::IncomingWebhookEvent::DisputeWon => Ok(Self::DisputeWon),
api_models::webhooks::IncomingWebhookEvent::DisputeLost => Ok(Self::DisputeLost),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "incoming_webhook_event",
}),
}
}
}
impl ForeignFrom<storage::Dispute> for api_models::disputes::DisputeResponse {
fn foreign_from(dispute: storage::Dispute) -> Self {
Self {
dispute_id: dispute.dispute_id,
payment_id: dispute.payment_id,
attempt_id: dispute.attempt_id,
amount: dispute.amount,
currency: dispute.dispute_currency.unwrap_or(
dispute
.currency
.to_uppercase()
.parse_enum("Currency")
.unwrap_or_default(),
),
dispute_stage: dispute.dispute_stage,
dispute_status: dispute.dispute_status,
connector: dispute.connector,
connector_status: dispute.connector_status,
connector_dispute_id: dispute.connector_dispute_id,
connector_reason: dispute.connector_reason,
connector_reason_code: dispute.connector_reason_code,
challenge_required_by: dispute.challenge_required_by,
connector_created_at: dispute.connector_created_at,
connector_updated_at: dispute.connector_updated_at,
created_at: dispute.created_at,
profile_id: dispute.profile_id,
merchant_connector_id: dispute.merchant_connector_id,
}
}
}
impl ForeignFrom<storage::Authorization> for payments::IncrementalAuthorizationResponse {
fn foreign_from(authorization: storage::Authorization) -> Self {
Self {
authorization_id: authorization.authorization_id,
amount: authorization.amount,
status: authorization.status,
error_code: authorization.error_code,
error_message: authorization.error_message,
previously_authorized_amount: authorization.previously_authorized_amount,
}
}
}
impl
ForeignFrom<
&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,
> for payments::ExternalAuthenticationDetailsResponse
{
fn foreign_from(
authn_store: &hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,
) -> Self {
let authn_data = &authn_store.authentication;
let version = authn_data
.maximum_supported_version
.as_ref()
.map(|version| version.to_string());
Self {
authentication_flow: authn_data.authentication_type,
electronic_commerce_indicator: authn_data.eci.clone(),
status: authn_data.authentication_status,
ds_transaction_id: authn_data.threeds_server_transaction_id.clone(),
version,
error_code: authn_data.error_code.clone(),
error_message: authn_data.error_message.clone(),
}
}
}
impl ForeignFrom<storage::Dispute> for api_models::disputes::DisputeResponsePaymentsRetrieve {
fn foreign_from(dispute: storage::Dispute) -> Self {
Self {
dispute_id: dispute.dispute_id,
dispute_stage: dispute.dispute_stage,
dispute_status: dispute.dispute_status,
connector_status: dispute.connector_status,
connector_dispute_id: dispute.connector_dispute_id,
connector_reason: dispute.connector_reason,
connector_reason_code: dispute.connector_reason_code,
challenge_required_by: dispute.challenge_required_by,
connector_created_at: dispute.connector_created_at,
connector_updated_at: dispute.connector_updated_at,
created_at: dispute.created_at,
}
}
}
impl ForeignFrom<storage::FileMetadata> for api_models::files::FileMetadataResponse {
fn foreign_from(file_metadata: storage::FileMetadata) -> Self {
Self {
file_id: file_metadata.file_id,
file_name: file_metadata.file_name,
file_size: file_metadata.file_size,
file_type: file_metadata.file_type,
available: file_metadata.available,
}
}
}
| 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/authentication.rs | crates/router/src/types/authentication.rs | pub use hyperswitch_domain_models::{
router_request_types::authentication::{
AcquirerDetails, AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData,
ConnectorPostAuthenticationRequestData, PreAuthNRequestData, PreAuthenticationData,
},
router_response_types::AuthenticationResponseData,
};
use super::{api, RouterData};
use crate::services;
pub type PreAuthNRouterData =
RouterData<api::PreAuthentication, PreAuthNRequestData, AuthenticationResponseData>;
pub type PreAuthNVersionCallRouterData =
RouterData<api::PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData>;
pub type ConnectorAuthenticationRouterData =
RouterData<api::Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData>;
pub type ConnectorPostAuthenticationRouterData = RouterData<
api::PostAuthentication,
ConnectorPostAuthenticationRequestData,
AuthenticationResponseData,
>;
pub type ConnectorAuthenticationType = dyn services::ConnectorIntegration<
api::Authentication,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>;
pub type ConnectorPostAuthenticationType = dyn services::ConnectorIntegration<
api::PostAuthentication,
ConnectorPostAuthenticationRequestData,
AuthenticationResponseData,
>;
pub type ConnectorPreAuthenticationType = dyn services::ConnectorIntegration<
api::PreAuthentication,
PreAuthNRequestData,
AuthenticationResponseData,
>;
pub type ConnectorPreAuthenticationVersionCallType = dyn services::ConnectorIntegration<
api::PreAuthenticationVersionCall,
PreAuthNRequestData,
AuthenticationResponseData,
>;
| 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.rs | crates/router/src/types/domain.rs | pub mod behaviour {
pub use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion};
}
mod payment_attempt {
pub use hyperswitch_domain_models::payments::payment_attempt::*;
}
mod merchant_account {
pub use hyperswitch_domain_models::merchant_account::*;
}
#[cfg(feature = "v2")]
mod business_profile {
pub use hyperswitch_domain_models::business_profile::{
Profile, ProfileGeneralUpdate, ProfileSetter, ProfileUpdate,
};
}
#[cfg(feature = "v1")]
mod business_profile {
pub use hyperswitch_domain_models::business_profile::{
ExternalVaultDetails, Profile, ProfileGeneralUpdate, ProfileSetter, ProfileUpdate,
};
}
mod platform {
pub use hyperswitch_domain_models::platform::{Initiator, Platform, Processor, Provider};
}
mod customers {
pub use hyperswitch_domain_models::customer::*;
}
pub mod callback_mapper {
pub use hyperswitch_domain_models::callback_mapper::CallbackMapper;
}
#[cfg(feature = "v2")]
mod split_payments {
pub use hyperswitch_domain_models::payments::split_payments::*;
}
pub use customers::*;
pub use merchant_account::*;
mod address;
mod event;
mod merchant_connector_account;
mod merchant_key_store {
pub use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
}
pub use hyperswitch_domain_models::bulk_tokenization::*;
pub mod payment_methods {
pub use hyperswitch_domain_models::payment_methods::*;
}
pub mod consts {
pub use hyperswitch_domain_models::consts::*;
}
pub mod payment_method_data {
pub use hyperswitch_domain_models::payment_method_data::*;
}
pub mod authentication {
pub use hyperswitch_domain_models::router_request_types::authentication::*;
}
#[cfg(feature = "v2")]
pub mod vault {
pub use hyperswitch_domain_models::vault::*;
}
#[cfg(feature = "v2")]
pub mod tokenization {
pub use hyperswitch_domain_models::tokenization::*;
}
mod routing {
pub use hyperswitch_domain_models::routing::*;
}
pub mod payments;
pub mod types;
#[cfg(feature = "olap")]
pub mod user;
pub mod user_key_store;
pub use address::*;
pub use business_profile::*;
pub use callback_mapper::*;
pub use consts::*;
pub use event::*;
pub use merchant_connector_account::*;
pub use merchant_key_store::*;
pub use payment_attempt::*;
pub use payment_method_data::*;
pub use payment_methods::*;
pub use platform::*;
pub use routing::*;
#[cfg(feature = "v2")]
pub use split_payments::*;
#[cfg(feature = "v2")]
pub use tokenization::*;
#[cfg(feature = "olap")]
pub use user::*;
pub use user_key_store::*;
#[cfg(feature = "v2")]
pub use vault::*;
| 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/api_keys.rs | crates/router/src/types/storage/api_keys.rs | #[cfg(feature = "email")]
pub use diesel_models::api_keys::ApiKeyExpiryTrackingData;
pub use diesel_models::api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, HashedApiKey};
| 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/locker_mock_up.rs | crates/router/src/types/storage/locker_mock_up.rs | pub use diesel_models::locker_mock_up::{LockerMockUp, LockerMockUpNew};
| 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.rs | crates/router/src/types/storage/user.rs | pub use diesel_models::user::*;
| 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.